blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20f242be89e79cc7c3dff948601e9ed34bd9f875
| 23,983,097,442,084 |
2c081f751de3747a99467a08f105197f007c2c47
|
/src/test/java/FirstMavenProject/FirstMavenProject/LoginFeature.java
|
7f94c17d2c5d4185f5036d4268ff394372c578c8
|
[] |
no_license
|
sanchalk/FirstMavenProject
|
https://github.com/sanchalk/FirstMavenProject
|
ed50f16ffda58bf03aa0a5a8d57a77aa859fe2e0
|
b578a02ef66109b022fc733f1648bcdbdc9e509c
|
refs/heads/master
| 2021-01-22T19:03:49.100000 | 2017-03-17T04:32:54 | 2017-03-17T04:32:54 | 85,152,355 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package FirstMavenProject.FirstMavenProject;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import utility.Constant;
public class LoginFeature
{
WebDriver driver;
@BeforeMethod
public void setup()
{
LaunchBrowser launchbrowser = new LaunchBrowser();
driver=launchbrowser.selectBrowser(Constant.browsername);
driver.get(Constant.baseurl);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test(description="validating login with Valid Credentials")
public void Test1()
{
LoginPage loginpage = new LoginPage(driver);
String val= loginpage.validLogin(Constant.Actitimeusername, Constant.password);
Assert.assertTrue(val.contains("Enter"),"fail to login");
}
@Test(description="validating login with In-Valid Credentials")
public void Test2()
{
LoginPage loginpage = new LoginPage(driver);
String val= loginpage.inValidLogin(Constant.Actitimeusername, Constant.password);
Assert.assertTrue(val.contains("Please try again."),"may be login");
}
@AfterMethod
public void teardown()
{
driver.manage().deleteAllCookies();
driver.quit();
}
}
|
UTF-8
|
Java
| 1,322 |
java
|
LoginFeature.java
|
Java
|
[] | null |
[] |
package FirstMavenProject.FirstMavenProject;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import utility.Constant;
public class LoginFeature
{
WebDriver driver;
@BeforeMethod
public void setup()
{
LaunchBrowser launchbrowser = new LaunchBrowser();
driver=launchbrowser.selectBrowser(Constant.browsername);
driver.get(Constant.baseurl);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test(description="validating login with Valid Credentials")
public void Test1()
{
LoginPage loginpage = new LoginPage(driver);
String val= loginpage.validLogin(Constant.Actitimeusername, Constant.password);
Assert.assertTrue(val.contains("Enter"),"fail to login");
}
@Test(description="validating login with In-Valid Credentials")
public void Test2()
{
LoginPage loginpage = new LoginPage(driver);
String val= loginpage.inValidLogin(Constant.Actitimeusername, Constant.password);
Assert.assertTrue(val.contains("Please try again."),"may be login");
}
@AfterMethod
public void teardown()
{
driver.manage().deleteAllCookies();
driver.quit();
}
}
| 1,322 | 0.76702 | 0.763994 | 49 | 25.979591 | 24.436916 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.530612 | false | false |
10
|
05ff9f687b7b87dc032e435417734a3549bf72ac
| 33,715,493,335,857 |
f20a2e74120f71d990ac368bdf783353daafafb0
|
/src/main/java/com/ly/springBoot/action/designPattern/Structural/桥接模式/WriteImpl.java
|
933beddaba4b83e478524c26a916ecddb1b84f75
|
[] |
no_license
|
Eee-Liu/springBoot
|
https://github.com/Eee-Liu/springBoot
|
9baa99b4137a7092eef98809361d88ec9dfdd67f
|
cb7b2069e4c449b531615b36f85f3be5658ccbe5
|
refs/heads/master
| 2022-06-22T03:48:25.895000 | 2020-08-30T07:47:58 | 2020-08-30T07:47:58 | 134,051,167 | 1 | 0 | null | false | 2022-06-17T01:46:25 | 2018-05-19T10:12:02 | 2020-08-30T07:48:12 | 2022-06-17T01:46:25 | 503 | 1 | 0 | 2 |
Java
| false | false |
package com.ly.springBoot.action.designPattern.Structural.桥接模式;
/**
* @Author: LiuYi
* @Description: 抽象部分,负责输出
* @Date: Created in 2018/12/7 17:32
*/
public interface WriteImpl {
public void writeFile();
}
|
UTF-8
|
Java
| 239 |
java
|
WriteImpl.java
|
Java
|
[
{
"context": "on.designPattern.Structural.桥接模式;\n\n/**\n * @Author: LiuYi\n * @Description: 抽象部分,负责输出\n * @Date: Created in 2",
"end": 86,
"score": 0.9991704821586609,
"start": 81,
"tag": "NAME",
"value": "LiuYi"
}
] | null |
[] |
package com.ly.springBoot.action.designPattern.Structural.桥接模式;
/**
* @Author: LiuYi
* @Description: 抽象部分,负责输出
* @Date: Created in 2018/12/7 17:32
*/
public interface WriteImpl {
public void writeFile();
}
| 239 | 0.706977 | 0.655814 | 10 | 20.5 | 19.011839 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false |
10
|
5c02f0fdddefa095481a42ff88ebb58d15fb1e05
| 31,241,592,155,268 |
d85a640c17af50ae884f05070d44b9e5976e4236
|
/crawlers/src/main/java/luccasdev/idwall/desafio/crawler/service/RedditThreadService.java
|
790ee369458f7111150e565f3f64b12da18ab1cd
|
[] |
no_license
|
luccasdev/desafios
|
https://github.com/luccasdev/desafios
|
646f26edc186d52eb085332fb18edcf748d020e6
|
d1ed055ddc147579b846634d2dfb35306e7caf89
|
refs/heads/master
| 2022-12-12T07:39:21.414000 | 2020-09-12T17:19:27 | 2020-09-12T17:19:27 | 293,558,902 | 1 | 0 | null | true | 2020-09-07T15:01:36 | 2020-09-07T15:01:35 | 2020-05-03T18:12:49 | 2020-08-24T05:34:43 | 24 | 0 | 0 | 0 | null | false | false |
package luccasdev.idwall.desafio.crawler.service;
import luccasdev.idwall.desafio.crawler.model.RedditThread;
import org.apache.logging.log4j.util.Strings;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class RedditThreadService {
private static final String REDDIT_URL = "https://old.reddit.com";
private static final String SUBREDDIT_PATH= "/r/";
private static final Integer PAGINATION_LIMIT = 50;
private static final Integer HOT_THREAD_POINTS = 5000;
public List<RedditThread> findHotRedditThreadsBySubreddits(List<String> subredditList) {
List<RedditThread> hotThreadList = new ArrayList<>();
subredditList.forEach(subreddit -> {
try {
List<Element> allThreadElements = this.findAllThreadElements(subreddit);
List<Element> hotThreadElements = this.findHotThreadElements(allThreadElements);
hotThreadElements.forEach(hotThreadElement -> hotThreadList.add(
RedditThread.builder()
.subreddit(subreddit)
.title(this.getThreadTitleFromElement(hotThreadElement))
.link(this.getThreadLinkFromElement(hotThreadElement))
.commentLink(this.getThreadLinkFromElement(hotThreadElement))
.upVotes(this.getTotalOfUpVotesByElement(hotThreadElement))
.build()
));
} catch (IOException e) {
e.printStackTrace();
}
});
return hotThreadList;
}
private List<Element> findAllThreadElements(String subreddit) throws IOException {
Document subredditDocument = Jsoup.connect(REDDIT_URL + SUBREDDIT_PATH + subreddit + "?limit=" + PAGINATION_LIMIT).get();
return subredditDocument.getElementById("siteTable").children().select("div[class*=thing]");
}
private List<Element> findHotThreadElements(List<Element> threadElements) {
List<Element> hotThreadElementList = new ArrayList<>();
threadElements.forEach(threadElement -> {
int totalUpVotes = this.getTotalOfUpVotesByElement(threadElement);
if (totalUpVotes >= HOT_THREAD_POINTS) {
hotThreadElementList.add(threadElement);
}
});
return hotThreadElementList;
}
private int getTotalOfUpVotesByElement(Element threadElement) {
String totalUpVotes = threadElement.children().select("div[class=score unvoted]").get(0).attr("title");
if (Strings.isEmpty(totalUpVotes)) {
return 0;
}
return Integer.parseInt(totalUpVotes);
}
private String getThreadTitleFromElement(Element threadElement) {
return threadElement.selectFirst("a.title").text();
}
private String getThreadLinkFromElement(Element threadElement) {
return REDDIT_URL + threadElement.attr("data-permalink");
}
}
|
UTF-8
|
Java
| 3,179 |
java
|
RedditThreadService.java
|
Java
|
[] | null |
[] |
package luccasdev.idwall.desafio.crawler.service;
import luccasdev.idwall.desafio.crawler.model.RedditThread;
import org.apache.logging.log4j.util.Strings;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class RedditThreadService {
private static final String REDDIT_URL = "https://old.reddit.com";
private static final String SUBREDDIT_PATH= "/r/";
private static final Integer PAGINATION_LIMIT = 50;
private static final Integer HOT_THREAD_POINTS = 5000;
public List<RedditThread> findHotRedditThreadsBySubreddits(List<String> subredditList) {
List<RedditThread> hotThreadList = new ArrayList<>();
subredditList.forEach(subreddit -> {
try {
List<Element> allThreadElements = this.findAllThreadElements(subreddit);
List<Element> hotThreadElements = this.findHotThreadElements(allThreadElements);
hotThreadElements.forEach(hotThreadElement -> hotThreadList.add(
RedditThread.builder()
.subreddit(subreddit)
.title(this.getThreadTitleFromElement(hotThreadElement))
.link(this.getThreadLinkFromElement(hotThreadElement))
.commentLink(this.getThreadLinkFromElement(hotThreadElement))
.upVotes(this.getTotalOfUpVotesByElement(hotThreadElement))
.build()
));
} catch (IOException e) {
e.printStackTrace();
}
});
return hotThreadList;
}
private List<Element> findAllThreadElements(String subreddit) throws IOException {
Document subredditDocument = Jsoup.connect(REDDIT_URL + SUBREDDIT_PATH + subreddit + "?limit=" + PAGINATION_LIMIT).get();
return subredditDocument.getElementById("siteTable").children().select("div[class*=thing]");
}
private List<Element> findHotThreadElements(List<Element> threadElements) {
List<Element> hotThreadElementList = new ArrayList<>();
threadElements.forEach(threadElement -> {
int totalUpVotes = this.getTotalOfUpVotesByElement(threadElement);
if (totalUpVotes >= HOT_THREAD_POINTS) {
hotThreadElementList.add(threadElement);
}
});
return hotThreadElementList;
}
private int getTotalOfUpVotesByElement(Element threadElement) {
String totalUpVotes = threadElement.children().select("div[class=score unvoted]").get(0).attr("title");
if (Strings.isEmpty(totalUpVotes)) {
return 0;
}
return Integer.parseInt(totalUpVotes);
}
private String getThreadTitleFromElement(Element threadElement) {
return threadElement.selectFirst("a.title").text();
}
private String getThreadLinkFromElement(Element threadElement) {
return REDDIT_URL + threadElement.attr("data-permalink");
}
}
| 3,179 | 0.656181 | 0.65335 | 77 | 40.285713 | 33.076794 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
10
|
86fdcc997322e1928cf9301c09243461041acc02
| 19,284,403,178,979 |
3c55aa69c1d94d49f7e3beaed04586d2fc8eb0e7
|
/binding/mdsal-binding-generator-util/src/main/java/org/opendaylight/mdsal/binding/model/util/generated/type/builder/GeneratedTypeBuilderImpl.java
|
576ba55f8b6ffd1d495c8d7a1fe28e7cee61ea1a
|
[] |
no_license
|
SoonPoong-Hong/mdsal
|
https://github.com/SoonPoong-Hong/mdsal
|
dee8a88e3900ff2776e7ab18da51ffa626fb1d1a
|
70faf85793f1639b7fc192a28b25d66e10806cab
|
refs/heads/master
| 2020-04-07T06:41:12.797000 | 2018-03-02T03:35:52 | 2018-03-06T14:50:04 | 124,189,614 | 1 | 0 | null | true | 2018-03-07T06:25:14 | 2018-03-07T06:25:14 | 2018-01-02T06:40:37 | 2018-03-06T14:50:25 | 11,715 | 0 | 0 | 0 | null | false | null |
/*
* Copyright (c) 2013 Cisco Systems, Inc. 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
*/
package org.opendaylight.mdsal.binding.model.util.generated.type.builder;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.TypeComment;
import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
import org.opendaylight.yangtools.yang.common.QName;
public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder<GeneratedTypeBuilder> implements
GeneratedTypeBuilder {
private String description;
private String reference;
private String moduleName;
private Iterable<QName> schemaPath;
public GeneratedTypeBuilderImpl(final String packageName, final String name) {
super(packageName, name);
setAbstract(true);
}
@Override
public GeneratedType toInstance() {
return new GeneratedTypeImpl(this);
}
@Override
public void setDescription(final String description) {
this.description = description;
}
@Override
public void setModuleName(final String moduleName) {
this.moduleName = moduleName;
}
@Override
public void setSchemaPath(final Iterable<QName> schemaPath) {
this.schemaPath = schemaPath;
}
@Override
public void setReference(final String reference) {
this.reference = reference;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("GeneratedTransferObject [packageName=");
builder.append(getPackageName());
builder.append(", name=");
builder.append(getName());
final TypeComment comment = getComment();
if (comment != null) {
builder.append(", comment=");
builder.append(comment.getJavadoc());
}
builder.append(", annotations=");
builder.append(getAnnotations());
builder.append(", implements=");
builder.append(getImplementsTypes());
builder.append(", enclosedTypes=");
builder.append(getEnclosedTypes());
builder.append(", constants=");
builder.append(getConstants());
builder.append(", enumerations=");
builder.append(getEnumerations());
builder.append(", properties=");
builder.append(", methods=");
builder.append(getMethodDefinitions());
builder.append("]");
return builder.toString();
}
@Override
protected GeneratedTypeBuilderImpl thisInstance() {
return this;
}
private static final class GeneratedTypeImpl extends AbstractGeneratedType {
private final String description;
private final String reference;
private final String moduleName;
private final Iterable<QName> schemaPath;
public GeneratedTypeImpl(final GeneratedTypeBuilderImpl builder) {
super(builder);
this.description = builder.description;
this.reference = builder.reference;
this.moduleName = builder.moduleName;
this.schemaPath = builder.schemaPath;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public String getReference() {
return this.reference;
}
@Override
public Iterable<QName> getSchemaPath() {
return this.schemaPath;
}
@Override
public String getModuleName() {
return this.moduleName;
}
}
}
|
UTF-8
|
Java
| 3,846 |
java
|
GeneratedTypeBuilderImpl.java
|
Java
|
[] | null |
[] |
/*
* Copyright (c) 2013 Cisco Systems, Inc. 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
*/
package org.opendaylight.mdsal.binding.model.util.generated.type.builder;
import org.opendaylight.mdsal.binding.model.api.GeneratedType;
import org.opendaylight.mdsal.binding.model.api.TypeComment;
import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
import org.opendaylight.yangtools.yang.common.QName;
public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder<GeneratedTypeBuilder> implements
GeneratedTypeBuilder {
private String description;
private String reference;
private String moduleName;
private Iterable<QName> schemaPath;
public GeneratedTypeBuilderImpl(final String packageName, final String name) {
super(packageName, name);
setAbstract(true);
}
@Override
public GeneratedType toInstance() {
return new GeneratedTypeImpl(this);
}
@Override
public void setDescription(final String description) {
this.description = description;
}
@Override
public void setModuleName(final String moduleName) {
this.moduleName = moduleName;
}
@Override
public void setSchemaPath(final Iterable<QName> schemaPath) {
this.schemaPath = schemaPath;
}
@Override
public void setReference(final String reference) {
this.reference = reference;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("GeneratedTransferObject [packageName=");
builder.append(getPackageName());
builder.append(", name=");
builder.append(getName());
final TypeComment comment = getComment();
if (comment != null) {
builder.append(", comment=");
builder.append(comment.getJavadoc());
}
builder.append(", annotations=");
builder.append(getAnnotations());
builder.append(", implements=");
builder.append(getImplementsTypes());
builder.append(", enclosedTypes=");
builder.append(getEnclosedTypes());
builder.append(", constants=");
builder.append(getConstants());
builder.append(", enumerations=");
builder.append(getEnumerations());
builder.append(", properties=");
builder.append(", methods=");
builder.append(getMethodDefinitions());
builder.append("]");
return builder.toString();
}
@Override
protected GeneratedTypeBuilderImpl thisInstance() {
return this;
}
private static final class GeneratedTypeImpl extends AbstractGeneratedType {
private final String description;
private final String reference;
private final String moduleName;
private final Iterable<QName> schemaPath;
public GeneratedTypeImpl(final GeneratedTypeBuilderImpl builder) {
super(builder);
this.description = builder.description;
this.reference = builder.reference;
this.moduleName = builder.moduleName;
this.schemaPath = builder.schemaPath;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public String getReference() {
return this.reference;
}
@Override
public Iterable<QName> getSchemaPath() {
return this.schemaPath;
}
@Override
public String getModuleName() {
return this.moduleName;
}
}
}
| 3,846 | 0.657826 | 0.655746 | 124 | 30.016129 | 24.246046 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532258 | false | false |
10
|
5a8733cf8468a2eb067784f2f275fde61805bfae
| 28,226,525,085,306 |
51842ab2662e0d783e9e70246a15c346bb10f55d
|
/Mock-UNIX-Shell/Assignment2B/A2/src/LinkedDocument.java
|
89faf91f8119e3d04549968a688f1e107cb3c695
|
[] |
no_license
|
ZainManji/UofT-Projects
|
https://github.com/ZainManji/UofT-Projects
|
3ee968e19bd1260513030fc8baeabc4b246c5ebf
|
2e10a6514d21cf5537d707b21a506a0e3f91e664
|
refs/heads/master
| 2021-01-23T11:48:16.687000 | 2013-11-18T18:53:35 | 2013-11-18T18:53:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Class handles symbolic linking. If accessed, returns the document or
* directory linked to this one.
*
* @author Avraham Sherman, Sean Gallagher
*/
public class LinkedDocument extends Dir {
/**
* @param link
* the document to be linked
* @param rootDir
* the root directory of the file system
*/
private Document link = null;
private Dir rootDir;
/**
* constructor, adds link to file system
*
* @param docName
* a string containing the name of the new LinkedDocument
* @param docPath
* a string containing the path to the new LinkedDocument
* @param linkedDoc
* the document or directory that this object will link to
* @param rootDir
* the root directory of the file system
*/
public LinkedDocument(String docName, String docPath, Document linkedDoc,
Dir rootDir) {
super(docName, docPath);
this.link = linkedDoc;
this.rootDir = rootDir;
Dir parentDir = rootDir.searchDir(docPath, rootDir);
if (parentDir.searchDoc(linkedDoc.getFullPath(), rootDir) != null)
parentDir.addDoc(this);
else
parentDir.addDir(this);
}
/**
* returns the document or directory linked through the symbolic link
*
* @return link the linked document/directory, or null if it no longer exists
*/
public Document getLink() {
if (rootDir.checkPathExists(this.link.getFullPath(), rootDir))
return this.link;
else
return null;
}
}
|
UTF-8
|
Java
| 1,649 |
java
|
LinkedDocument.java
|
Java
|
[
{
"context": " or\n * directory linked to this one.\n *\n * @author Avraham Sherman, Sean Gallagher\n */\npublic class LinkedDocument e",
"end": 138,
"score": 0.9998547434806824,
"start": 123,
"tag": "NAME",
"value": "Avraham Sherman"
},
{
"context": "linked to this one.\n *\n * @author Avraham Sherman, Sean Gallagher\n */\npublic class LinkedDocument extends Dir {\n ",
"end": 154,
"score": 0.9998744130134583,
"start": 140,
"tag": "NAME",
"value": "Sean Gallagher"
}
] | null |
[] |
/**
* Class handles symbolic linking. If accessed, returns the document or
* directory linked to this one.
*
* @author <NAME>, <NAME>
*/
public class LinkedDocument extends Dir {
/**
* @param link
* the document to be linked
* @param rootDir
* the root directory of the file system
*/
private Document link = null;
private Dir rootDir;
/**
* constructor, adds link to file system
*
* @param docName
* a string containing the name of the new LinkedDocument
* @param docPath
* a string containing the path to the new LinkedDocument
* @param linkedDoc
* the document or directory that this object will link to
* @param rootDir
* the root directory of the file system
*/
public LinkedDocument(String docName, String docPath, Document linkedDoc,
Dir rootDir) {
super(docName, docPath);
this.link = linkedDoc;
this.rootDir = rootDir;
Dir parentDir = rootDir.searchDir(docPath, rootDir);
if (parentDir.searchDoc(linkedDoc.getFullPath(), rootDir) != null)
parentDir.addDoc(this);
else
parentDir.addDir(this);
}
/**
* returns the document or directory linked through the symbolic link
*
* @return link the linked document/directory, or null if it no longer exists
*/
public Document getLink() {
if (rootDir.checkPathExists(this.link.getFullPath(), rootDir))
return this.link;
else
return null;
}
}
| 1,632 | 0.600364 | 0.600364 | 55 | 29 | 24.879345 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.381818 | false | false |
10
|
5c41299c315af55a3f130866d92c8ae284eb4d2b
| 33,500,744,939,362 |
3e62b91c49a99263ffd069c3055e3c554419c1f2
|
/exceptions/LoggingTest.java
|
c3beab278e31151eff0db8c15d92765ba281214f
|
[] |
no_license
|
rechade/TIJ
|
https://github.com/rechade/TIJ
|
7acc692efba11ac5b80a6e259ed3b16a2d23a095
|
cdd7c0f968a0f339bee66cbc9e11b5c3f99141b5
|
refs/heads/master
| 2021-01-23T06:44:16.578000 | 2015-01-20T07:07:50 | 2015-01-20T07:07:50 | 28,683,727 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// TIJ exceptions ex6 p322
package exceptions;
import java.util.logging.Logger;
import java.io.*;
class Exception1 extends Exception {
private static Logger logger = Logger.getLogger("Exception1");
Exception1() {
StringWriter trace = new StringWriter();
printStackTrace (new PrintWriter(trace));
logger.severe(trace.toString());
}
}
class Exception2 extends Exception {
private static Logger logger = Logger.getLogger("Exception2");
Exception2() {
StringWriter trace = new StringWriter();
printStackTrace (new PrintWriter(trace));
logger.severe(trace.toString());
}
}
public class LoggingTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i=0; i<3; i++) {
try {
throw new Exception1();
} catch (Exception1 e) {
}
}
for (int i=0; i<3; i++) {
try {
throw new Exception2();
} catch (Exception2 e) {
}
}
}
}
|
UTF-8
|
Java
| 915 |
java
|
LoggingTest.java
|
Java
|
[] | null |
[] |
// TIJ exceptions ex6 p322
package exceptions;
import java.util.logging.Logger;
import java.io.*;
class Exception1 extends Exception {
private static Logger logger = Logger.getLogger("Exception1");
Exception1() {
StringWriter trace = new StringWriter();
printStackTrace (new PrintWriter(trace));
logger.severe(trace.toString());
}
}
class Exception2 extends Exception {
private static Logger logger = Logger.getLogger("Exception2");
Exception2() {
StringWriter trace = new StringWriter();
printStackTrace (new PrintWriter(trace));
logger.severe(trace.toString());
}
}
public class LoggingTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i=0; i<3; i++) {
try {
throw new Exception1();
} catch (Exception1 e) {
}
}
for (int i=0; i<3; i++) {
try {
throw new Exception2();
} catch (Exception2 e) {
}
}
}
}
| 915 | 0.672131 | 0.652459 | 43 | 20.27907 | 17.67448 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.883721 | false | false |
10
|
2b19752ea4438cbc099f0b9901241e72377d2ac1
| 4,587,025,101,598 |
4e43d03fb61a621de897889dd1e68d79f0a1a286
|
/source/FM/V1R5/esdk_fm_neadp_1.5_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/model/common/AddAzReq.java
|
036cdbe51b2962416b81c068bb18cf26853e5be2
|
[
"Apache-2.0"
] |
permissive
|
eSDK/esdk_cloud_fm_r3_native_java
|
https://github.com/eSDK/esdk_cloud_fm_r3_native_java
|
9b03eb738e2e77a22ea57f0b36f1c53764a97075
|
660e4780cd1af4454b809250ddb5d5c3f676cbde
|
refs/heads/master
| 2018-10-08T09:29:32.531000 | 2015-10-16T08:26:57 | 2015-10-16T08:26:57 | 26,214,218 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.huawei.esdk.fusionmanager.local.model.common;
import java.util.List;
/**
*
* VDC加入云资源池请求信息。
* <p>
* @since eSDK Cloud V100R003C30
*/
public class AddAzReq
{
// /**
// * 是否选择所有AZ,废弃变量。
// */
// private Boolean allAz;
/**
* 【可选】AZ ID列表。
*/
private List<AzBaseInfo> azBaseInfos;
public List<AzBaseInfo> getAzBaseInfos()
{
return azBaseInfos;
}
public void setAzBaseInfos(List<AzBaseInfo> azBaseInfos)
{
this.azBaseInfos = azBaseInfos;
}
// public Boolean getAllAz()
// {
// return allAz;
// }
//
// public void setAllAz(Boolean allAz)
// {
// this.allAz = allAz;
// }
}
|
UTF-8
|
Java
| 833 |
java
|
AddAzReq.java
|
Java
|
[] | null |
[] |
package com.huawei.esdk.fusionmanager.local.model.common;
import java.util.List;
/**
*
* VDC加入云资源池请求信息。
* <p>
* @since eSDK Cloud V100R003C30
*/
public class AddAzReq
{
// /**
// * 是否选择所有AZ,废弃变量。
// */
// private Boolean allAz;
/**
* 【可选】AZ ID列表。
*/
private List<AzBaseInfo> azBaseInfos;
public List<AzBaseInfo> getAzBaseInfos()
{
return azBaseInfos;
}
public void setAzBaseInfos(List<AzBaseInfo> azBaseInfos)
{
this.azBaseInfos = azBaseInfos;
}
// public Boolean getAllAz()
// {
// return allAz;
// }
//
// public void setAllAz(Boolean allAz)
// {
// this.allAz = allAz;
// }
}
| 833 | 0.514877 | 0.504528 | 43 | 16.976744 | 16.039904 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.186047 | false | false |
10
|
b244cc6ebf9e119e09ea3ba13c9fb00aa3a71aee
| 10,857,677,369,896 |
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
|
/com.tencent.mm/classes.jar/com/tencent/thumbplayer/utils/j$a.java
|
2f24966bf2536b584c641dc451a9e0fe3a285dc2
|
[] |
no_license
|
tsuzcx/qq_apk
|
https://github.com/tsuzcx/qq_apk
|
0d5e792c3c7351ab781957bac465c55c505caf61
|
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
|
refs/heads/main
| 2022-07-02T10:32:11.651000 | 2022-02-01T12:41:38 | 2022-02-01T12:41:38 | 453,860,108 | 36 | 9 | null | false | 2022-01-31T09:46:26 | 2022-01-31T02:43:22 | 2022-01-31T06:56:43 | 2022-01-31T09:46:26 | 167,304 | 0 | 1 | 1 |
Java
| false | false |
package com.tencent.thumbplayer.utils;
import android.os.Handler;
import android.os.Message;
final class j$a
extends Handler
{
public final void handleMessage(Message paramMessage) {}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes3.jar
* Qualified Name: com.tencent.thumbplayer.utils.j.a
* JD-Core Version: 0.7.0.1
*/
|
UTF-8
|
Java
| 385 |
java
|
j$a.java
|
Java
|
[] | null |
[] |
package com.tencent.thumbplayer.utils;
import android.os.Handler;
import android.os.Message;
final class j$a
extends Handler
{
public final void handleMessage(Message paramMessage) {}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes3.jar
* Qualified Name: com.tencent.thumbplayer.utils.j.a
* JD-Core Version: 0.7.0.1
*/
| 385 | 0.680519 | 0.667532 | 20 | 17.549999 | 23.410414 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.15 | false | false |
10
|
c050698e00355f7af1aecb8239ae0ca00772d23b
| 22,789,096,476,495 |
deb72f96ed7d4b89e0f7397e2f717fb7e0d20c24
|
/broadway.kyle.homework2/src/broadway/kyle/UndoManagerImpl.java
|
4a59ae9184cf907e6d2d08e45a94e2e43267f7f4
|
[] |
no_license
|
kwbbpc/Software-Patterns-Code
|
https://github.com/kwbbpc/Software-Patterns-Code
|
2c221e822184a2689a396d3264ccf9aaad7cbec9
|
7c18dc66bbd485697eaf994c7bf567329d9f2fc5
|
refs/heads/master
| 2016-09-06T19:31:11.888000 | 2012-05-01T01:50:06 | 2012-05-01T01:50:06 | 3,621,777 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package broadway.kyle;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.EmptyStackException;
import java.util.Stack;
import com.javadude.command.Command;
import com.javadude.command.UndoManager;
public class UndoManagerImpl implements UndoManager
{
private Stack<Command> undoStack = FactoryCollection.createStack();
private Stack<Command> redoStack = FactoryCollection.createStack();
private PropertyChangeSupport pcs = FactoryPropertyChange.createPropertyChangeSupport(this);
@Override
public void addPropertyChangeListener(PropertyChangeListener listener)
{
pcs.addPropertyChangeListener(listener);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener listener)
{
pcs.removePropertyChangeListener(listener);
}
@Override
public void execute(Command command)
{
command.execute();
//clear the redo stack anytime a new command is executed.
String oldRedoCommand = getRedoName();
redoStack.clear();
pcs.firePropertyChange("redoName", oldRedoCommand, null);
//push onto the undo stack
String oldUndoCommand = getUndoName();
undoStack.push(command);
pcs.firePropertyChange("undoName", oldUndoCommand, getUndoName());
}
@Override
public void undo()
{
//ensure there's something to undo
if (undoStack.isEmpty())
{
System.out.println("nothing to undo.");
return;
}
//undo the command
Command lastCommand = undoStack.pop();
lastCommand.undo();
pcs.firePropertyChange("undoName", lastCommand.getName(), getUndoName());
//push onto the redo stack
String oldRedoCommand = getRedoName();
redoStack.push(lastCommand);
pcs.firePropertyChange("redoName", oldRedoCommand, getRedoName());
}
@Override
public void redo()
{
//ensure there's something to redo
if (redoStack.isEmpty())
{
System.out.println("nothing to redo.");
return;
}
//redo the command
Command lastCommand = redoStack.pop();
lastCommand.redo();
pcs.firePropertyChange("redoName", lastCommand.getName(), getRedoName());
//push onto the undo stack
String oldUndoCommand = getUndoName();
undoStack.push(lastCommand);
pcs.firePropertyChange("undoName", oldUndoCommand, getUndoName());
}
@Override
public String getUndoName()
{
try
{
return undoStack.peek().getName();
}
catch (EmptyStackException e)
{
return null;
}
}
@Override
public String getRedoName()
{
try
{
return redoStack.peek().getName();
}
catch (EmptyStackException e)
{
return null;
}
}
}
|
UTF-8
|
Java
| 2,991 |
java
|
UndoManagerImpl.java
|
Java
|
[] | null |
[] |
package broadway.kyle;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.EmptyStackException;
import java.util.Stack;
import com.javadude.command.Command;
import com.javadude.command.UndoManager;
public class UndoManagerImpl implements UndoManager
{
private Stack<Command> undoStack = FactoryCollection.createStack();
private Stack<Command> redoStack = FactoryCollection.createStack();
private PropertyChangeSupport pcs = FactoryPropertyChange.createPropertyChangeSupport(this);
@Override
public void addPropertyChangeListener(PropertyChangeListener listener)
{
pcs.addPropertyChangeListener(listener);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener listener)
{
pcs.removePropertyChangeListener(listener);
}
@Override
public void execute(Command command)
{
command.execute();
//clear the redo stack anytime a new command is executed.
String oldRedoCommand = getRedoName();
redoStack.clear();
pcs.firePropertyChange("redoName", oldRedoCommand, null);
//push onto the undo stack
String oldUndoCommand = getUndoName();
undoStack.push(command);
pcs.firePropertyChange("undoName", oldUndoCommand, getUndoName());
}
@Override
public void undo()
{
//ensure there's something to undo
if (undoStack.isEmpty())
{
System.out.println("nothing to undo.");
return;
}
//undo the command
Command lastCommand = undoStack.pop();
lastCommand.undo();
pcs.firePropertyChange("undoName", lastCommand.getName(), getUndoName());
//push onto the redo stack
String oldRedoCommand = getRedoName();
redoStack.push(lastCommand);
pcs.firePropertyChange("redoName", oldRedoCommand, getRedoName());
}
@Override
public void redo()
{
//ensure there's something to redo
if (redoStack.isEmpty())
{
System.out.println("nothing to redo.");
return;
}
//redo the command
Command lastCommand = redoStack.pop();
lastCommand.redo();
pcs.firePropertyChange("redoName", lastCommand.getName(), getRedoName());
//push onto the undo stack
String oldUndoCommand = getUndoName();
undoStack.push(lastCommand);
pcs.firePropertyChange("undoName", oldUndoCommand, getUndoName());
}
@Override
public String getUndoName()
{
try
{
return undoStack.peek().getName();
}
catch (EmptyStackException e)
{
return null;
}
}
@Override
public String getRedoName()
{
try
{
return redoStack.peek().getName();
}
catch (EmptyStackException e)
{
return null;
}
}
}
| 2,991 | 0.627549 | 0.627549 | 118 | 24.347458 | 23.581944 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432203 | false | false |
10
|
1abf92a31072ab1d9ae21ec48dae7430c9f4a96c
| 26,491,358,306,331 |
07efa03a2f3bdaecb69c2446a01ea386c63f26df
|
/eclipse_jee/Pdf/Etrieve/EtrieveItWebProject/Java Source/etrieveweb/etrievebean/contractdetailDBean.java
|
0faed7a1dc9a3ec4c790cbc61c3e2e4f13b95021
|
[] |
no_license
|
johnvincentio/repo-java
|
https://github.com/johnvincentio/repo-java
|
cc21e2b6e4d2bed038e2f7138bb8a269dfabeb2c
|
1824797cb4e0c52e0945248850e40e20b09effdd
|
refs/heads/master
| 2022-07-08T18:14:36.378000 | 2020-01-29T20:55:49 | 2020-01-29T20:55:49 | 84,679,095 | 0 | 0 | null | false | 2022-06-30T20:11:56 | 2017-03-11T20:51:46 | 2020-01-29T20:58:35 | 2022-06-30T20:11:55 | 172,670 | 0 | 0 | 2 |
Java
| false | false |
// *****************************************************************************************************************
// Copyright (C) 2005 The Hertz Corporation, All Rights Reserved. Unpublished.
//
// The information contained herein is confidential and proprietary to the Hertz Corporation
// and may not be duplicated, disclosed to third parties, or used for any purpose not
// expressly authorized by it.
// Any unauthorized use, duplication, or disclosure is prohibited by law.
// ****************************************************************************************************************
// MODIFICATION INDEX
//
// Index User Id Date Project Desciption
// ------ ----------- ---------- ---------------- --------------------------------------------------------
// x001 DTC9028 12/01/03 SR26609 PCR1 Removed the selection of RDTYPE equal "XD" or "YD"
// x002 DTC9028 01/14/03 SR26609 PCR1 Added fields RDMICG and RDEXM$
// x003 DTC9028 01/14/03 SR26609 PCR1 Added getEquipmentInfo method
// x004 DTC9028 01/27/03 SR26609 PCR1 Removed the join to RAPKUPFL file in the getRows method
// x005 DTC9028 01/27/03 SR26609 PCR1 Added a new method to query RAPKUPFL file
// x006 DTC9028 01/28/03 SR26609 PCR1 Added a "VS" to the where clause
// x007 DTC9028 02/12/03 SR26609 PCR1 Added the transaction type parameter to the getRows method
// x008 DTC9028 02/12/03 SR26609 PCR1 Added the RDTYPE to the SQL
// x009 DTC9028 03/22/04 SR28586 PCR25 Changed RSOQTY to RSSQTY for invoiced sales orders
// x010 DTC9028 01/12/05 TT404162 Corrected qty error for bulk items
// RI011 DTC9028 08/01/05 SR31413 PCR19 Datasource implementation modification
// RI012 DTC2073 11/15/05 SR35880 Added a method to retrieve order comments
// RI013 DTC2073 01/31/06 SR36721 Add shop supply fee to WO page.
// RI014 DTC2073 02/09/06 SR35873 Abbr. Equipment Release
// ****************************************************************************************************************
package etrieveweb.etrievebean;
import java.sql.*;
import java.io.*;
import etrieveweb.utility.sqlBean;
public class contractdetailDBean extends sqlBean implements java.io.Serializable{
ResultSet result=null, result2=null, result3=null;
Statement stmt=null, stmt2=null, stmt3=null;
public contractdetailDBean() {
super();
}
public synchronized boolean getRows(int customer_num, String company, String datalib, int contract_num, int sequence_num, String type, String itemtype, String str_transtype, String str_ordertype) throws Exception {
// *****************************************************************************************************************
// type = the RHTYPE field from RAOHDRFL or RACHDRFL
// itemtype = which section is being populated the "equipment" or "sales"
// transtype = "sales" when coming from Open Sales Orders, Sales Reservation-Quote, Closed Sales invoices????
// *****************************************************************************************************************
String SQLstatement = "";
if (type.equals("S") || type.equals("I") || type.equals("W") || ( ( type.equals("G") || ( type.equals("X") && str_transtype.equals("sales") ) ) && itemtype.equals("sales") ) ) {
// **********************************************************************************************************************
// SALES detail...
// This section simulates the RentalMan display file format RACNTICC/RACNTICS in program RACNTI
// S = Sales invoices I = Inter-company Expense W = Work Order G = Rental purchase X = Quote (sales only)
// **********************************************************************************************************************
if ( sequence_num == 0 )
SQLstatement =
"select RSITEM as RDITEM, RSISEQ as RDSEQ#, RSTYPE as RDTYPE, 0 as RDCATG, 0 as RDCLAS, RSSTKC as RDSTKC, RSOQTY as RDQTY, RSPRCE as RDPRCE, RSSTTS as RDSTTS, RSUNIT as RDUNIT, 0 as RDMHCD, 0 as RDMHO, 0 as RDMHI, 0 as MHTOTAL, 0 as RDMICG, 0 as RDEXM$, 0 as RDRSTK, ( ( RSPRCE*( 1-RSDSCP ) ) * RSOQTY ) as SOLDPRICE, 0 as RDAMT$, 0 as RDDYRT, 0 as RDWKRT, 0 as RDMORT, 0 as RDRATU, RSEMPC " +
"from " + datalib + ".RASDETF3 " +
" where RSCMP='" + company + "' and RSCON#=" + contract_num;
else
SQLstatement =
"select RSITEM as RDITEM, RSISEQ as RDSEQ#, RSTYPE as RDTYPE, 0 as RDCATG, 0 as RDCLAS, RSSTKC as RDSTKC, RSSQTY as RDQTY, RSPRCE as RDPRCE, RSSTTS as RDSTTS, RSUNIT as RDUNIT, 0 as RDMHCD, 0 as RDMHO, 0 as RDMHI, 0 as MHTOTAL, 0 as RDMICG, 0 as RDEXM$, 0 as RDRSTK, ( ( RSPRCE*(1-RSDSCP) ) * RSSQTY ) as SOLDPRICE, 0 as RDAMT$, 0 as RDDYRT, 0 as RDWKRT, 0 as RDMORT, 0 as RDRATU, RSEMPC " +
"from " + datalib + ".RASDETF3 " +
" where RSCMP='" + company + "' and RSCON#=" + contract_num + " and RSISEQ=" + sequence_num;
} else if (sequence_num == 0 && !type.equals("Y") && !type.equals("T") ) {
// **********************************************************************************************************************
// OPEN contracts, reservations, quotes details...
// This section simulates the RentalMan display file format RACNTIC1/RACNTIS1 from program RACNTI
// **********************************************************************************************************************
if ( itemtype.equals("sales") )
SQLstatement =
"select RDITEM, RDSEQ#, RDTYPE, RDCATG, RDCLAS, RDSTKC, (RDQTY-RDQTYR) as RDQTY, RDPRCE, RDSTTS, RDUNIT, RDMHCD, RDMHO, RDMHI, 0 as MHTOTAL, RDMICG, RDEXM$, RDRSTK, ( (RDPRCE * (1-RDDSCP)) * (RDQTY-RDQTYR) ) as soldprice, RDDYRT, RDWKRT, RDMORT, RDRATU " +
"from " + datalib + ".RAODETFL " +
" where RDCMP='" + company + "' and RDCON#=" + contract_num + " and RDTYPE in ('XC', 'YC', 'SI', 'VS')";
else
SQLstatement =
"select RDITEM, RDSEQ#, RDTYPE, RDCATG, RDCLAS, RDSTKC, (RDQTY-RDQTYR) as RDQTY, RDPRCE, RDSTTS, RDUNIT, RDMHCD, RDMHO, RDMHI, (RDMHI-RDMHO) as MHTOTAL, RDMICG, RDEXM$, RDRSTK,( (RDPRCE * (1-RDDSCP)) * (RDQTY-RDQTYR) ) as soldprice, RDDYRT, RDWKRT, RDMORT, RDRATU " +
"from " + datalib + ".RAODETFL " +
" where RDCMP='" + company + "' and RDCON#=" + contract_num + " and RDTYPE not in ('XC', 'XD', 'YC', 'YD', 'SI', 'VS')";
} else {
// ******************************************************************************************************************
// Invoices details
// NOTE: The quantity for the equipment section will be based on the RHTYPE and RHOTYP
// ******************************************************************************************************************
if ( itemtype.equals("sales") ) {
SQLstatement =
"select RDITEM, RDSEQ#, RDTYPE, RDCATG, RDCLAS, RDSTKC, (RDQTY-RDQTYR) as RDQTY, RDPRCE, RDSTTS, RDUNIT, RDMHCD, RDMHO, RDMHI, 0 as MHTOTAL, RDMICG, RDEXM$, RDRSTK, RDAMT$, ( (RDPRCE * (1-RDDSCP) ) * (RDQTY-RDQTYR) ) as soldprice, RDDYRT, RDWKRT, RDMORT, RDRATU " +
"from " + datalib + ".RACDETFL " +
" where RDCMP='" + company + "' and RDCON#=" + contract_num + " and RDISEQ =" + sequence_num + " and RDTYPE in ('XC', 'YC', 'SI', 'VS')";
} else {
String variable_SQLfields = "";
if ( ( type.equals("O") && str_ordertype.equals("C") ) || type.equals("C") || type.equals("Q") || type.equals("Y") || type.equals("T") || type.equals("F") || type.equals("G") )
variable_SQLfields = " (RDQTY - RDQTYR) as RDQTY, ( (RDPRCE * (1 - RDDSCP) ) * (RDQTY - RDQTYR) ) as soldprice ";
else
variable_SQLfields = " RDQTYR as RDQTY, ( (RDPRCE * (1-RDDSCP) ) * RDQTYR ) as soldprice ";
SQLstatement =
"select RDITEM, RDSEQ#, RDTYPE, RDCATG, RDCLAS, RDSTKC, RDPRCE, RDSTTS, RDUNIT, RDMHCD, RDMHO, RDMHI, (RDMHI-RDMHO) as MHTOTAL, RDMICG, RDEXM$, RDRSTK, RDAMT$, RDDYRT, RDWKRT, RDMORT, RDRATU, " + variable_SQLfields +
"from " + datalib + ".RACDETFL " +
" where RDCMP='" + company + "' and RDCON#=" + contract_num + " and RDISEQ =" + sequence_num + " and RDTYPE not in ('XC', 'XD', 'YC', 'YD', 'SI', 'VS')";
}
}
try {
// RI011 stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result=stmt.executeQuery(SQLstatement);
return (result != null);
} catch (SQLException e) {
System.err.println(e.getMessage());
System.out.println("The record does not exist!");
return false;
}
}
public synchronized String getDescription(String company, String datalib, String equipitem, int catg_num, int class_num, String stock) throws Exception {
String SQLstatement2 = "";
if ( catg_num != 0 || class_num != 0 ) {
SQLstatement2 =
"select ECDESC as description, ECBULK " + // RI014
"from " + datalib + ".EQPCCMFL " +
"where ECCMP='" + company + "' and ECCATG=" + catg_num + " and ECCLAS =" + class_num;
try {
// RI011 stmt2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt2=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result2=stmt2.executeQuery(SQLstatement2);
} catch (SQLException e) {
System.err.println(e.getMessage());
System.out.println("Description not available");
return "";
}
} else {
SQLstatement2 =
"select IMDESC as description " +
"from " + datalib + ".ITMMASFL " +
"where IMCMP='" + company + "' and IMITEM ='" + equipitem + "' and IMSTKC = '" + stock + "'";
try {
// RI011 stmt2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt2=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result2=stmt2.executeQuery(SQLstatement2);
} catch (SQLException e) {
System.err.println(e.getMessage());
System.out.println("Description not available");
return "Not Found";
}
}
if ( result2.next() )
return result2.getString("description");
else
return "Description not available";
}
//*******************************************
// RI014 - Get bulk item flag from result2
//******************************************
public String getColumn2(String colName) throws Exception {
try {
return result2.getString(colName);
} catch (SQLException e) {
System.err.println(e.getMessage());
return "N";
}
}
//*******************************************
// RI012 - Get line item comments
//******************************************
public synchronized String getItemComments(String company, String datalib, int contract, int seqno, int lineno) throws Exception {
String itemcomments = "";
ResultSet result4=null ;
Statement stmt4=null ;
try
{
String SQLstatement4 = "";
SQLstatement4 =
"select OCCMNT" +
" From "+ datalib + ".ORDCOMFL " +
" where OCCMP='" + company + "' " +
" and OCREF#= " + contract +
" and OCISEQ= " + seqno +
" and OCTYPE= 'R' " +
" and OCASEQ= " + lineno ;
stmt4=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
result4=stmt4.executeQuery(SQLstatement4);
if (result4 != null)
{
while(result4.next())
{
itemcomments = itemcomments.trim() + " " + result4.getString("OCCMNT").trim();
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
itemcomments = "";
}
endcurrentResultset(result4);
endcurrentStatement(stmt4);
return itemcomments;
}
public synchronized String[] getEquipmentInfo(String company, String datalib, String equipitem, int catg_num, int class_num) throws Exception {
String SQLstatement3 = "";
String[] Array = { "", "", ""};
if ( catg_num != 0 || class_num != 0 ) {
SQLstatement3 =
"select EMMAKE, EMMODL, EMSER# " +
"from " + datalib + ".EQPMASFL " +
"where EMCMP='" + company.trim() + "' and EMEQP#='" + equipitem.trim() + "'";
try {
// RI011 stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI001
result3=stmt3.executeQuery(SQLstatement3);
if ( result3.next() ) {
Array[0] = result3.getString("EMMAKE");
Array[1] = result3.getString("EMMODL");
Array[2] = result3.getString("EMSER#");
}
} catch (SQLException e) {
System.err.println(e.getMessage());
return Array;
} finally { // RI011
endcurrentResultset(result3); // RI011
endcurrentStatement(stmt3); // RI011
} // RI011
}
return Array;
}
public synchronized String[] getFreeMiles(String company, String datalib, int contract_num, int sequence_num, int catg_num, int class_num) throws Exception {
String SQLstatement3 = "";
String[] Array = { "", "", ""};
if ( catg_num != 0 || class_num != 0 ) {
SQLstatement3 =
"select ADDYFMIL, ADWKFMIL, ADMOFMIL " +
"from " + datalib + ".RAOADTFL " +
"where ADCMP='" + company.trim() + "' and ADCON#=" + contract_num + " and ADTYPE = 'RI' and ADSEQ#=" + sequence_num;
try {
// RI011 stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result3=stmt3.executeQuery(SQLstatement3);
if ( result3.next() ) {
Array[0] = result3.getString("ADDYFMIL");
Array[1] = result3.getString("ADWKFMIL");
Array[2] = result3.getString("ADMOFMIL");
}
} catch (SQLException e) {
System.err.println(e.getMessage());
return Array;
} finally { // RI011
endcurrentResultset(result3); // RI011
endcurrentStatement(stmt3); // RI011
} // RI011
}
return Array;
}
public synchronized String getPickupStatus(String company, String datalib, int contract_num, int sequence_num, String equipitem) throws Exception {
String SQLstatement3 = "";
String str_pickupStatus = "";
SQLstatement3 =
"select distinct RUSTTS " +
"from " + datalib + ".RAPKUPFL " +
"where RUCMP='" + company.trim() + "' and RUCON#=" + contract_num + " and RUSTTS = 'OP' and RUEQP#='" + equipitem.trim() + "' and RUSEQ#=" + sequence_num;
try {
// RI011 stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result3=stmt3.executeQuery(SQLstatement3);
if ( result3.next() ) {
str_pickupStatus = result3.getString("RUSTTS");
return str_pickupStatus;
}
} catch (SQLException e) {
System.err.println(e.getMessage());
return str_pickupStatus;
} finally { // RI011
endcurrentResultset(result3); // RI011
endcurrentStatement(stmt3); // RI011
} // RI011
return str_pickupStatus;
}
public boolean getNext() throws Exception {
return result.next();
}
public String getColumn(String colNum) throws Exception {
return result.getString(colNum);
}
public void cleanup() throws Exception {
endcurrentResultset(result); // RI011
endcurrentResultset(result2); // RI011
endcurrentResultset(result3); // RI011
endcurrentStatement(stmt); // RI011
endcurrentStatement(stmt2); // RI011
endcurrentStatement(stmt3); // RI011
}
}
|
UTF-8
|
Java
| 16,939 |
java
|
contractdetailDBean.java
|
Java
|
[] | null |
[] |
// *****************************************************************************************************************
// Copyright (C) 2005 The Hertz Corporation, All Rights Reserved. Unpublished.
//
// The information contained herein is confidential and proprietary to the Hertz Corporation
// and may not be duplicated, disclosed to third parties, or used for any purpose not
// expressly authorized by it.
// Any unauthorized use, duplication, or disclosure is prohibited by law.
// ****************************************************************************************************************
// MODIFICATION INDEX
//
// Index User Id Date Project Desciption
// ------ ----------- ---------- ---------------- --------------------------------------------------------
// x001 DTC9028 12/01/03 SR26609 PCR1 Removed the selection of RDTYPE equal "XD" or "YD"
// x002 DTC9028 01/14/03 SR26609 PCR1 Added fields RDMICG and RDEXM$
// x003 DTC9028 01/14/03 SR26609 PCR1 Added getEquipmentInfo method
// x004 DTC9028 01/27/03 SR26609 PCR1 Removed the join to RAPKUPFL file in the getRows method
// x005 DTC9028 01/27/03 SR26609 PCR1 Added a new method to query RAPKUPFL file
// x006 DTC9028 01/28/03 SR26609 PCR1 Added a "VS" to the where clause
// x007 DTC9028 02/12/03 SR26609 PCR1 Added the transaction type parameter to the getRows method
// x008 DTC9028 02/12/03 SR26609 PCR1 Added the RDTYPE to the SQL
// x009 DTC9028 03/22/04 SR28586 PCR25 Changed RSOQTY to RSSQTY for invoiced sales orders
// x010 DTC9028 01/12/05 TT404162 Corrected qty error for bulk items
// RI011 DTC9028 08/01/05 SR31413 PCR19 Datasource implementation modification
// RI012 DTC2073 11/15/05 SR35880 Added a method to retrieve order comments
// RI013 DTC2073 01/31/06 SR36721 Add shop supply fee to WO page.
// RI014 DTC2073 02/09/06 SR35873 Abbr. Equipment Release
// ****************************************************************************************************************
package etrieveweb.etrievebean;
import java.sql.*;
import java.io.*;
import etrieveweb.utility.sqlBean;
public class contractdetailDBean extends sqlBean implements java.io.Serializable{
ResultSet result=null, result2=null, result3=null;
Statement stmt=null, stmt2=null, stmt3=null;
public contractdetailDBean() {
super();
}
public synchronized boolean getRows(int customer_num, String company, String datalib, int contract_num, int sequence_num, String type, String itemtype, String str_transtype, String str_ordertype) throws Exception {
// *****************************************************************************************************************
// type = the RHTYPE field from RAOHDRFL or RACHDRFL
// itemtype = which section is being populated the "equipment" or "sales"
// transtype = "sales" when coming from Open Sales Orders, Sales Reservation-Quote, Closed Sales invoices????
// *****************************************************************************************************************
String SQLstatement = "";
if (type.equals("S") || type.equals("I") || type.equals("W") || ( ( type.equals("G") || ( type.equals("X") && str_transtype.equals("sales") ) ) && itemtype.equals("sales") ) ) {
// **********************************************************************************************************************
// SALES detail...
// This section simulates the RentalMan display file format RACNTICC/RACNTICS in program RACNTI
// S = Sales invoices I = Inter-company Expense W = Work Order G = Rental purchase X = Quote (sales only)
// **********************************************************************************************************************
if ( sequence_num == 0 )
SQLstatement =
"select RSITEM as RDITEM, RSISEQ as RDSEQ#, RSTYPE as RDTYPE, 0 as RDCATG, 0 as RDCLAS, RSSTKC as RDSTKC, RSOQTY as RDQTY, RSPRCE as RDPRCE, RSSTTS as RDSTTS, RSUNIT as RDUNIT, 0 as RDMHCD, 0 as RDMHO, 0 as RDMHI, 0 as MHTOTAL, 0 as RDMICG, 0 as RDEXM$, 0 as RDRSTK, ( ( RSPRCE*( 1-RSDSCP ) ) * RSOQTY ) as SOLDPRICE, 0 as RDAMT$, 0 as RDDYRT, 0 as RDWKRT, 0 as RDMORT, 0 as RDRATU, RSEMPC " +
"from " + datalib + ".RASDETF3 " +
" where RSCMP='" + company + "' and RSCON#=" + contract_num;
else
SQLstatement =
"select RSITEM as RDITEM, RSISEQ as RDSEQ#, RSTYPE as RDTYPE, 0 as RDCATG, 0 as RDCLAS, RSSTKC as RDSTKC, RSSQTY as RDQTY, RSPRCE as RDPRCE, RSSTTS as RDSTTS, RSUNIT as RDUNIT, 0 as RDMHCD, 0 as RDMHO, 0 as RDMHI, 0 as MHTOTAL, 0 as RDMICG, 0 as RDEXM$, 0 as RDRSTK, ( ( RSPRCE*(1-RSDSCP) ) * RSSQTY ) as SOLDPRICE, 0 as RDAMT$, 0 as RDDYRT, 0 as RDWKRT, 0 as RDMORT, 0 as RDRATU, RSEMPC " +
"from " + datalib + ".RASDETF3 " +
" where RSCMP='" + company + "' and RSCON#=" + contract_num + " and RSISEQ=" + sequence_num;
} else if (sequence_num == 0 && !type.equals("Y") && !type.equals("T") ) {
// **********************************************************************************************************************
// OPEN contracts, reservations, quotes details...
// This section simulates the RentalMan display file format RACNTIC1/RACNTIS1 from program RACNTI
// **********************************************************************************************************************
if ( itemtype.equals("sales") )
SQLstatement =
"select RDITEM, RDSEQ#, RDTYPE, RDCATG, RDCLAS, RDSTKC, (RDQTY-RDQTYR) as RDQTY, RDPRCE, RDSTTS, RDUNIT, RDMHCD, RDMHO, RDMHI, 0 as MHTOTAL, RDMICG, RDEXM$, RDRSTK, ( (RDPRCE * (1-RDDSCP)) * (RDQTY-RDQTYR) ) as soldprice, RDDYRT, RDWKRT, RDMORT, RDRATU " +
"from " + datalib + ".RAODETFL " +
" where RDCMP='" + company + "' and RDCON#=" + contract_num + " and RDTYPE in ('XC', 'YC', 'SI', 'VS')";
else
SQLstatement =
"select RDITEM, RDSEQ#, RDTYPE, RDCATG, RDCLAS, RDSTKC, (RDQTY-RDQTYR) as RDQTY, RDPRCE, RDSTTS, RDUNIT, RDMHCD, RDMHO, RDMHI, (RDMHI-RDMHO) as MHTOTAL, RDMICG, RDEXM$, RDRSTK,( (RDPRCE * (1-RDDSCP)) * (RDQTY-RDQTYR) ) as soldprice, RDDYRT, RDWKRT, RDMORT, RDRATU " +
"from " + datalib + ".RAODETFL " +
" where RDCMP='" + company + "' and RDCON#=" + contract_num + " and RDTYPE not in ('XC', 'XD', 'YC', 'YD', 'SI', 'VS')";
} else {
// ******************************************************************************************************************
// Invoices details
// NOTE: The quantity for the equipment section will be based on the RHTYPE and RHOTYP
// ******************************************************************************************************************
if ( itemtype.equals("sales") ) {
SQLstatement =
"select RDITEM, RDSEQ#, RDTYPE, RDCATG, RDCLAS, RDSTKC, (RDQTY-RDQTYR) as RDQTY, RDPRCE, RDSTTS, RDUNIT, RDMHCD, RDMHO, RDMHI, 0 as MHTOTAL, RDMICG, RDEXM$, RDRSTK, RDAMT$, ( (RDPRCE * (1-RDDSCP) ) * (RDQTY-RDQTYR) ) as soldprice, RDDYRT, RDWKRT, RDMORT, RDRATU " +
"from " + datalib + ".RACDETFL " +
" where RDCMP='" + company + "' and RDCON#=" + contract_num + " and RDISEQ =" + sequence_num + " and RDTYPE in ('XC', 'YC', 'SI', 'VS')";
} else {
String variable_SQLfields = "";
if ( ( type.equals("O") && str_ordertype.equals("C") ) || type.equals("C") || type.equals("Q") || type.equals("Y") || type.equals("T") || type.equals("F") || type.equals("G") )
variable_SQLfields = " (RDQTY - RDQTYR) as RDQTY, ( (RDPRCE * (1 - RDDSCP) ) * (RDQTY - RDQTYR) ) as soldprice ";
else
variable_SQLfields = " RDQTYR as RDQTY, ( (RDPRCE * (1-RDDSCP) ) * RDQTYR ) as soldprice ";
SQLstatement =
"select RDITEM, RDSEQ#, RDTYPE, RDCATG, RDCLAS, RDSTKC, RDPRCE, RDSTTS, RDUNIT, RDMHCD, RDMHO, RDMHI, (RDMHI-RDMHO) as MHTOTAL, RDMICG, RDEXM$, RDRSTK, RDAMT$, RDDYRT, RDWKRT, RDMORT, RDRATU, " + variable_SQLfields +
"from " + datalib + ".RACDETFL " +
" where RDCMP='" + company + "' and RDCON#=" + contract_num + " and RDISEQ =" + sequence_num + " and RDTYPE not in ('XC', 'XD', 'YC', 'YD', 'SI', 'VS')";
}
}
try {
// RI011 stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result=stmt.executeQuery(SQLstatement);
return (result != null);
} catch (SQLException e) {
System.err.println(e.getMessage());
System.out.println("The record does not exist!");
return false;
}
}
public synchronized String getDescription(String company, String datalib, String equipitem, int catg_num, int class_num, String stock) throws Exception {
String SQLstatement2 = "";
if ( catg_num != 0 || class_num != 0 ) {
SQLstatement2 =
"select ECDESC as description, ECBULK " + // RI014
"from " + datalib + ".EQPCCMFL " +
"where ECCMP='" + company + "' and ECCATG=" + catg_num + " and ECCLAS =" + class_num;
try {
// RI011 stmt2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt2=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result2=stmt2.executeQuery(SQLstatement2);
} catch (SQLException e) {
System.err.println(e.getMessage());
System.out.println("Description not available");
return "";
}
} else {
SQLstatement2 =
"select IMDESC as description " +
"from " + datalib + ".ITMMASFL " +
"where IMCMP='" + company + "' and IMITEM ='" + equipitem + "' and IMSTKC = '" + stock + "'";
try {
// RI011 stmt2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt2=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result2=stmt2.executeQuery(SQLstatement2);
} catch (SQLException e) {
System.err.println(e.getMessage());
System.out.println("Description not available");
return "Not Found";
}
}
if ( result2.next() )
return result2.getString("description");
else
return "Description not available";
}
//*******************************************
// RI014 - Get bulk item flag from result2
//******************************************
public String getColumn2(String colName) throws Exception {
try {
return result2.getString(colName);
} catch (SQLException e) {
System.err.println(e.getMessage());
return "N";
}
}
//*******************************************
// RI012 - Get line item comments
//******************************************
public synchronized String getItemComments(String company, String datalib, int contract, int seqno, int lineno) throws Exception {
String itemcomments = "";
ResultSet result4=null ;
Statement stmt4=null ;
try
{
String SQLstatement4 = "";
SQLstatement4 =
"select OCCMNT" +
" From "+ datalib + ".ORDCOMFL " +
" where OCCMP='" + company + "' " +
" and OCREF#= " + contract +
" and OCISEQ= " + seqno +
" and OCTYPE= 'R' " +
" and OCASEQ= " + lineno ;
stmt4=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
result4=stmt4.executeQuery(SQLstatement4);
if (result4 != null)
{
while(result4.next())
{
itemcomments = itemcomments.trim() + " " + result4.getString("OCCMNT").trim();
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
itemcomments = "";
}
endcurrentResultset(result4);
endcurrentStatement(stmt4);
return itemcomments;
}
public synchronized String[] getEquipmentInfo(String company, String datalib, String equipitem, int catg_num, int class_num) throws Exception {
String SQLstatement3 = "";
String[] Array = { "", "", ""};
if ( catg_num != 0 || class_num != 0 ) {
SQLstatement3 =
"select EMMAKE, EMMODL, EMSER# " +
"from " + datalib + ".EQPMASFL " +
"where EMCMP='" + company.trim() + "' and EMEQP#='" + equipitem.trim() + "'";
try {
// RI011 stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI001
result3=stmt3.executeQuery(SQLstatement3);
if ( result3.next() ) {
Array[0] = result3.getString("EMMAKE");
Array[1] = result3.getString("EMMODL");
Array[2] = result3.getString("EMSER#");
}
} catch (SQLException e) {
System.err.println(e.getMessage());
return Array;
} finally { // RI011
endcurrentResultset(result3); // RI011
endcurrentStatement(stmt3); // RI011
} // RI011
}
return Array;
}
public synchronized String[] getFreeMiles(String company, String datalib, int contract_num, int sequence_num, int catg_num, int class_num) throws Exception {
String SQLstatement3 = "";
String[] Array = { "", "", ""};
if ( catg_num != 0 || class_num != 0 ) {
SQLstatement3 =
"select ADDYFMIL, ADWKFMIL, ADMOFMIL " +
"from " + datalib + ".RAOADTFL " +
"where ADCMP='" + company.trim() + "' and ADCON#=" + contract_num + " and ADTYPE = 'RI' and ADSEQ#=" + sequence_num;
try {
// RI011 stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result3=stmt3.executeQuery(SQLstatement3);
if ( result3.next() ) {
Array[0] = result3.getString("ADDYFMIL");
Array[1] = result3.getString("ADWKFMIL");
Array[2] = result3.getString("ADMOFMIL");
}
} catch (SQLException e) {
System.err.println(e.getMessage());
return Array;
} finally { // RI011
endcurrentResultset(result3); // RI011
endcurrentStatement(stmt3); // RI011
} // RI011
}
return Array;
}
public synchronized String getPickupStatus(String company, String datalib, int contract_num, int sequence_num, String equipitem) throws Exception {
String SQLstatement3 = "";
String str_pickupStatus = "";
SQLstatement3 =
"select distinct RUSTTS " +
"from " + datalib + ".RAPKUPFL " +
"where RUCMP='" + company.trim() + "' and RUCON#=" + contract_num + " and RUSTTS = 'OP' and RUEQP#='" + equipitem.trim() + "' and RUSEQ#=" + sequence_num;
try {
// RI011 stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt3=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // RI011
result3=stmt3.executeQuery(SQLstatement3);
if ( result3.next() ) {
str_pickupStatus = result3.getString("RUSTTS");
return str_pickupStatus;
}
} catch (SQLException e) {
System.err.println(e.getMessage());
return str_pickupStatus;
} finally { // RI011
endcurrentResultset(result3); // RI011
endcurrentStatement(stmt3); // RI011
} // RI011
return str_pickupStatus;
}
public boolean getNext() throws Exception {
return result.next();
}
public String getColumn(String colNum) throws Exception {
return result.getString(colNum);
}
public void cleanup() throws Exception {
endcurrentResultset(result); // RI011
endcurrentResultset(result2); // RI011
endcurrentResultset(result3); // RI011
endcurrentStatement(stmt); // RI011
endcurrentStatement(stmt2); // RI011
endcurrentStatement(stmt3); // RI011
}
}
| 16,939 | 0.541295 | 0.511837 | 435 | 36.944828 | 52.044868 | 405 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.09885 | false | false |
10
|
2d4b42c2f62563ddfcaad9b8bb84d2bab67d9c42
| 19,954,418,099,892 |
379d11362a4a2230cdc0569f014104bb93cea932
|
/[Heneria] Report/src/fr/shyzuko/commands/tuto.java
|
81e023d55009d4b5af98a7b2d468bcb82ef03bc9
|
[] |
no_license
|
Shyzuko/Test
|
https://github.com/Shyzuko/Test
|
194259a8040c0dd6d48b46b7b9112eeae8dd4f34
|
bfff560c3b1c40be96ecc14ef0f48047d7ec0265
|
refs/heads/main
| 2023-04-11T04:36:07.177000 | 2021-04-22T16:01:14 | 2021-04-22T16:01:14 | 360,576,268 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fr.shyzuko.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class tuto implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(label.equalsIgnoreCase("tuto")){
Player p = (Player)sender;
p.sendMessage(" §3§lHene§b§lria ");
p.sendMessage(" ");
p.sendMessage("§71) §6Vous devez aller faire votre carte d'identités");
p.sendMessage("§72) §6Une fois faite allait acheter un téléphone");
p.sendMessage("§73) §6puis acheter à manger ");
p.sendMessage("§74) §6Regarder votre Gps pour aller faire votre carte bancaire etc.");
p.sendMessage("§75) §6Je vous laisse vous amuser");
p.sendMessage(" ");
p.sendMessage(" ");
}
return false;
}
}
|
UTF-8
|
Java
| 1,078 |
java
|
tuto.java
|
Java
|
[] | null |
[] |
package fr.shyzuko.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class tuto implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(label.equalsIgnoreCase("tuto")){
Player p = (Player)sender;
p.sendMessage(" §3§lHene§b§lria ");
p.sendMessage(" ");
p.sendMessage("§71) §6Vous devez aller faire votre carte d'identités");
p.sendMessage("§72) §6Une fois faite allait acheter un téléphone");
p.sendMessage("§73) §6puis acheter à manger ");
p.sendMessage("§74) §6Regarder votre Gps pour aller faire votre carte bancaire etc.");
p.sendMessage("§75) §6Je vous laisse vous amuser");
p.sendMessage(" ");
p.sendMessage(" ");
}
return false;
}
}
| 1,078 | 0.593396 | 0.578302 | 25 | 40.400002 | 29.30802 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.76 | false | false |
10
|
1df3f3c17bc59ab04be192f449877b4dfedaccc7
| 4,930,622,509,829 |
82450c678164c92ae7e8a6eb0d74b4a0d12beb7d
|
/Trust/src/main/java/com/trust/app/service/UserServiceImpl.java
|
e6cf3a8d2e24a67958678f279184917bae23c695
|
[] |
no_license
|
litoumas/trust
|
https://github.com/litoumas/trust
|
dcce5b9fc0124a3c01b55484d02c03e88f155b51
|
dc3d26dabaec6830e273cb79030befc5c2d05ae7
|
refs/heads/master
| 2020-04-09T04:50:54.139000 | 2019-04-26T07:15:05 | 2019-04-26T07:15:05 | 160,023,083 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.trust.app.service;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.trust.app.dao.UserDAO;
import com.trust.app.model.User;
@Service
@ManagedBean(name = "userService")
@SessionScoped
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
@Override
@Transactional
public List<User> listUsers() {
return this.userDAO.listUsers();
}
@Override
@Transactional
public void addUser(User u) {
this.userDAO.addUser(u);
}
@Override
@Transactional
public void deleteUser(User u) {
this.userDAO.deleteUser(u);
}
@Override
@Transactional
public void updateUser(User u) {
this.userDAO.updateUser(u);
}
@Override
@Transactional
public User researchUsers(String login, String passhash) {
// TODO Auto-generated method stub
return this.userDAO.researchUsers(login, passhash);
}
}
|
UTF-8
|
Java
| 1,091 |
java
|
UserServiceImpl.java
|
Java
|
[] | null |
[] |
package com.trust.app.service;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.trust.app.dao.UserDAO;
import com.trust.app.model.User;
@Service
@ManagedBean(name = "userService")
@SessionScoped
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
@Override
@Transactional
public List<User> listUsers() {
return this.userDAO.listUsers();
}
@Override
@Transactional
public void addUser(User u) {
this.userDAO.addUser(u);
}
@Override
@Transactional
public void deleteUser(User u) {
this.userDAO.deleteUser(u);
}
@Override
@Transactional
public void updateUser(User u) {
this.userDAO.updateUser(u);
}
@Override
@Transactional
public User researchUsers(String login, String passhash) {
// TODO Auto-generated method stub
return this.userDAO.researchUsers(login, passhash);
}
}
| 1,091 | 0.762603 | 0.762603 | 58 | 17.827587 | 17.668535 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.931035 | false | false |
10
|
ad947c9ec905c5f8264612a8d742efb20da8351a
| 3,839,700,796,741 |
85fc70e91cbe3c31ef60eab175a006bf81b9fc2e
|
/src/test/java/automation_practice_tests/Level13Tests.java
|
daf297dc7acef41bc5a8e32f18b20c15cd4d23f3
|
[
"MIT"
] |
permissive
|
XPuigA/automation-framework
|
https://github.com/XPuigA/automation-framework
|
8f89d458b3d5f3011a1bd875c9688d7071707af1
|
401d28f0fce69186db47c24b020b743d61c9ccd0
|
refs/heads/main
| 2023-01-14T16:37:09.465000 | 2020-11-25T21:23:50 | 2020-11-25T21:23:50 | 311,450,382 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package automation_practice_tests;
import automation_practice.pages.levels.Level3Page;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import automation_practice.pages.levels.Level13Page;
@Execution(ExecutionMode.CONCURRENT)
class Level13Tests extends AutomationPracticeTest {
Level13Page page;
@BeforeEach
void setUp() {
goTo(url + "level13");
page = new Level13Page(driver);
}
@Test
void correctTest() {
page.waitForLoaderAndClickContinue();
Assertions.assertTrue(driver.getCurrentUrl().endsWith("level14"));
}
}
|
UTF-8
|
Java
| 751 |
java
|
Level13Tests.java
|
Java
|
[] | null |
[] |
package automation_practice_tests;
import automation_practice.pages.levels.Level3Page;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import automation_practice.pages.levels.Level13Page;
@Execution(ExecutionMode.CONCURRENT)
class Level13Tests extends AutomationPracticeTest {
Level13Page page;
@BeforeEach
void setUp() {
goTo(url + "level13");
page = new Level13Page(driver);
}
@Test
void correctTest() {
page.waitForLoaderAndClickContinue();
Assertions.assertTrue(driver.getCurrentUrl().endsWith("level14"));
}
}
| 751 | 0.744341 | 0.727031 | 27 | 26.814816 | 21.018576 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false |
10
|
d266e2e9ac2e8ae4ab4b6b5ba39cf18916e420da
| 3,839,700,797,427 |
9dad6c3a03ae385aee729c166c4874c95d0e68c6
|
/spring-batch-training/src/main/java/com/mantinha/springbatchtraining/job/step/reader/flat/MyReaderWithFlatMultiLines.java
|
d4ad27e45eee8accad43b9bce93345b78c09603d
|
[] |
no_license
|
mantinha/spring-batch-training
|
https://github.com/mantinha/spring-batch-training
|
e1aecfac1f6262ecafb744c5d580b23e7d29cd6d
|
fa1cdd5991f45c355cb85cfaf580fb3dcd288b08
|
refs/heads/master
| 2023-03-10T16:50:31.076000 | 2021-02-27T07:37:42 | 2021-02-27T07:37:42 | 318,663,201 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mantinha.springbatchtraining.job.step.reader.flat;
//import org.springframework.batch.core.configuration.annotation.StepScope;
//import org.springframework.batch.item.file.FlatFileItemReader;
//import org.springframework.batch.item.file.LineMapper;
//import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.io.Resource;
//
///**
// * Leitor de arquivos Flat com condições ou
// * multifatores com delimitações
// * CÓPIA DE MULTIFORMAT
// *
// * @author adriano
// *
// */
//@Configuration
//public class MyReaderWithFlatMultiLines {
//
// @SuppressWarnings({ "rawtypes", "unchecked"})
// @StepScope
// @Bean
// public FlatFileItemReader fileReader(@Value("#{jobParameters['paramClientes']}") Resource paramClientes, LineMapper lineMapper ) {
// return new FlatFileItemReaderBuilder()
// .name("fileReader")
// .resource(paramClientes)
// .lineMapper(lineMapper)
// .build();
// }
//}
|
UTF-8
|
Java
| 1,152 |
java
|
MyReaderWithFlatMultiLines.java
|
Java
|
[
{
"context": "ações\n// * CÓPIA DE MULTIFORMAT\n// * \n// * @author adriano\n// *\n// */\n//@Configuration\n//public class MyRead",
"end": 709,
"score": 0.70619136095047,
"start": 702,
"tag": "USERNAME",
"value": "adriano"
}
] | null |
[] |
package com.mantinha.springbatchtraining.job.step.reader.flat;
//import org.springframework.batch.core.configuration.annotation.StepScope;
//import org.springframework.batch.item.file.FlatFileItemReader;
//import org.springframework.batch.item.file.LineMapper;
//import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.io.Resource;
//
///**
// * Leitor de arquivos Flat com condições ou
// * multifatores com delimitações
// * CÓPIA DE MULTIFORMAT
// *
// * @author adriano
// *
// */
//@Configuration
//public class MyReaderWithFlatMultiLines {
//
// @SuppressWarnings({ "rawtypes", "unchecked"})
// @StepScope
// @Bean
// public FlatFileItemReader fileReader(@Value("#{jobParameters['paramClientes']}") Resource paramClientes, LineMapper lineMapper ) {
// return new FlatFileItemReaderBuilder()
// .name("fileReader")
// .resource(paramClientes)
// .lineMapper(lineMapper)
// .build();
// }
//}
| 1,152 | 0.755013 | 0.755013 | 33 | 33.757576 | 29.504011 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false |
10
|
e1470c24b2a0cc83a24a35aee8d1b8bbb22bf0b5
| 32,452,772,950,430 |
ffcb6eeb56c0a05dc9945020dd04afee73ed4c1d
|
/src/main/java/doppio/apps/explorer/view/component/singletweetlabel/SingleTweetLabel.java
|
4b35a3d1f1aeffcae844434aad01c1dca69db1a7
|
[] |
no_license
|
mbroughani81/doppio_core
|
https://github.com/mbroughani81/doppio_core
|
a75ff07c6c4addd6753ba48e42a926d4f617b1c4
|
ed05df55336ed60966f2c3e5471effc181fadc8e
|
refs/heads/master
| 2023-04-27T05:29:23.731000 | 2021-05-18T17:42:52 | 2021-05-18T17:42:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package doppio.apps.explorer.view.component.singletweetlabel;
import doppio.apps.authentication.model.User;
import doppio.apps.explorer.view.component.singletweetlabel.listener.ProfileClickInvoker;
import doppio.apps.explorer.view.component.singletweetlabel.listener.ProfileClickListener;
import doppio.apps.explorer.view.component.singletweetlabel.listener.SingelTweetBottomBarListener;
import doppio.apps.post.model.Tweet;
import doppio.config.ExplorerConfig;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class SingleTweetLabel extends JLabel implements ProfileClickInvoker {
ExplorerConfig explorerConfig = new ExplorerConfig();
JLabel profilePicture;
TweetContentPanel tweetContentPanel;
JLabel textLabel;
JLabel tweetImage;
JPanel bottomBar;
ProfileClickListener profileClickListener;
public SingleTweetLabel(Tweet tweet) {
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
this.setOpaque(true);
this.setPreferredSize(new Dimension(explorerConfig.getSingleTweetLabelWidth(), explorerConfig.getSingleTweetLabelHeight()));
textLabel = new SingleTweetTextLabel(tweet.getText());
tweetImage = new SingleTweetImageLabel(tweet.getId());
tweetContentPanel = new TweetContentPanel();
tweetContentPanel.addPreferredSize(textLabel);
tweetContentPanel.addPreferredSize(tweetImage);
tweetContentPanel.add(textLabel, BorderLayout.CENTER);
tweetContentPanel.add(tweetImage, BorderLayout.SOUTH);
addPreferredSize(tweetContentPanel);
add(tweetContentPanel, BorderLayout.CENTER);
profilePicture = new ProfilePictureLabel(tweet.getCreator().getId());
profilePicture.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
checkProfileClickListener(tweet.getCreator().getId());
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
}
@Override
public void mouseEntered(MouseEvent mouseEvent) {
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
}
});
add(profilePicture, BorderLayout.WEST);
bottomBar = new SingleTweetBottomBar(new SingelTweetBottomBarListener(tweet.getId()));
addPreferredSize(bottomBar);
add(bottomBar, BorderLayout.SOUTH);
profileClickListener = null;
}
private void addPreferredSize(JComponent component) {
this.setPreferredSize(new Dimension(
(int)getPreferredSize().getWidth(),
(int)getPreferredSize().getHeight() + (int)component.getPreferredSize().getHeight()
));
}
@Override
public void setProfileClickListener(ProfileClickListener listener) {
this.profileClickListener = listener;
}
@Override
public void checkProfileClickListener(int userId) {
this.profileClickListener.runProfileClickListener(userId);
}
}
|
UTF-8
|
Java
| 3,258 |
java
|
SingleTweetLabel.java
|
Java
|
[] | null |
[] |
package doppio.apps.explorer.view.component.singletweetlabel;
import doppio.apps.authentication.model.User;
import doppio.apps.explorer.view.component.singletweetlabel.listener.ProfileClickInvoker;
import doppio.apps.explorer.view.component.singletweetlabel.listener.ProfileClickListener;
import doppio.apps.explorer.view.component.singletweetlabel.listener.SingelTweetBottomBarListener;
import doppio.apps.post.model.Tweet;
import doppio.config.ExplorerConfig;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class SingleTweetLabel extends JLabel implements ProfileClickInvoker {
ExplorerConfig explorerConfig = new ExplorerConfig();
JLabel profilePicture;
TweetContentPanel tweetContentPanel;
JLabel textLabel;
JLabel tweetImage;
JPanel bottomBar;
ProfileClickListener profileClickListener;
public SingleTweetLabel(Tweet tweet) {
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
this.setOpaque(true);
this.setPreferredSize(new Dimension(explorerConfig.getSingleTweetLabelWidth(), explorerConfig.getSingleTweetLabelHeight()));
textLabel = new SingleTweetTextLabel(tweet.getText());
tweetImage = new SingleTweetImageLabel(tweet.getId());
tweetContentPanel = new TweetContentPanel();
tweetContentPanel.addPreferredSize(textLabel);
tweetContentPanel.addPreferredSize(tweetImage);
tweetContentPanel.add(textLabel, BorderLayout.CENTER);
tweetContentPanel.add(tweetImage, BorderLayout.SOUTH);
addPreferredSize(tweetContentPanel);
add(tweetContentPanel, BorderLayout.CENTER);
profilePicture = new ProfilePictureLabel(tweet.getCreator().getId());
profilePicture.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
checkProfileClickListener(tweet.getCreator().getId());
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
}
@Override
public void mouseEntered(MouseEvent mouseEvent) {
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
}
});
add(profilePicture, BorderLayout.WEST);
bottomBar = new SingleTweetBottomBar(new SingelTweetBottomBarListener(tweet.getId()));
addPreferredSize(bottomBar);
add(bottomBar, BorderLayout.SOUTH);
profileClickListener = null;
}
private void addPreferredSize(JComponent component) {
this.setPreferredSize(new Dimension(
(int)getPreferredSize().getWidth(),
(int)getPreferredSize().getHeight() + (int)component.getPreferredSize().getHeight()
));
}
@Override
public void setProfileClickListener(ProfileClickListener listener) {
this.profileClickListener = listener;
}
@Override
public void checkProfileClickListener(int userId) {
this.profileClickListener.runProfileClickListener(userId);
}
}
| 3,258 | 0.703499 | 0.703499 | 97 | 32.587627 | 29.728931 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.505155 | false | false |
10
|
51cfdec0409f28a024af2d21e5cb2acb7600a379
| 14,302,241,116,389 |
77a091a281d426ca99575dc1e7bd9e8d482802df
|
/src/main/java/com/etoak/utils/EnumUtil.java
|
367fc1ace8a4e8c3bf8aadba1aa76b73addd4c2f
|
[] |
no_license
|
xingsshang/sell
|
https://github.com/xingsshang/sell
|
87308709d0228fbfac5f1a508efc0260453f0b14
|
a6e71bf87000bd5c475a98695176feaefed6377f
|
refs/heads/master
| 2020-03-25T01:50:51.543000 | 2018-08-03T05:38:07 | 2018-08-03T05:38:07 | 143,260,180 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.etoak.utils;
import com.etoak.enums.CodeEnum;
/**
* @Description
* @Author 邢尚尚
* @Date 2018/5/22
*/
public class EnumUtil {
public static <T extends CodeEnum> T getByCode(Integer code, Class<T> enumClass){
for(T each:enumClass.getEnumConstants()){
if(code.equals(each.getCode())){
return each;
}
}
return null;
};
}
|
UTF-8
|
Java
| 412 |
java
|
EnumUtil.java
|
Java
|
[
{
"context": "k.enums.CodeEnum;\n\n/**\n * @Description\n * @Author 邢尚尚\n * @Date 2018/5/22\n */\npublic class EnumUtil {\n ",
"end": 94,
"score": 0.9998578429222107,
"start": 91,
"tag": "NAME",
"value": "邢尚尚"
}
] | null |
[] |
package com.etoak.utils;
import com.etoak.enums.CodeEnum;
/**
* @Description
* @Author 邢尚尚
* @Date 2018/5/22
*/
public class EnumUtil {
public static <T extends CodeEnum> T getByCode(Integer code, Class<T> enumClass){
for(T each:enumClass.getEnumConstants()){
if(code.equals(each.getCode())){
return each;
}
}
return null;
};
}
| 412 | 0.583744 | 0.566502 | 19 | 20.368422 | 20.573898 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false |
10
|
a0915f73d67547a265e25853eaf6ee6e8745cea2
| 18,794,776,909,421 |
524ddc772c0796e3bc59dc9dbfc11167822f1520
|
/src/main/java/seedu/saveit/logic/parser/AddTagCommandParser.java
|
0d1b64388ee6eb9960ff19fdbd5de416b40371de
|
[
"LicenseRef-scancode-other-permissive",
"MIT"
] |
permissive
|
jasonvank/main
|
https://github.com/jasonvank/main
|
20685e7319503736cac8f1da0bc44c16efce03ca
|
34632f1eb02357c97dcc22c4f74eecd6f6b32941
|
refs/heads/master
| 2020-03-30T12:01:08.686000 | 2018-11-08T11:17:37 | 2018-11-08T11:17:37 | 151,204,478 | 0 | 2 |
NOASSERTION
| true | 2018-11-07T12:00:53 | 2018-10-02T05:25:45 | 2018-11-07T11:58:44 | 2018-11-07T12:00:53 | 16,149 | 0 | 0 | 0 |
Java
| false | null |
package seedu.saveit.logic.parser;
import static java.util.Objects.requireNonNull;
import static seedu.saveit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.saveit.commons.core.Messages.MESSAGE_INVALID_ISSUE_DISPLAYED_INDEX;
import static seedu.saveit.commons.util.StringUtil.arePrefixesNotPresent;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_DESCRIPTION;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_NEW_TAG;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_REMARK;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_SOLUTION_LINK;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_STATEMENT;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_TAG;
import java.util.HashSet;
import java.util.Set;
import seedu.saveit.commons.core.Messages;
import seedu.saveit.commons.core.index.Index;
import seedu.saveit.commons.exceptions.IllegalValueException;
import seedu.saveit.logic.commands.AddTagCommand;
import seedu.saveit.logic.parser.exceptions.ParseException;
import seedu.saveit.model.issue.Tag;
/**
* Parses input arguments and creates a new AddTagCommand object
*/
public class AddTagCommandParser implements Parser<AddTagCommand> {
private Set<Tag> tagList;
private final int indexLowerLimit = 1;
/**
* Parses the given {@code String} of arguments in the context of the AddTagCommand and returns an AddTagCommand
* object for execution.
*
* @throws ParseException if the user input does not conform the expected format
*/
public AddTagCommand parse(String args) throws ParseException {
requireNonNull(args);
Set<Index> index = new HashSet<>();
ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_TAG);
try {
String indexToCheck = argMultimap.getPreamble();
if (indexToCheck.contains("-")) {
addRangeIndex(index, indexToCheck);
} else if (indexToCheck.contains(" ")) {
addDiscreteIndex(index, indexToCheck);
} else {
index.add(ParserUtil.parseIndex(indexToCheck));
}
} catch (ParseException pe) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
if (argMultimap.getValue(PREFIX_TAG).isPresent() && arePrefixesNotPresent(args,
PREFIX_SOLUTION_LINK, PREFIX_REMARK, PREFIX_STATEMENT, PREFIX_DESCRIPTION, PREFIX_NEW_TAG)) {
tagList = ParserUtil.parseTags(argMultimap.getAllValues(PREFIX_TAG));
} else {
throw new ParseException(
String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
return new AddTagCommand(index, tagList);
}
/**
* add discrete values to the index set
*
* @param index index set
* @param indexToCheck the issue index user want to add tags
*/
private void addDiscreteIndex(Set<Index> index, String indexToCheck) throws ParseException {
String[] indexNumber = indexToCheck.split(" ");
try {
for (int i = 0; i < indexNumber.length; i++) {
addIndex(index, Integer.parseInt(indexNumber[i]));
}
} catch (NumberFormatException nfe) {
throw new ParseException(
String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
}
/**
* add range values to the index set
*
* @param index index set
* @param indexToCheck the issue index user want to add tags
*/
private void addRangeIndex(Set<Index> index, String indexToCheck) throws ParseException {
String[] indexRange = indexToCheck.split("-");
int rangeStart;
int rangeEnd;
try {
rangeStart = Integer.parseInt(indexRange[0]);
rangeEnd = Integer.parseInt(indexRange[1]);
} catch (NumberFormatException nfe) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
checkLowerBound(rangeStart);
if (rangeEnd < rangeStart) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
for (int i = rangeStart; i <= rangeEnd; i++) {
addIndex(index, i);
}
}
/**
* add the issue index to the index set.
*
* @param index index set for the issue that users want to add tags.
* @param indexToAdd the index that user want to add tags.
*/
private void addIndex(Set<Index> index, int indexToAdd) throws ParseException {
checkLowerBound(indexToAdd);
String toAdd = String.valueOf(indexToAdd);
try {
Index addIndex = ParserUtil.parseIndex(toAdd);
index.add(addIndex);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
}
/**
* check if the index is smaller than indexLowerLimit.
*
* @throws ParseException throw exception if index is smaller than indexLowerLimit.
*/
private void checkLowerBound(int indexToAdd) throws ParseException {
if (indexToAdd < indexLowerLimit) {
throw new ParseException(String
.format(MESSAGE_INVALID_ISSUE_DISPLAYED_INDEX, Messages.MESSAGE_INVALID_DISPLAYED_INDEX));
}
}
}
|
UTF-8
|
Java
| 5,619 |
java
|
AddTagCommandParser.java
|
Java
|
[] | null |
[] |
package seedu.saveit.logic.parser;
import static java.util.Objects.requireNonNull;
import static seedu.saveit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.saveit.commons.core.Messages.MESSAGE_INVALID_ISSUE_DISPLAYED_INDEX;
import static seedu.saveit.commons.util.StringUtil.arePrefixesNotPresent;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_DESCRIPTION;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_NEW_TAG;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_REMARK;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_SOLUTION_LINK;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_STATEMENT;
import static seedu.saveit.logic.parser.CliSyntax.PREFIX_TAG;
import java.util.HashSet;
import java.util.Set;
import seedu.saveit.commons.core.Messages;
import seedu.saveit.commons.core.index.Index;
import seedu.saveit.commons.exceptions.IllegalValueException;
import seedu.saveit.logic.commands.AddTagCommand;
import seedu.saveit.logic.parser.exceptions.ParseException;
import seedu.saveit.model.issue.Tag;
/**
* Parses input arguments and creates a new AddTagCommand object
*/
public class AddTagCommandParser implements Parser<AddTagCommand> {
private Set<Tag> tagList;
private final int indexLowerLimit = 1;
/**
* Parses the given {@code String} of arguments in the context of the AddTagCommand and returns an AddTagCommand
* object for execution.
*
* @throws ParseException if the user input does not conform the expected format
*/
public AddTagCommand parse(String args) throws ParseException {
requireNonNull(args);
Set<Index> index = new HashSet<>();
ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_TAG);
try {
String indexToCheck = argMultimap.getPreamble();
if (indexToCheck.contains("-")) {
addRangeIndex(index, indexToCheck);
} else if (indexToCheck.contains(" ")) {
addDiscreteIndex(index, indexToCheck);
} else {
index.add(ParserUtil.parseIndex(indexToCheck));
}
} catch (ParseException pe) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
if (argMultimap.getValue(PREFIX_TAG).isPresent() && arePrefixesNotPresent(args,
PREFIX_SOLUTION_LINK, PREFIX_REMARK, PREFIX_STATEMENT, PREFIX_DESCRIPTION, PREFIX_NEW_TAG)) {
tagList = ParserUtil.parseTags(argMultimap.getAllValues(PREFIX_TAG));
} else {
throw new ParseException(
String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
return new AddTagCommand(index, tagList);
}
/**
* add discrete values to the index set
*
* @param index index set
* @param indexToCheck the issue index user want to add tags
*/
private void addDiscreteIndex(Set<Index> index, String indexToCheck) throws ParseException {
String[] indexNumber = indexToCheck.split(" ");
try {
for (int i = 0; i < indexNumber.length; i++) {
addIndex(index, Integer.parseInt(indexNumber[i]));
}
} catch (NumberFormatException nfe) {
throw new ParseException(
String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
}
/**
* add range values to the index set
*
* @param index index set
* @param indexToCheck the issue index user want to add tags
*/
private void addRangeIndex(Set<Index> index, String indexToCheck) throws ParseException {
String[] indexRange = indexToCheck.split("-");
int rangeStart;
int rangeEnd;
try {
rangeStart = Integer.parseInt(indexRange[0]);
rangeEnd = Integer.parseInt(indexRange[1]);
} catch (NumberFormatException nfe) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
checkLowerBound(rangeStart);
if (rangeEnd < rangeStart) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
for (int i = rangeStart; i <= rangeEnd; i++) {
addIndex(index, i);
}
}
/**
* add the issue index to the index set.
*
* @param index index set for the issue that users want to add tags.
* @param indexToAdd the index that user want to add tags.
*/
private void addIndex(Set<Index> index, int indexToAdd) throws ParseException {
checkLowerBound(indexToAdd);
String toAdd = String.valueOf(indexToAdd);
try {
Index addIndex = ParserUtil.parseIndex(toAdd);
index.add(addIndex);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddTagCommand.MESSAGE_USAGE));
}
}
/**
* check if the index is smaller than indexLowerLimit.
*
* @throws ParseException throw exception if index is smaller than indexLowerLimit.
*/
private void checkLowerBound(int indexToAdd) throws ParseException {
if (indexToAdd < indexLowerLimit) {
throw new ParseException(String
.format(MESSAGE_INVALID_ISSUE_DISPLAYED_INDEX, Messages.MESSAGE_INVALID_DISPLAYED_INDEX));
}
}
}
| 5,619 | 0.666667 | 0.665955 | 147 | 37.224491 | 31.383472 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510204 | false | false |
10
|
156d7563afca37d2632fa23f9b67737b7761d0a4
| 3,049,426,791,935 |
f1ac7003b43fae7396957f5969c5e7b43d6ff8cc
|
/src/main/java/siustis/teodor/DBUtils.java
|
2519b68b9c0d9a3456ab70b41347ff8f2b2cfceb
|
[] |
no_license
|
TSiustis/DataMedApp
|
https://github.com/TSiustis/DataMedApp
|
18d4599fb51b34359ae67a290fa0e90b485c6e11
|
ea13b15689a648963c1f0991b955db24346f5f2c
|
refs/heads/master
| 2021-07-08T08:15:34.686000 | 2017-10-08T13:03:22 | 2017-10-08T13:03:22 | 106,176,611 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package siustis.teodor;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtils {
public static void close(Connection connection){
if(connection != null){
try{
connection.close();
}catch(SQLException e){
}
}
}
public static void close(Statement statement){
if(statement != null){
try{
statement.close();
}catch(SQLException e){
}
}
}
}
|
UTF-8
|
Java
| 436 |
java
|
DBUtils.java
|
Java
|
[] | null |
[] |
package siustis.teodor;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtils {
public static void close(Connection connection){
if(connection != null){
try{
connection.close();
}catch(SQLException e){
}
}
}
public static void close(Statement statement){
if(statement != null){
try{
statement.close();
}catch(SQLException e){
}
}
}
}
| 436 | 0.665138 | 0.665138 | 26 | 15.769231 | 14.085748 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false |
10
|
4adb9f690a40d8b385211578c01b19e651a8cc47
| 24,266,565,232,275 |
7773ea6f465ffecfd4f9821aad56ee1eab90d97a
|
/platform/core-impl/src/com/intellij/lang/ASTFactory.java
|
ccb6f38ab279a8ca1356fa0b6440f4ba99b7e655
|
[
"Apache-2.0"
] |
permissive
|
aghasyedbilal/intellij-community
|
https://github.com/aghasyedbilal/intellij-community
|
5fa14a8bb62a037c0d2764fb172e8109a3db471f
|
fa602b2874ea4eb59442f9937b952dcb55910b6e
|
refs/heads/master
| 2023-04-10T20:55:27.988000 | 2020-05-03T22:00:26 | 2020-05-03T22:26:23 | 261,074,802 | 2 | 0 |
Apache-2.0
| true | 2020-05-04T03:48:36 | 2020-05-04T03:48:35 | 2020-05-04T03:48:32 | 2020-05-03T23:01:03 | 3,386,775 | 0 | 0 | 0 | null | false | false |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.source.CharTableImpl;
import com.intellij.psi.impl.source.CodeFragmentElement;
import com.intellij.psi.impl.source.DummyHolderElement;
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil;
import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.impl.source.tree.LazyParseableElement;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl;
import com.intellij.psi.tree.ICompositeElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.ILazyParseableElementType;
import com.intellij.psi.tree.ILeafElementType;
import com.intellij.util.CharTable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class ASTFactory {
private static final CharTable WHITESPACES = new CharTableImpl();
// interface methods
@Nullable
public LazyParseableElement createLazy(@NotNull ILazyParseableElementType type, final CharSequence text) {
return null;
}
@Nullable
public CompositeElement createComposite(@NotNull IElementType type) {
return null;
}
@Nullable
public LeafElement createLeaf(@NotNull IElementType type, @NotNull CharSequence text) {
return null;
}
// factory methods
@NotNull
public static LazyParseableElement lazy(@NotNull final ILazyParseableElementType type, CharSequence text) {
final ASTNode node = type.createNode(text);
if (node != null) return (LazyParseableElement)node;
if (type == TokenType.CODE_FRAGMENT) {
return new CodeFragmentElement(null);
}
if (type == TokenType.DUMMY_HOLDER) {
return new DummyHolderElement(text);
}
final LazyParseableElement customLazy = factory(type).createLazy(type, text);
return customLazy != null ? customLazy : DefaultFactoryHolder.DEFAULT.createLazy(type, text);
}
@NotNull
public static CompositeElement composite(@NotNull final IElementType type) {
if (type instanceof ICompositeElementType) {
return (CompositeElement)((ICompositeElementType)type).createCompositeNode();
}
final CompositeElement customComposite = factory(type).createComposite(type);
return customComposite != null ? customComposite : DefaultFactoryHolder.DEFAULT.createComposite(type);
}
@NotNull
public static LeafElement leaf(@NotNull final IElementType type, @NotNull CharSequence text) {
if (type == TokenType.WHITE_SPACE) {
return new PsiWhiteSpaceImpl(text);
}
if (type instanceof ILeafElementType) {
return (LeafElement)((ILeafElementType)type).createLeafNode(text);
}
final LeafElement customLeaf = factory(type).createLeaf(type, text);
return customLeaf != null ? customLeaf : DefaultFactoryHolder.DEFAULT.createLeaf(type, text);
}
private static ASTFactory factory(final IElementType type) {
return LanguageASTFactory.INSTANCE.forLanguage(type.getLanguage());
}
@NotNull
public static LeafElement whitespace(final CharSequence text) {
final PsiWhiteSpaceImpl w = new PsiWhiteSpaceImpl(WHITESPACES.intern(text));
CodeEditUtil.setNodeGenerated(w, true);
return w;
}
public static class DefaultFactoryHolder {
public static final DefaultASTFactoryImpl DEFAULT = new DefaultASTFactoryImpl();
private DefaultFactoryHolder() {
}
}
}
|
UTF-8
|
Java
| 3,567 |
java
|
ASTFactory.java
|
Java
|
[] | null |
[] |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.source.CharTableImpl;
import com.intellij.psi.impl.source.CodeFragmentElement;
import com.intellij.psi.impl.source.DummyHolderElement;
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil;
import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.impl.source.tree.LazyParseableElement;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl;
import com.intellij.psi.tree.ICompositeElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.ILazyParseableElementType;
import com.intellij.psi.tree.ILeafElementType;
import com.intellij.util.CharTable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class ASTFactory {
private static final CharTable WHITESPACES = new CharTableImpl();
// interface methods
@Nullable
public LazyParseableElement createLazy(@NotNull ILazyParseableElementType type, final CharSequence text) {
return null;
}
@Nullable
public CompositeElement createComposite(@NotNull IElementType type) {
return null;
}
@Nullable
public LeafElement createLeaf(@NotNull IElementType type, @NotNull CharSequence text) {
return null;
}
// factory methods
@NotNull
public static LazyParseableElement lazy(@NotNull final ILazyParseableElementType type, CharSequence text) {
final ASTNode node = type.createNode(text);
if (node != null) return (LazyParseableElement)node;
if (type == TokenType.CODE_FRAGMENT) {
return new CodeFragmentElement(null);
}
if (type == TokenType.DUMMY_HOLDER) {
return new DummyHolderElement(text);
}
final LazyParseableElement customLazy = factory(type).createLazy(type, text);
return customLazy != null ? customLazy : DefaultFactoryHolder.DEFAULT.createLazy(type, text);
}
@NotNull
public static CompositeElement composite(@NotNull final IElementType type) {
if (type instanceof ICompositeElementType) {
return (CompositeElement)((ICompositeElementType)type).createCompositeNode();
}
final CompositeElement customComposite = factory(type).createComposite(type);
return customComposite != null ? customComposite : DefaultFactoryHolder.DEFAULT.createComposite(type);
}
@NotNull
public static LeafElement leaf(@NotNull final IElementType type, @NotNull CharSequence text) {
if (type == TokenType.WHITE_SPACE) {
return new PsiWhiteSpaceImpl(text);
}
if (type instanceof ILeafElementType) {
return (LeafElement)((ILeafElementType)type).createLeafNode(text);
}
final LeafElement customLeaf = factory(type).createLeaf(type, text);
return customLeaf != null ? customLeaf : DefaultFactoryHolder.DEFAULT.createLeaf(type, text);
}
private static ASTFactory factory(final IElementType type) {
return LanguageASTFactory.INSTANCE.forLanguage(type.getLanguage());
}
@NotNull
public static LeafElement whitespace(final CharSequence text) {
final PsiWhiteSpaceImpl w = new PsiWhiteSpaceImpl(WHITESPACES.intern(text));
CodeEditUtil.setNodeGenerated(w, true);
return w;
}
public static class DefaultFactoryHolder {
public static final DefaultASTFactoryImpl DEFAULT = new DefaultASTFactoryImpl();
private DefaultFactoryHolder() {
}
}
}
| 3,567 | 0.767031 | 0.764228 | 100 | 34.669998 | 33.649979 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false |
10
|
17805e973b57a54d92a698a1c99f8a62062eaff6
| 15,942,918,672,273 |
bc412ad0f2a2878e078d7a3713c27ea5220ce348
|
/FER_JSP/src/com/rs/fer/servlet/DisplayExpenseReportServlet.java
|
93501bf610dff5408b77eea47aeb8812cee24526
|
[] |
no_license
|
amitkumarSahoo/FER
|
https://github.com/amitkumarSahoo/FER
|
d714474134159c19b41c799ad3cdacf2828453d3
|
0d44bbc674b94d54a3bbaafaf9cf5f6b0f4efb2f
|
refs/heads/master
| 2021-04-27T08:26:55.337000 | 2018-02-22T15:04:44 | 2018-02-22T15:04:44 | 122,491,326 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.rs.fer.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.rs.fer.Util.HTMLUtil;
public class DisplayExpenseReportServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
HTMLUtil.generateHeaderAndLeftFrame(out);
out.println("<form action='ExpenseReport' method='post'>");
out.println("<table border='1' align='center'>");
out.println("<tr height='50px'>");
out.println("<td align='center' colspan='2' height='80px'>Expense Report");
out.println("</tr>");
out.println("<tr>");
out.println("<td align='center'>Expense Type</td>");
out.println("<td align='center'><input type='text' name='expenseType'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td align='center'>From Date</td>");
out.println("<td align='center'><input type='text' name='fromDate'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td align='center'>To Date</td>");
out.println("<td align='center'><input type='text' name='toDate'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td align='center' colspan='2'>");
out.println("<input type='submit' value='GetReport'> ");
out.println("</tr>");
out.println("</table>");
HTMLUtil.generateFooter(out);
}
}
|
UTF-8
|
Java
| 1,658 |
java
|
DisplayExpenseReportServlet.java
|
Java
|
[] | null |
[] |
package com.rs.fer.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.rs.fer.Util.HTMLUtil;
public class DisplayExpenseReportServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
HTMLUtil.generateHeaderAndLeftFrame(out);
out.println("<form action='ExpenseReport' method='post'>");
out.println("<table border='1' align='center'>");
out.println("<tr height='50px'>");
out.println("<td align='center' colspan='2' height='80px'>Expense Report");
out.println("</tr>");
out.println("<tr>");
out.println("<td align='center'>Expense Type</td>");
out.println("<td align='center'><input type='text' name='expenseType'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td align='center'>From Date</td>");
out.println("<td align='center'><input type='text' name='fromDate'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td align='center'>To Date</td>");
out.println("<td align='center'><input type='text' name='toDate'></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td align='center' colspan='2'>");
out.println("<input type='submit' value='GetReport'> ");
out.println("</tr>");
out.println("</table>");
HTMLUtil.generateFooter(out);
}
}
| 1,658 | 0.670688 | 0.666466 | 49 | 31.836735 | 24.729843 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false |
10
|
8f1bff5807a0e6958827f5965e8936594b81ff3b
| 28,209,345,218,767 |
9e53baa6e1d8756438c070ead09a7ef229756e1d
|
/CH4P0S4M4_2016/src/org/usfirst/frc/team3158/robot/commands/Autonomous/StraightForwardTimeout.java
|
d690a6a9eb5beb30bc59fe96b58525472cf11218
|
[] |
no_license
|
javiermomc/CH4P0S4M4_2016
|
https://github.com/javiermomc/CH4P0S4M4_2016
|
5e5a6274f737c96cebb47406b2c43950d9c50eda
|
e224279b395c13512d3e7315ed60cf5afb0cee57
|
refs/heads/master
| 2017-12-08T08:28:34.740000 | 2017-01-16T23:59:18 | 2017-01-16T23:59:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.usfirst.frc.team3158.robot.commands.Autonomous;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc.team3158.robot.commands.Chassis.*;
/**
*
*/
public class StraightForwardTimeout extends CommandGroup {
public StraightForwardTimeout(double time) {
addSequential(new ChassisStraightForwardTimeout(time));
}
}
|
UTF-8
|
Java
| 365 |
java
|
StraightForwardTimeout.java
|
Java
|
[] | null |
[] |
package org.usfirst.frc.team3158.robot.commands.Autonomous;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc.team3158.robot.commands.Chassis.*;
/**
*
*/
public class StraightForwardTimeout extends CommandGroup {
public StraightForwardTimeout(double time) {
addSequential(new ChassisStraightForwardTimeout(time));
}
}
| 365 | 0.767123 | 0.745205 | 14 | 25.071428 | 26.53694 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false |
10
|
8b488665219194e124be798f69a810808c33c0c8
| 28,020,366,695,618 |
89cfb9c157cdacc0c428bd806a6f21c5f98cb997
|
/src/main/java/net/ilexiconn/llibrary/server/config/Config.java
|
d44e7f48e1fcc23bbf7ae03c9dfbcacd74a12498
|
[] |
no_license
|
Alex-the-666/LLibrary-1
|
https://github.com/Alex-the-666/LLibrary-1
|
1e82cc851048ec0aaf7374c1d00bfb5af7ce8d10
|
712006d223d15bb4bf36406e028d969afdff4f89
|
refs/heads/1.10.2
| 2021-01-24T22:02:01.328000 | 2016-07-30T13:52:09 | 2016-07-30T13:52:09 | 65,349,113 | 1 | 0 | null | true | 2016-08-10T03:56:36 | 2016-08-10T03:56:35 | 2016-08-08T22:14:06 | 2016-07-30T13:52:32 | 906 | 0 | 0 | 0 | null | null | null |
package net.ilexiconn.llibrary.server.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Assign a new config instance to the field and register it.
*
* @author iLexiconn
* @since 1.2.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Config {
}
|
UTF-8
|
Java
| 412 |
java
|
Config.java
|
Java
|
[
{
"context": "stance to the field and register it.\n *\n * @author iLexiconn\n * @since 1.2.0\n */\n@Retention(RetentionPolicy.RU",
"end": 298,
"score": 0.999565064907074,
"start": 289,
"tag": "USERNAME",
"value": "iLexiconn"
}
] | null |
[] |
package net.ilexiconn.llibrary.server.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Assign a new config instance to the field and register it.
*
* @author iLexiconn
* @since 1.2.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Config {
}
| 412 | 0.776699 | 0.769417 | 18 | 21.888889 | 19.078461 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277778 | false | false |
10
|
956b7a6fc1e1a162277e473dcf6059c0404da2ff
| 38,276,748,545,111 |
8fcf8db391992bc040ed03513fcf9818d76a123f
|
/src/edu/wisc/ssec/hydra/Scatter.java
|
690073243da0c51034bc9955ebb1c22b08798094
|
[] |
no_license
|
tomrink/HYDRA2
|
https://github.com/tomrink/HYDRA2
|
6f31aa7989d5c26af01cbf132c55e174353c5da9
|
0bb20d808bc7f8e10f1932915e72481261a56ab5
|
refs/heads/master
| 2020-04-12T01:21:46.679000 | 2017-03-23T21:31:39 | 2017-03-23T21:31:39 | 54,215,366 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.wisc.ssec.hydra;
import ucar.visad.display.DisplayMaster;
import ucar.visad.display.XYDisplay;
import ucar.visad.display.RGBDisplayable;
import visad.georef.MapProjection;
import edu.wisc.ssec.adapter.ReprojectSwath;
import visad.*;
import java.rmi.RemoteException;
import java.awt.Dimension;
import java.awt.Component;
import java.awt.Color;
import javax.swing.JFrame;
public class Scatter {
public static ImageDisplay imageX = null;
public static ImageDisplay imageY = null;
public static FlatField X_field = null;
public static FlatField Y_field = null;
public static Linear2DSet domSetX = null;
public static Linear2DSet domSetY = null;
public static MyScatterDisplay display = null;
public static FlatField lastImage = null;
public static MapProjection lastProj = null;
public Scatter() {
}
public static void makeScatterDisplay(ImageDisplay image) {
if (imageX == null && imageY == null) {
imageX = image;
}
else if (imageY == null) {
imageY = image;
try {
X_field = (FlatField) imageX.getImageDisplayable().getData();
Y_field = (FlatField) imageY.getImageDisplayable().getData();
domSetX = (Linear2DSet) X_field.getDomainSet();
domSetY = (Linear2DSet) Y_field.getDomainSet();
// resample if sets not equal
if (!(domSetX.equals(domSetY)))
{
FlatField swathImageY = Hydra.displayableToImage.get((HydraRGBDisplayable)imageY.getImageDisplayable());
if (swathImageY == null) { // may not have original swath, eg. came from a computation
Y_field = resample(X_field, Y_field);
}
else { // New logic, first get original swath data
lastImage = Y_field;
lastProj = imageY.getMapProjection();
Linear2DSet grd = domSetX;
MapProjection mp = imageX.getMapProjection();
int mode = Hydra.getReprojectMode();
Y_field = ReprojectSwath.swathToGrid(grd, swathImageY, mode);
imageY.getImageDisplayable().setData(Y_field);
imageY.getReadoutProbe().updateData(Y_field);
imageY.setMapProjection(imageX.getMapProjection());
}
}
display = new MyScatterDisplay(X_field, Y_field, imageX, imageY);
//TODO: use if don't have/want interactive point/image selection
//ScatterDisplay display = new ScatterDisplay(X_field, imageX.name, Y_field, imageY.name);
} catch (VisADException e) {
System.out.println(e);
} catch (RemoteException e) {
System.out.println(e);
} catch (Exception e) {
e.printStackTrace();
}
}
else {
imageX = image;
imageY = null;
}
}
public static void clear() {
try {
if (lastImage != null) {
imageY.getImageDisplayable().setData(lastImage);
imageY.setMapProjection(lastProj);
imageY.getReadoutProbe().updateData(lastImage);
}
}
catch (Exception e) {
e.printStackTrace();
}
imageX = null;
imageY = null;
X_field = null;
Y_field = null;
domSetX = null;
domSetY = null;
display = null;
lastImage = null;
lastProj = null;
}
public static FlatField resample(FlatField X_field, FlatField Y_field) throws VisADException, RemoteException {
RealTupleType X_domainRef = null;
RealTupleType Y_domainRef = null;
float[][] coords = null;
float[][] Yvalues = Y_field.getFloats(false);
float[][] Xsamples = ((SampledSet)X_field.getDomainSet()).getSamples(false);
CoordinateSystem X_cs = X_field.getDomainCoordinateSystem();
if (X_cs == null) {
RealTupleType X_domain = ((FunctionType)X_field.getType()).getDomain();
}
else {
X_domainRef = X_cs.getReference();
}
CoordinateSystem Y_cs = Y_field.getDomainCoordinateSystem();
if (Y_cs == null) {
RealTupleType Y_domain = ((FunctionType)Y_field.getType()).getDomain();
}
else {
Y_domainRef = Y_cs.getReference();
}
Gridded2DSet domSetY = (Gridded2DSet) Y_field.getDomainSet();
if ( X_domainRef != null && Y_domainRef != null) {
Xsamples = X_cs.toReference(Xsamples);
Xsamples = Y_cs.fromReference(Xsamples);
}
else if ( X_domainRef == null && Y_domainRef != null ) {
Xsamples = Y_cs.fromReference(Xsamples);
}
else if ( X_domainRef != null && Y_domainRef == null) {
Xsamples = X_cs.toReference(Xsamples);
Gridded2DSet domSet = (Gridded2DSet) Y_field.getDomainSet();
// TODO this is a hack for the longitude range problem
float[] hi = domSet.getHi();
if (hi[0] <= 180f) {
for (int t=0; t<Xsamples[0].length; t++) {
if (Xsamples[0][t] > 180f) Xsamples[0][t] -=360;
}
}
}
else if (X_domainRef == null && Y_domainRef == null) {
Gridded2DSet domSet = (Gridded2DSet) Y_field.getDomainSet();
}
int length = Xsamples[0].length;
float[][] new_values = new float[1][length];
// Force weighted average for now.
if (false) { // nearest neighbor
int[] indexes = domSetY.valueToIndex(Xsamples);
for (int k=0; k<indexes.length; k++) {
new_values[0][k] = Float.NaN;
if (indexes[k] >= 0) {
new_values[0][k] = Yvalues[0][indexes[k]];
}
}
} else { // weighted average
int[][] indices = new int[length][];
float[][] coefs = new float[length][];
domSetY.valueToInterp(Xsamples, indices, coefs);
for (int i=0; i<length; i++) {
float v = Float.NaN;
int len = indices[i] == null ? 0 : indices[i].length;
if (len > 0) {
v = Yvalues[0][indices[i][0]] * coefs[i][0];
for (int k=1; k<len; k++) {
v += Yvalues[0][indices[i][k]] * coefs[i][k];
}
new_values[0][i] = v;
}
else { // values outside grid
new_values[0][i] = Float.NaN;
}
}
}
FunctionType ftype =
new FunctionType(((FunctionType)X_field.getType()).getDomain(),
((FunctionType)Y_field.getType()).getRange());
Y_field = new FlatField(ftype, X_field.getDomainSet());
Y_field.setSamples(new_values);
return Y_field;
}
}
class ScatterDisplay extends HydraDisplay {
Color[] selectorColors = new Color[] {Color.magenta, Color.green, Color.blue};
int n_selectors = selectorColors.length;
float[][] maskColorPalette = new float[][] {{0.8f,0f,0f},{0f,0.8f,0f},{0.8f,0f,0.8f}};
float[][] markColorPalette = new float[][] {{1f,0.8f,0f,0f},{1f,0f,0.8f,0f},{1f,0.8f,0f,0.8f}};
DisplayMaster master = null;
public ScatterDisplay(FlatField X_field, String X_name, FlatField Y_field, String Y_name) throws VisADException, RemoteException {
ScatterDisplayable scatterDsp = new ScatterDisplayable("scatter",
RealType.getRealType("mask"), markColorPalette, false);
float[] valsX = X_field.getFloats(false)[0];
float[] valsY = Y_field.getFloats(false)[0];
// NaN test
for (int k=0; k<valsX.length; k++) {
if (Float.isNaN(valsX[k]) || Float.isNaN(valsY[k])) {
valsX[k] = Float.NaN;
valsY[k] = Float.NaN;
}
}
Integer1DSet set = new Integer1DSet(valsX.length);
FlatField scatter = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), set);
float[] mask = new float[valsX.length];
for (int k=0; k<mask.length; k++) mask[k] = 0;
float[][] scatterFieldRange = new float[][] {valsX, valsY, mask};
scatter.setSamples(scatterFieldRange);
scatterDsp.setPointSize(2f);
scatterDsp.setRangeForColor(0,n_selectors);
float[] xRange = Hydra.minmax(valsX);
float[] yRange = Hydra.minmax(valsY);
scatterDsp.setData(scatter);
/**
scatterMarkDsp = new ScatterDisplayable("scatter",
RealType.getRealType("mask"), markColorPalette, false);
set = new Integer1DSet(2);
scatter = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), set);
scatterMarkDsp.setData(scatter);
scatterMarkDsp.setPointSize(2f);
scatterMarkDsp.setRangeForColor(0,n_selectors);
*/
master = new XYDisplay("Scatter", RealType.XAxis, RealType.YAxis);
master.setMouseFunctions(Hydra.getMouseFunctionMap());
master.draw();
((XYDisplay)master).showAxisScales(true);
AxisScale scaleX = ((XYDisplay)master).getXAxisScale();
scaleX.setTitle(X_name);
AxisScale scaleY = ((XYDisplay)master).getYAxisScale();
scaleY.setTitle(Y_name);
((XYDisplay)master).setXRange((double)xRange[0], (double)xRange[1]);
((XYDisplay)master).setYRange((double)yRange[0], (double)yRange[1]);
master.addDisplayable(scatterDsp);
//master.addDisplayable(scatterMarkDsp);
JFrame frame = Hydra.createAndShowFrame("Scatter", doMakeComponent(), new Dimension(280,280));
frame.addWindowListener(this);
}
public Component doMakeComponent() {
return master.getDisplayComponent();
}
}
class ScatterDisplayable extends RGBDisplayable {
ScatterDisplayable(String name, RealType rgbRealType, float[][] colorPalette, boolean alphaflag)
throws VisADException, RemoteException {
super(name, rgbRealType, colorPalette, alphaflag);
}
}
|
UTF-8
|
Java
| 10,072 |
java
|
Scatter.java
|
Java
|
[] | null |
[] |
package edu.wisc.ssec.hydra;
import ucar.visad.display.DisplayMaster;
import ucar.visad.display.XYDisplay;
import ucar.visad.display.RGBDisplayable;
import visad.georef.MapProjection;
import edu.wisc.ssec.adapter.ReprojectSwath;
import visad.*;
import java.rmi.RemoteException;
import java.awt.Dimension;
import java.awt.Component;
import java.awt.Color;
import javax.swing.JFrame;
public class Scatter {
public static ImageDisplay imageX = null;
public static ImageDisplay imageY = null;
public static FlatField X_field = null;
public static FlatField Y_field = null;
public static Linear2DSet domSetX = null;
public static Linear2DSet domSetY = null;
public static MyScatterDisplay display = null;
public static FlatField lastImage = null;
public static MapProjection lastProj = null;
public Scatter() {
}
public static void makeScatterDisplay(ImageDisplay image) {
if (imageX == null && imageY == null) {
imageX = image;
}
else if (imageY == null) {
imageY = image;
try {
X_field = (FlatField) imageX.getImageDisplayable().getData();
Y_field = (FlatField) imageY.getImageDisplayable().getData();
domSetX = (Linear2DSet) X_field.getDomainSet();
domSetY = (Linear2DSet) Y_field.getDomainSet();
// resample if sets not equal
if (!(domSetX.equals(domSetY)))
{
FlatField swathImageY = Hydra.displayableToImage.get((HydraRGBDisplayable)imageY.getImageDisplayable());
if (swathImageY == null) { // may not have original swath, eg. came from a computation
Y_field = resample(X_field, Y_field);
}
else { // New logic, first get original swath data
lastImage = Y_field;
lastProj = imageY.getMapProjection();
Linear2DSet grd = domSetX;
MapProjection mp = imageX.getMapProjection();
int mode = Hydra.getReprojectMode();
Y_field = ReprojectSwath.swathToGrid(grd, swathImageY, mode);
imageY.getImageDisplayable().setData(Y_field);
imageY.getReadoutProbe().updateData(Y_field);
imageY.setMapProjection(imageX.getMapProjection());
}
}
display = new MyScatterDisplay(X_field, Y_field, imageX, imageY);
//TODO: use if don't have/want interactive point/image selection
//ScatterDisplay display = new ScatterDisplay(X_field, imageX.name, Y_field, imageY.name);
} catch (VisADException e) {
System.out.println(e);
} catch (RemoteException e) {
System.out.println(e);
} catch (Exception e) {
e.printStackTrace();
}
}
else {
imageX = image;
imageY = null;
}
}
public static void clear() {
try {
if (lastImage != null) {
imageY.getImageDisplayable().setData(lastImage);
imageY.setMapProjection(lastProj);
imageY.getReadoutProbe().updateData(lastImage);
}
}
catch (Exception e) {
e.printStackTrace();
}
imageX = null;
imageY = null;
X_field = null;
Y_field = null;
domSetX = null;
domSetY = null;
display = null;
lastImage = null;
lastProj = null;
}
public static FlatField resample(FlatField X_field, FlatField Y_field) throws VisADException, RemoteException {
RealTupleType X_domainRef = null;
RealTupleType Y_domainRef = null;
float[][] coords = null;
float[][] Yvalues = Y_field.getFloats(false);
float[][] Xsamples = ((SampledSet)X_field.getDomainSet()).getSamples(false);
CoordinateSystem X_cs = X_field.getDomainCoordinateSystem();
if (X_cs == null) {
RealTupleType X_domain = ((FunctionType)X_field.getType()).getDomain();
}
else {
X_domainRef = X_cs.getReference();
}
CoordinateSystem Y_cs = Y_field.getDomainCoordinateSystem();
if (Y_cs == null) {
RealTupleType Y_domain = ((FunctionType)Y_field.getType()).getDomain();
}
else {
Y_domainRef = Y_cs.getReference();
}
Gridded2DSet domSetY = (Gridded2DSet) Y_field.getDomainSet();
if ( X_domainRef != null && Y_domainRef != null) {
Xsamples = X_cs.toReference(Xsamples);
Xsamples = Y_cs.fromReference(Xsamples);
}
else if ( X_domainRef == null && Y_domainRef != null ) {
Xsamples = Y_cs.fromReference(Xsamples);
}
else if ( X_domainRef != null && Y_domainRef == null) {
Xsamples = X_cs.toReference(Xsamples);
Gridded2DSet domSet = (Gridded2DSet) Y_field.getDomainSet();
// TODO this is a hack for the longitude range problem
float[] hi = domSet.getHi();
if (hi[0] <= 180f) {
for (int t=0; t<Xsamples[0].length; t++) {
if (Xsamples[0][t] > 180f) Xsamples[0][t] -=360;
}
}
}
else if (X_domainRef == null && Y_domainRef == null) {
Gridded2DSet domSet = (Gridded2DSet) Y_field.getDomainSet();
}
int length = Xsamples[0].length;
float[][] new_values = new float[1][length];
// Force weighted average for now.
if (false) { // nearest neighbor
int[] indexes = domSetY.valueToIndex(Xsamples);
for (int k=0; k<indexes.length; k++) {
new_values[0][k] = Float.NaN;
if (indexes[k] >= 0) {
new_values[0][k] = Yvalues[0][indexes[k]];
}
}
} else { // weighted average
int[][] indices = new int[length][];
float[][] coefs = new float[length][];
domSetY.valueToInterp(Xsamples, indices, coefs);
for (int i=0; i<length; i++) {
float v = Float.NaN;
int len = indices[i] == null ? 0 : indices[i].length;
if (len > 0) {
v = Yvalues[0][indices[i][0]] * coefs[i][0];
for (int k=1; k<len; k++) {
v += Yvalues[0][indices[i][k]] * coefs[i][k];
}
new_values[0][i] = v;
}
else { // values outside grid
new_values[0][i] = Float.NaN;
}
}
}
FunctionType ftype =
new FunctionType(((FunctionType)X_field.getType()).getDomain(),
((FunctionType)Y_field.getType()).getRange());
Y_field = new FlatField(ftype, X_field.getDomainSet());
Y_field.setSamples(new_values);
return Y_field;
}
}
class ScatterDisplay extends HydraDisplay {
Color[] selectorColors = new Color[] {Color.magenta, Color.green, Color.blue};
int n_selectors = selectorColors.length;
float[][] maskColorPalette = new float[][] {{0.8f,0f,0f},{0f,0.8f,0f},{0.8f,0f,0.8f}};
float[][] markColorPalette = new float[][] {{1f,0.8f,0f,0f},{1f,0f,0.8f,0f},{1f,0.8f,0f,0.8f}};
DisplayMaster master = null;
public ScatterDisplay(FlatField X_field, String X_name, FlatField Y_field, String Y_name) throws VisADException, RemoteException {
ScatterDisplayable scatterDsp = new ScatterDisplayable("scatter",
RealType.getRealType("mask"), markColorPalette, false);
float[] valsX = X_field.getFloats(false)[0];
float[] valsY = Y_field.getFloats(false)[0];
// NaN test
for (int k=0; k<valsX.length; k++) {
if (Float.isNaN(valsX[k]) || Float.isNaN(valsY[k])) {
valsX[k] = Float.NaN;
valsY[k] = Float.NaN;
}
}
Integer1DSet set = new Integer1DSet(valsX.length);
FlatField scatter = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), set);
float[] mask = new float[valsX.length];
for (int k=0; k<mask.length; k++) mask[k] = 0;
float[][] scatterFieldRange = new float[][] {valsX, valsY, mask};
scatter.setSamples(scatterFieldRange);
scatterDsp.setPointSize(2f);
scatterDsp.setRangeForColor(0,n_selectors);
float[] xRange = Hydra.minmax(valsX);
float[] yRange = Hydra.minmax(valsY);
scatterDsp.setData(scatter);
/**
scatterMarkDsp = new ScatterDisplayable("scatter",
RealType.getRealType("mask"), markColorPalette, false);
set = new Integer1DSet(2);
scatter = new FlatField(
new FunctionType(RealType.Generic,
new RealTupleType(RealType.XAxis, RealType.YAxis, RealType.getRealType("mask"))), set);
scatterMarkDsp.setData(scatter);
scatterMarkDsp.setPointSize(2f);
scatterMarkDsp.setRangeForColor(0,n_selectors);
*/
master = new XYDisplay("Scatter", RealType.XAxis, RealType.YAxis);
master.setMouseFunctions(Hydra.getMouseFunctionMap());
master.draw();
((XYDisplay)master).showAxisScales(true);
AxisScale scaleX = ((XYDisplay)master).getXAxisScale();
scaleX.setTitle(X_name);
AxisScale scaleY = ((XYDisplay)master).getYAxisScale();
scaleY.setTitle(Y_name);
((XYDisplay)master).setXRange((double)xRange[0], (double)xRange[1]);
((XYDisplay)master).setYRange((double)yRange[0], (double)yRange[1]);
master.addDisplayable(scatterDsp);
//master.addDisplayable(scatterMarkDsp);
JFrame frame = Hydra.createAndShowFrame("Scatter", doMakeComponent(), new Dimension(280,280));
frame.addWindowListener(this);
}
public Component doMakeComponent() {
return master.getDisplayComponent();
}
}
class ScatterDisplayable extends RGBDisplayable {
ScatterDisplayable(String name, RealType rgbRealType, float[][] colorPalette, boolean alphaflag)
throws VisADException, RemoteException {
super(name, rgbRealType, colorPalette, alphaflag);
}
}
| 10,072 | 0.594023 | 0.58469 | 285 | 34.340351 | 27.246759 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.796491 | false | false |
10
|
28fefed239011c44ba0717ed8c13419fe003ed84
| 35,613,868,839,635 |
a79e59cd52f3a948ccc694179da41e929d8b22b6
|
/src/main/java/org/example/dao/userresume/UserResumeDAO.java
|
284a285712d3ac9714d1637298b67fd0e86a9703
|
[] |
no_license
|
ISLAMBEKTOG/DBMS2
|
https://github.com/ISLAMBEKTOG/DBMS2
|
ae1e05451d80c8d25072c76166276ee1af8b7748
|
18797271a8be8486069a0a81867b45fdeb19cc84
|
refs/heads/main
| 2023-01-22T16:51:11.480000 | 2020-11-27T13:09:45 | 2020-11-27T13:09:45 | 316,504,244 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.example.dao.userresume;
import org.example.model.UserResume;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserResumeDAO extends CrudRepository<UserResume, String> {
}
|
UTF-8
|
Java
| 274 |
java
|
UserResumeDAO.java
|
Java
|
[] | null |
[] |
package org.example.dao.userresume;
import org.example.model.UserResume;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserResumeDAO extends CrudRepository<UserResume, String> {
}
| 274 | 0.846715 | 0.846715 | 9 | 29.444445 | 26.310585 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
10
|
4dcc00d8f60c5771e94fb3e0431182fea4ed12b7
| 15,195,594,333,647 |
c5a21198ac4772f8ef42b68f30b476945b5e07e5
|
/app/src/main/java/net/smimran/cloud_new/CategoryBaseNote.java
|
82e070958215357e49d2815b04842df8471bb13a
|
[] |
no_license
|
shah3093/cloud-note-2
|
https://github.com/shah3093/cloud-note-2
|
63843d3ba2bad8154805ff3bd0ebf99cd0110743
|
5032f1d07dbd311d3b098e8797631d152ab7910c
|
refs/heads/master
| 2020-04-01T06:26:46.933000 | 2018-11-07T18:37:06 | 2018-11-07T18:37:06 | 152,947,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.smimran.cloud_new;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import net.smimran.cloud_new.R;
public class CategoryBaseNote extends Fragment {
FirebaseFirestore db = FirebaseFirestore.getInstance();
private FirebaseAuth auth;
NoteAdapter noteAdapter;
RecyclerView recyclerView;
String category;
@Override
public void onStart() {
super.onStart();
noteAdapter.startListening();
}
@Override
public void onStop() {
super.onStop();
noteAdapter.stopListening();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
category = getArguments().getString("CATEGORYNAME");
auth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_all_note,container,false);
recyclerView = view.findViewById(R.id.recyclerID);
setUpRecycleView();
FloatingActionButton floatingActionButton = view.findViewById(R.id.floatingactionbutton);
return view;
}
public void setUpRecycleView() {
FirebaseUser user = auth.getCurrentUser();
Query query = db.collection(user.getUid()).whereEqualTo("category",category)
.orderBy("created_at",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class).build();
noteAdapter = new NoteAdapter(options, getActivity());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(noteAdapter);
}
public void callAddActivity(View view) {
FirebaseUser user = auth.getCurrentUser();
Intent intent = new Intent(getActivity(), AddNoteActivity.class);
intent.putExtra("USERID", user.getUid());
startActivity(intent);
}
}
|
UTF-8
|
Java
| 2,661 |
java
|
CategoryBaseNote.java
|
Java
|
[] | null |
[] |
package net.smimran.cloud_new;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import net.smimran.cloud_new.R;
public class CategoryBaseNote extends Fragment {
FirebaseFirestore db = FirebaseFirestore.getInstance();
private FirebaseAuth auth;
NoteAdapter noteAdapter;
RecyclerView recyclerView;
String category;
@Override
public void onStart() {
super.onStart();
noteAdapter.startListening();
}
@Override
public void onStop() {
super.onStop();
noteAdapter.stopListening();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
category = getArguments().getString("CATEGORYNAME");
auth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_all_note,container,false);
recyclerView = view.findViewById(R.id.recyclerID);
setUpRecycleView();
FloatingActionButton floatingActionButton = view.findViewById(R.id.floatingactionbutton);
return view;
}
public void setUpRecycleView() {
FirebaseUser user = auth.getCurrentUser();
Query query = db.collection(user.getUid()).whereEqualTo("category",category)
.orderBy("created_at",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class).build();
noteAdapter = new NoteAdapter(options, getActivity());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(noteAdapter);
}
public void callAddActivity(View view) {
FirebaseUser user = auth.getCurrentUser();
Intent intent = new Intent(getActivity(), AddNoteActivity.class);
intent.putExtra("USERID", user.getUid());
startActivity(intent);
}
}
| 2,661 | 0.723412 | 0.722285 | 89 | 28.898876 | 27.853971 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617977 | false | false |
10
|
d9596c82b80c0169b2b0e1c878966e356d2f6562
| 34,342,558,522,556 |
01a2ed96aec63f40b258105645ad2ad79a74f180
|
/SecurityTermProject/src/ChecksumService.java
|
ab1403814c14a5b083305a1714cb6b941b9c8441
|
[] |
no_license
|
semraince/BasicHostIDS
|
https://github.com/semraince/BasicHostIDS
|
01740e93650e1c6005ae85bc9ec8e6373498ebed
|
8d623c567fcfebd6b468a9e0673882f5a269a68a
|
refs/heads/master
| 2022-03-29T18:59:55.631000 | 2020-01-11T12:18:24 | 2020-01-11T12:18:24 | 233,226,829 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
public class ChecksumService {
private MessageDigest messageDigest;
private Driver driver;
private static byte[] key;
private static SecretKeySpec secretKey;
public ChecksumService(Driver driver,String secret) {
try {
setKey(secret);
messageDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.driver=driver;
}
private String calculateChecksum (String filepath, MessageDigest md) throws FileNotFoundException, IOException {
// file hashing with DigestInputStream
try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
System.out.println(dis);
while (dis.read() != -1) ; //empty loop to clear the data
md = dis.getMessageDigest();
}
// bytes to hex
StringBuilder result = new StringBuilder();
for (byte b : md.digest()) {
result.append(String.format("%02x", b));
}
System.out.println("res: "+result.toString());
return result.toString();
}
public File[] listf(String directoryName,ArrayList<File> files) throws FileNotFoundException, IOException {
File[] fList = null;
File directory = new File(directoryName);
fList = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return !name.equals(".DS_Store");
}
});
for (File file : fList) {
if (file.isFile()&&file.canRead()) {
System.out.println("file: "+file.getAbsolutePath()+" "+file.getName());
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(),files);
}
}
return fList;
}
public void createHashes(String directoryName) throws FileNotFoundException, IOException {
//File[] fList=listf(directoryName);
ArrayList<File> files=new ArrayList<>();
listf(directoryName,files);
for(int i=0;i<files.size();i++) {
File file=files.get(i);
//String calculated=file.getAbsolutePath()+","+Integer.toString(i)+",";
String calculated=calculateChecksum(file.getAbsolutePath(),messageDigest)+","+Integer.toString(i)+":";;
if(i==files.size()-1) {
calculated+=Integer.toString(Level.LAST.getLevel());
}
else {
calculated+=Integer.toString(Level.NOTLAST.getLevel());
}
//HashFile hFile=new HashFile(file.getAbsolutePath(),encrypt(calculateChecksum(file.getAbsolutePath(),messageDigest)));
HashFile hFile=new HashFile(file.getAbsolutePath(),encrypt(calculated));
driver.addElement(hFile);
}
}
public ArrayList<HashFile> calculateNewHashes(String directoryName) throws FileNotFoundException, IOException{
ArrayList<File> files=new ArrayList<>();
listf(directoryName,files);
ArrayList<HashFile> hashedFiles=new ArrayList<>();
for(int i=0;i<files.size();i++) {
File file=files.get(i);
HashFile hFile=new HashFile(file.getAbsolutePath(),calculateChecksum(file.getAbsolutePath(),messageDigest));
hashedFiles.add(hFile);
}
return hashedFiles;
}
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt)
{
try
{
//setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt)
{
try
{
//setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public ArrayList<HashFile> getHashedFiles(){
ArrayList<HashFile> encryptedFiles=new ArrayList<>();
encryptedFiles=driver.getElements();
for(int i=0;i<encryptedFiles.size();i++) {
encryptedFiles.get(i).setHashValue(decrypt(encryptedFiles.get(i).getHashValue()));
}
return encryptedFiles;
}
}
|
UTF-8
|
Java
| 4,992 |
java
|
ChecksumService.java
|
Java
|
[] | null |
[] |
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
public class ChecksumService {
private MessageDigest messageDigest;
private Driver driver;
private static byte[] key;
private static SecretKeySpec secretKey;
public ChecksumService(Driver driver,String secret) {
try {
setKey(secret);
messageDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.driver=driver;
}
private String calculateChecksum (String filepath, MessageDigest md) throws FileNotFoundException, IOException {
// file hashing with DigestInputStream
try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
System.out.println(dis);
while (dis.read() != -1) ; //empty loop to clear the data
md = dis.getMessageDigest();
}
// bytes to hex
StringBuilder result = new StringBuilder();
for (byte b : md.digest()) {
result.append(String.format("%02x", b));
}
System.out.println("res: "+result.toString());
return result.toString();
}
public File[] listf(String directoryName,ArrayList<File> files) throws FileNotFoundException, IOException {
File[] fList = null;
File directory = new File(directoryName);
fList = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return !name.equals(".DS_Store");
}
});
for (File file : fList) {
if (file.isFile()&&file.canRead()) {
System.out.println("file: "+file.getAbsolutePath()+" "+file.getName());
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(),files);
}
}
return fList;
}
public void createHashes(String directoryName) throws FileNotFoundException, IOException {
//File[] fList=listf(directoryName);
ArrayList<File> files=new ArrayList<>();
listf(directoryName,files);
for(int i=0;i<files.size();i++) {
File file=files.get(i);
//String calculated=file.getAbsolutePath()+","+Integer.toString(i)+",";
String calculated=calculateChecksum(file.getAbsolutePath(),messageDigest)+","+Integer.toString(i)+":";;
if(i==files.size()-1) {
calculated+=Integer.toString(Level.LAST.getLevel());
}
else {
calculated+=Integer.toString(Level.NOTLAST.getLevel());
}
//HashFile hFile=new HashFile(file.getAbsolutePath(),encrypt(calculateChecksum(file.getAbsolutePath(),messageDigest)));
HashFile hFile=new HashFile(file.getAbsolutePath(),encrypt(calculated));
driver.addElement(hFile);
}
}
public ArrayList<HashFile> calculateNewHashes(String directoryName) throws FileNotFoundException, IOException{
ArrayList<File> files=new ArrayList<>();
listf(directoryName,files);
ArrayList<HashFile> hashedFiles=new ArrayList<>();
for(int i=0;i<files.size();i++) {
File file=files.get(i);
HashFile hFile=new HashFile(file.getAbsolutePath(),calculateChecksum(file.getAbsolutePath(),messageDigest));
hashedFiles.add(hFile);
}
return hashedFiles;
}
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt)
{
try
{
//setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt)
{
try
{
//setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public ArrayList<HashFile> getHashedFiles(){
ArrayList<HashFile> encryptedFiles=new ArrayList<>();
encryptedFiles=driver.getElements();
for(int i=0;i<encryptedFiles.size();i++) {
encryptedFiles.get(i).setHashValue(decrypt(encryptedFiles.get(i).getHashValue()));
}
return encryptedFiles;
}
}
| 4,992 | 0.716546 | 0.711939 | 165 | 29.254545 | 27.390255 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.527273 | false | false |
10
|
ccafdeafdeb08c9425eb7414caac83222b9a9cec
| 13,855,564,568,781 |
572927a9970f4365fe8cee25e3e27fc502ce7f41
|
/sistemaDeGestionDeProyectosEIncidencias/src/sv/edu/udb/vistas/requestview/RequestList.java
|
82fd3fc6e41396bb64742786ffd471eaa2b463f7
|
[] |
no_license
|
IvonneSoriano/JavaProyect
|
https://github.com/IvonneSoriano/JavaProyect
|
e8002dfda8bf7ffec91e42838b2925b4b3567e80
|
45226bf8595f27c2ec65a3545aa66389d0805aa9
|
refs/heads/master
| 2021-03-01T17:09:06.275000 | 2020-03-27T00:10:50 | 2020-03-27T00:10:50 | 245,801,015 | 0 | 0 | null | false | 2020-03-27T00:10:52 | 2020-03-08T11:21:34 | 2020-03-26T23:58:18 | 2020-03-27T00:10:51 | 6,316 | 0 | 0 | 0 |
Java
| false | false |
/*
* 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 sv.edu.udb.vistas.requestview;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import sv.edu.udb.controllers.ProjectsController;
import sv.edu.udb.controllers.RequestController;
import sv.edu.udb.controllers.RequestTypeController;
import sv.edu.udb.models.Request;
import sv.edu.udb.models.Session;
/**
*
* @author Imer Palma
*/
public class RequestList extends javax.swing.JInternalFrame {
/**
* Creates new form RequestList
*/
ResultSet tabla;
Request reOb = new Request();
RequestController reControl = new RequestController();
List<Request> listRe = new ArrayList<>();
ProjectsController proControl = new ProjectsController();
RequestTypeController rtControl = new RequestTypeController();
DefaultTableModel modelo1;
public RequestList() {
initComponents();
loadData();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setClosable(true);
setIconifiable(true);
jLabel1.setText("Lista de solicitudes ");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(269, 269, 269))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(40, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public void loadData() {
Object[][] data = null;
String[] columns = {
"Id Solicitud", "Tipo de solicitud", "Projecto", "Fecha de solicitud", "Descripcion", "Estatus"
};
modelo1 = new DefaultTableModel(data, columns);
this.jTable1.setModel(modelo1);
listRe = reControl.findRequestByDeparmentId(Session.deparmentId);
for (Request request : listRe) {
Object[] newRow = {request.getId(), request.getIdTypeRequest(), request.getProjectId(), request.getRequestDate(),
request.getRequestDescription(), request.getRequestStatus()
};
this.jTable1.getColumnModel().getColumn(0).setPreferredWidth(250);
this.jTable1.getColumnModel().getColumn(1).setPreferredWidth(325);
this.jTable1.getColumnModel().getColumn(2).setPreferredWidth(225);
this.jTable1.getColumnModel().getColumn(3).setPreferredWidth(350);
this.jTable1.getColumnModel().getColumn(4).setPreferredWidth(600);
this.jTable1.getColumnModel().getColumn(5).setPreferredWidth(600);
modelo1.addRow(newRow);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 4,977 |
java
|
RequestList.java
|
Java
|
[
{
"context": "port sv.edu.udb.models.Session;\n\n/**\n *\n * @author Imer Palma\n */\npublic class RequestList extends javax.swing.",
"end": 588,
"score": 0.9998310208320618,
"start": 578,
"tag": "NAME",
"value": "Imer Palma"
}
] | null |
[] |
/*
* 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 sv.edu.udb.vistas.requestview;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import sv.edu.udb.controllers.ProjectsController;
import sv.edu.udb.controllers.RequestController;
import sv.edu.udb.controllers.RequestTypeController;
import sv.edu.udb.models.Request;
import sv.edu.udb.models.Session;
/**
*
* @author <NAME>
*/
public class RequestList extends javax.swing.JInternalFrame {
/**
* Creates new form RequestList
*/
ResultSet tabla;
Request reOb = new Request();
RequestController reControl = new RequestController();
List<Request> listRe = new ArrayList<>();
ProjectsController proControl = new ProjectsController();
RequestTypeController rtControl = new RequestTypeController();
DefaultTableModel modelo1;
public RequestList() {
initComponents();
loadData();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setClosable(true);
setIconifiable(true);
jLabel1.setText("Lista de solicitudes ");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(269, 269, 269))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(40, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public void loadData() {
Object[][] data = null;
String[] columns = {
"Id Solicitud", "Tipo de solicitud", "Projecto", "Fecha de solicitud", "Descripcion", "Estatus"
};
modelo1 = new DefaultTableModel(data, columns);
this.jTable1.setModel(modelo1);
listRe = reControl.findRequestByDeparmentId(Session.deparmentId);
for (Request request : listRe) {
Object[] newRow = {request.getId(), request.getIdTypeRequest(), request.getProjectId(), request.getRequestDate(),
request.getRequestDescription(), request.getRequestStatus()
};
this.jTable1.getColumnModel().getColumn(0).setPreferredWidth(250);
this.jTable1.getColumnModel().getColumn(1).setPreferredWidth(325);
this.jTable1.getColumnModel().getColumn(2).setPreferredWidth(225);
this.jTable1.getColumnModel().getColumn(3).setPreferredWidth(350);
this.jTable1.getColumnModel().getColumn(4).setPreferredWidth(600);
this.jTable1.getColumnModel().getColumn(5).setPreferredWidth(600);
modelo1.addRow(newRow);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| 4,973 | 0.650191 | 0.635523 | 131 | 36.992367 | 30.809063 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717557 | false | false |
10
|
b22a9c2c23794d006bd3023c7e2722593f8be595
| 30,803,505,450,137 |
1e7263aaae3127fad119e2778043d89e34e61a6f
|
/app/src/main/java/com/example/myhistorycleaner/Adapter/FolderVideoAdapter.java
|
441a80a7e1535b6f542f3f2e06ad49ae96c00051
|
[] |
no_license
|
Dhruva22/MyHistoryCleaner
|
https://github.com/Dhruva22/MyHistoryCleaner
|
e14d89be6383a4321614dff789ab3a1819e6c7fe
|
a4d0ba9eed89d652f5ff37c1c953aed5583d8783
|
refs/heads/master
| 2021-05-01T12:47:03.208000 | 2017-01-20T05:53:18 | 2017-01-20T05:53:18 | 79,531,907 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.myhistorycleaner.Adapter;
import android.content.Context;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.myhistorycleaner.Model.Folder;
import com.example.myhistorycleaner.R;
import java.util.ArrayList;
/**
* Created by Tej710 on 13-01-2017.
*/
public class FolderVideoAdapter extends RecyclerView.Adapter<FolderVideoAdapter.FolderVideoViewHolder> {
ArrayList<Folder> folderList;
Context context;
Clickable clickable;
public static int count=0;
public static Boolean selected_flag=false;
public FolderVideoAdapter(ArrayList<Folder> folderList, Context context, Clickable clickable) {
this.folderList = folderList;
this.context = context;
this.clickable = clickable;
}
public interface Clickable{
void cbClick(int position, String BucketId, Boolean isSelected, Boolean click);
}
@Override
public FolderVideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_folder_list,parent,false);
return new FolderVideoViewHolder(itemView);
}
@Override
public void onBindViewHolder(final FolderVideoViewHolder holder, final int position) {
final Folder folder = folderList.get(position);
if(folder.isSelected == true)
{
holder.cbFolder.setVisibility(View.VISIBLE);
holder.cbFolder.setChecked(true);
clickable.cbClick(position,folder.bucketImagesId,true,true);
}
else {
holder.cbFolder.setVisibility(View.INVISIBLE);
holder.cbFolder.setChecked(false);
clickable.cbClick(position,folder.bucketImagesId,false,true);
}
//CardView LongpressclickListener
holder.cdFolder.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
holder.cbFolder.setVisibility(View.VISIBLE);
holder.cbFolder.setChecked(true);
count++;
selected_flag=true;
clickable.cbClick(position,folder.bucketImagesId,true,true);
return true;
}
});
holder.cdFolder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(selected_flag == true && count > 0)
{ if(!holder.cbFolder.isChecked())
{
holder.cbFolder.setVisibility(View.VISIBLE);
holder.cbFolder.setChecked(true);
count++;
clickable.cbClick(position,folder.bucketImagesId,true,true);
}
else
{
holder.cbFolder.setVisibility(View.INVISIBLE);
holder.cbFolder.setChecked(false);
count--;
clickable.cbClick(position,folder.bucketImagesId,false,true);
}
}
else
{
selected_flag = false;
count = 0;
clickable.cbClick(position,folder.bucketImagesId,false,false);
}
}
});
holder.ivFolder.setImageBitmap(ThumbnailUtils.createVideoThumbnail(folder.getAbsolutePathOfImage(), MediaStore.Video.Thumbnails.FULL_SCREEN_KIND));
holder.tvFolder.setText(folder.bucketImagesName);
holder.cbFolder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
holder.cbFolder.setVisibility(View.VISIBLE);
holder.cbFolder.setChecked(true);
count++;
clickable.cbClick(position,folder.bucketImagesId, true,true);
} else {
holder.cbFolder.setVisibility(View.INVISIBLE);
holder.cbFolder.setChecked(false);
count--;
clickable.cbClick(position,folder.bucketImagesId, false,true);
}
}
});
}
@Override
public int getItemCount() {
return folderList.size();
}
public class FolderVideoViewHolder extends RecyclerView.ViewHolder{
ImageView ivFolder;
TextView tvFolder;
CheckBox cbFolder;
CardView cdFolder;
public FolderVideoViewHolder(View itemView) {
super(itemView);
ivFolder = (ImageView) itemView.findViewById(R.id.ivFolder);
tvFolder = (TextView) itemView.findViewById(R.id.tvFolder);
cbFolder = (CheckBox)itemView.findViewById(R.id.cbFolder);
cdFolder = (CardView)itemView.findViewById(R.id.cdFolder);
}
}
}
|
UTF-8
|
Java
| 5,471 |
java
|
FolderVideoAdapter.java
|
Java
|
[
{
"context": "R;\n\nimport java.util.ArrayList;\n\n/**\n * Created by Tej710 on 13-01-2017.\n */\n\npublic class FolderVideoAdapt",
"end": 632,
"score": 0.9995676279067993,
"start": 626,
"tag": "USERNAME",
"value": "Tej710"
}
] | null |
[] |
package com.example.myhistorycleaner.Adapter;
import android.content.Context;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.myhistorycleaner.Model.Folder;
import com.example.myhistorycleaner.R;
import java.util.ArrayList;
/**
* Created by Tej710 on 13-01-2017.
*/
public class FolderVideoAdapter extends RecyclerView.Adapter<FolderVideoAdapter.FolderVideoViewHolder> {
ArrayList<Folder> folderList;
Context context;
Clickable clickable;
public static int count=0;
public static Boolean selected_flag=false;
public FolderVideoAdapter(ArrayList<Folder> folderList, Context context, Clickable clickable) {
this.folderList = folderList;
this.context = context;
this.clickable = clickable;
}
public interface Clickable{
void cbClick(int position, String BucketId, Boolean isSelected, Boolean click);
}
@Override
public FolderVideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_folder_list,parent,false);
return new FolderVideoViewHolder(itemView);
}
@Override
public void onBindViewHolder(final FolderVideoViewHolder holder, final int position) {
final Folder folder = folderList.get(position);
if(folder.isSelected == true)
{
holder.cbFolder.setVisibility(View.VISIBLE);
holder.cbFolder.setChecked(true);
clickable.cbClick(position,folder.bucketImagesId,true,true);
}
else {
holder.cbFolder.setVisibility(View.INVISIBLE);
holder.cbFolder.setChecked(false);
clickable.cbClick(position,folder.bucketImagesId,false,true);
}
//CardView LongpressclickListener
holder.cdFolder.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
holder.cbFolder.setVisibility(View.VISIBLE);
holder.cbFolder.setChecked(true);
count++;
selected_flag=true;
clickable.cbClick(position,folder.bucketImagesId,true,true);
return true;
}
});
holder.cdFolder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(selected_flag == true && count > 0)
{ if(!holder.cbFolder.isChecked())
{
holder.cbFolder.setVisibility(View.VISIBLE);
holder.cbFolder.setChecked(true);
count++;
clickable.cbClick(position,folder.bucketImagesId,true,true);
}
else
{
holder.cbFolder.setVisibility(View.INVISIBLE);
holder.cbFolder.setChecked(false);
count--;
clickable.cbClick(position,folder.bucketImagesId,false,true);
}
}
else
{
selected_flag = false;
count = 0;
clickable.cbClick(position,folder.bucketImagesId,false,false);
}
}
});
holder.ivFolder.setImageBitmap(ThumbnailUtils.createVideoThumbnail(folder.getAbsolutePathOfImage(), MediaStore.Video.Thumbnails.FULL_SCREEN_KIND));
holder.tvFolder.setText(folder.bucketImagesName);
holder.cbFolder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
holder.cbFolder.setVisibility(View.VISIBLE);
holder.cbFolder.setChecked(true);
count++;
clickable.cbClick(position,folder.bucketImagesId, true,true);
} else {
holder.cbFolder.setVisibility(View.INVISIBLE);
holder.cbFolder.setChecked(false);
count--;
clickable.cbClick(position,folder.bucketImagesId, false,true);
}
}
});
}
@Override
public int getItemCount() {
return folderList.size();
}
public class FolderVideoViewHolder extends RecyclerView.ViewHolder{
ImageView ivFolder;
TextView tvFolder;
CheckBox cbFolder;
CardView cdFolder;
public FolderVideoViewHolder(View itemView) {
super(itemView);
ivFolder = (ImageView) itemView.findViewById(R.id.ivFolder);
tvFolder = (TextView) itemView.findViewById(R.id.tvFolder);
cbFolder = (CheckBox)itemView.findViewById(R.id.cbFolder);
cdFolder = (CardView)itemView.findViewById(R.id.cdFolder);
}
}
}
| 5,471 | 0.595504 | 0.592579 | 164 | 32.365852 | 29.294556 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.664634 | false | false |
10
|
9326f6558cdb10226a658cb52c6c44ed598e48a6
| 13,769,665,172,395 |
062deac7b87d708652418a822a47ac667c29505c
|
/Doctorsecond/src/com/qichuang/doctor/adapter/ZhidaoBaseAdapter.java
|
87f99c8cddffe3d2fa711cee090ee0a32e85f013
|
[] |
no_license
|
wang472501098/niuben
|
https://github.com/wang472501098/niuben
|
ca2acfb66381aa37de7ba040ea554550736dbda4
|
2e3b3b305ef54aaa2726e7dbd002622460df9175
|
refs/heads/master
| 2016-08-03T09:03:23.505000 | 2015-07-16T02:21:44 | 2015-07-16T02:21:44 | 39,171,656 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.qichuang.doctor.adapter;
import java.util.ArrayList;
import java.util.List;
import com.qichuang.doctor.activity.R;
import com.qichuang.doctor.bean.ZhidaoBean;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ZhidaoBaseAdapter extends BaseAdapter {
private List<ZhidaoBean> beans=new ArrayList<ZhidaoBean>();
private Context context;
public ZhidaoBaseAdapter(List<ZhidaoBean> beans, Context context) {
super();
this.beans = beans;
this.context = context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return beans.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return beans.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null){
holder=new ViewHolder();
convertView=LayoutInflater.from(context).inflate(R.layout.zhidao_item_layout, null);
holder.zhidao_item_content=(TextView) convertView.findViewById(R.id.zhidao_item_content);
holder.zhidao_item_name=(TextView) convertView.findViewById(R.id.zhidao_item_name);
holder.zhidao_item_zhiwei=(TextView) convertView.findViewById(R.id.zhidao_item_zhiwei);
holder.zhidao_item_yiyuan=(TextView) convertView.findViewById(R.id.zhidao_item_yiyuan);
holder.zhidao_item_tuijian=(TextView) convertView.findViewById(R.id.zhidao_item_tuijian);
convertView.setTag(holder);
}else{
holder=(ViewHolder) convertView.getTag();
}
holder.zhidao_item_name.setText(beans.get(position).getName());
holder.zhidao_item_zhiwei.setText(beans.get(position).getZhiwei());
holder.zhidao_item_yiyuan.setText(beans.get(position).getYiyuan());
holder.zhidao_item_content.setText(beans.get(position).getContent());
holder.zhidao_item_tuijian.setText(beans.get(position).getTuijianNum());
return convertView;
}
class ViewHolder{
TextView zhidao_item_name;
TextView zhidao_item_zhiwei;
TextView zhidao_item_yiyuan;
TextView zhidao_item_content;
TextView zhidao_item_tuijian;
}
}
|
UTF-8
|
Java
| 2,422 |
java
|
ZhidaoBaseAdapter.java
|
Java
|
[] | null |
[] |
package com.qichuang.doctor.adapter;
import java.util.ArrayList;
import java.util.List;
import com.qichuang.doctor.activity.R;
import com.qichuang.doctor.bean.ZhidaoBean;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ZhidaoBaseAdapter extends BaseAdapter {
private List<ZhidaoBean> beans=new ArrayList<ZhidaoBean>();
private Context context;
public ZhidaoBaseAdapter(List<ZhidaoBean> beans, Context context) {
super();
this.beans = beans;
this.context = context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return beans.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return beans.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null){
holder=new ViewHolder();
convertView=LayoutInflater.from(context).inflate(R.layout.zhidao_item_layout, null);
holder.zhidao_item_content=(TextView) convertView.findViewById(R.id.zhidao_item_content);
holder.zhidao_item_name=(TextView) convertView.findViewById(R.id.zhidao_item_name);
holder.zhidao_item_zhiwei=(TextView) convertView.findViewById(R.id.zhidao_item_zhiwei);
holder.zhidao_item_yiyuan=(TextView) convertView.findViewById(R.id.zhidao_item_yiyuan);
holder.zhidao_item_tuijian=(TextView) convertView.findViewById(R.id.zhidao_item_tuijian);
convertView.setTag(holder);
}else{
holder=(ViewHolder) convertView.getTag();
}
holder.zhidao_item_name.setText(beans.get(position).getName());
holder.zhidao_item_zhiwei.setText(beans.get(position).getZhiwei());
holder.zhidao_item_yiyuan.setText(beans.get(position).getYiyuan());
holder.zhidao_item_content.setText(beans.get(position).getContent());
holder.zhidao_item_tuijian.setText(beans.get(position).getTuijianNum());
return convertView;
}
class ViewHolder{
TextView zhidao_item_name;
TextView zhidao_item_zhiwei;
TextView zhidao_item_yiyuan;
TextView zhidao_item_content;
TextView zhidao_item_tuijian;
}
}
| 2,422 | 0.741949 | 0.741536 | 74 | 30.729731 | 26.614006 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.878378 | false | false |
10
|
2f0ff7d57fb8de9febd33640bd0df4a1b214da1b
| 34,196,529,625,118 |
59592e1f073b9b74896018f8d8add4fffa79bac5
|
/java/20210224/src/ex.java
|
c48b408a838ed9e915cfce3c4f9c89fdb47bdad7
|
[] |
no_license
|
kjw5263/AcademyStudy
|
https://github.com/kjw5263/AcademyStudy
|
75ece8d35a4a0132ff45b540148df5c45659ade3
|
426624c7370e6d9757890a5090f69732ee1f899d
|
refs/heads/master
| 2023-06-20T06:15:33.593000 | 2021-07-13T07:58:07 | 2021-07-13T07:58:07 | 352,520,983 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
*/
//ex라는 이름(식별자)의 클래스 정의
public class ex {
//main이라는 이름의 메소드 정의
public static void main(String[] args) {
System.out.println("안녕하세요.");
System.out.println(123);
System.out.println(3.14);//3.14데이터를 출력하기 위해서 printout()구문에 넣음
}
}
|
UTF-8
|
Java
| 354 |
java
|
ex.java
|
Java
|
[] | null |
[] |
/*
*/
//ex라는 이름(식별자)의 클래스 정의
public class ex {
//main이라는 이름의 메소드 정의
public static void main(String[] args) {
System.out.println("안녕하세요.");
System.out.println(123);
System.out.println(3.14);//3.14데이터를 출력하기 위해서 printout()구문에 넣음
}
}
| 354 | 0.602273 | 0.568182 | 23 | 10.347826 | 16.244354 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.956522 | false | false |
10
|
7e50c0283c706e5f2019468c333b6cb0111ec52f
| 32,323,923,871,987 |
064cd30dc70ba8d233251fb508342d41e8554446
|
/CalculatorTest/src/test/java/com/epam/cdp/calc/parallelrun/ParallelRun.java
|
32b0b1e68121c28e39025b9ea83c704aa4893781
|
[] |
no_license
|
DzmitryParkhomenka/AutomationJavaTraining
|
https://github.com/DzmitryParkhomenka/AutomationJavaTraining
|
2fa1081dcf8634976306cff6bfc323a728b8e129
|
b092045bf122828b28be61ba61b96373b5cd1746
|
refs/heads/master
| 2021-08-22T02:53:14.151000 | 2018-11-15T08:31:17 | 2018-11-15T08:31:17 | 138,878,832 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.epam.cdp.calc.parallelrun;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.epam.cdp.calc.TestResourcesTestNG;
import junit.framework.Assert;
public class ParallelRun extends TestResourcesTestNG{
@Test(dataProvider = "valuesForCosDouble")
public void cosTestDouble(double a, double expectedResult) {
double result = calculator.cos(a);
Assert.assertEquals("Cos result is incorrect", expectedResult, result);
}
@DataProvider(name = "valuesForCosDouble")
public Object[][] valuesForCosDouble(){
return new Object[][] {
{0.0, 1.0},
{30.0, 0.15425145},
{45.0, 0.52532199},
{60.0, -0.95241298},
{90.0, -0.44807362},
};
}
@Test(dataProvider = "valuesForCtgDouble")
public void ctgTestDouble(double a, double expectedResult) {
double result = calculator.ctg(a);
Assert.assertEquals("Ctg result is incorrect", expectedResult, result);
}
@DataProvider(name = "valuesForCtgDouble")
public Object[][] valuesForCtgDouble(){
Double x = Double.NaN;
return new Object[][] {
{0.0, x},
{30.0, -0.15611995},
{45.0, 0.6174},
{60.0, 3.1246},
{90.0, -0.50120278},
};
}
@Test(dataProvider = "valuesForDivDouble")
public void divTestDouble(double a, double b, double expectedResult) {
double result = calculator.div(a, b);
Assert.assertEquals("Div result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForDivDouble")
public Object[][] valuesForDivDouble(){
double x = Double.NaN;
return new Object[][] {
{2.0, 2.0, 1.0},
{-2.0, -2.0, 1.0},
{0.0, 0.0, x},
{-5.0, 2.0, -2.5},
{5.0, -2.0, -2.5},
};
}
@Test(dataProvider = "valuesForDivLong")
public void divTestLong(long a, long b, long expectedResult) {
long result = calculator.div(a, b);
Assert.assertEquals("Div result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForDivLong")
public Object[][] valuesForDivLong(){
return new Object[][] {
{2, 2, 1},
{-2, -2, 1},
{0, 0, 0},
{-5, 2, -2},
{5, -2, -2},
};
}
@Test(dataProvider = "valuesForNegativeLong")
public void isNegativeTestLong(long a, boolean expectedResult) {
boolean result = calculator.isNegative(a);
Assert.assertEquals(a + " is positive", result, expectedResult);
}
@DataProvider(name = "valuesForNegativeLong")
public Object[][] valuesForNegativeLong(){
return new Object[][] {
{1, false},
{-1, true},
{0, false},
};
}
@Test(dataProvider = "valuesForPositiveLong")
public void isPositiveTestLong(long a, boolean expectedResult) {
boolean result = calculator.isPositive(a);
Assert.assertEquals(a + " is negative", result, expectedResult);
}
@DataProvider(name = "valuesForPositiveLong")
public Object[][] valuesForPositiveLong(){
return new Object[][] {
{1, true},
{-1, false},
{0, false},
};
}
@Test(dataProvider = "valuesForMulDouble")
public void mulTestLong(double a, double b, double expectedResult) {
double result = calculator.mult(a, b);
Assert.assertEquals("Mul result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForMulDouble")
public Object[][] valuesForMulDouble(){
return new Object[][] {
{2.0, 2.0, 4.0},
{2.1, 2.1, 4.41},
{2.5, 2.5, 6.25},
{3.6, 3.6, 12,96},
{-2.0, 2.0, -4.0},
{2.0, -2.0, -4.0},
{-2.0, -2.0, 4.0},
{0.0, 0.0, 0.0},
{0.0, 2.0, 0.0},
{2.0, 0.0, 0.0},
};
}
@Test(dataProvider = "valuesForMulLong")
public void mulTestLong(long a, long b, long expectedResult) {
long result = calculator.mult(a, b);
Assert.assertEquals("Sum result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForMulLong")
public Object[][] valuesForMulLong(){
return new Object[][] {
{2, 2, 4},
{-2, 2, -4},
{2, -2, -4},
{-2, -2, 4},
{0, 0, 0},
{0, 2, 0},
{2, 0, 0},
};
}
@Test(dataProvider = "valuesForPowDouble")
public void powTestDouble(double a, double b, double expectedResult) {
double result = calculator.pow(a, b);
Assert.assertEquals("Pow result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForPowDouble")
public Object[][] valuesForPowDouble(){
return new Object[][] {
{2.0, 2.0, 4.0},
{10.0, 10.0, 10000000000.0},
{-2.0, 2.0, 4.0},
{2.0, -2.0, 0.25},
{3.0, 3.0, 27.0},
{0.0, 0.0, 1.0},
};
}
@Test(dataProvider = "valuesForSinDouble")
public void sinTestDouble(double a, double expectedResult) {
double result = calculator.sin(a);
Assert.assertEquals("Sin result is incorrect", expectedResult, result);
}
@DataProvider(name = "valuesForSinDouble")
public Object[][] valuesForSinDouble(){
return new Object[][] {
{0.0, 0.0},
{30.0, -0.9880316240928618},
{45.0, 0.8509035245341184},
{60.0, -0.3048106211022167},
{90.0, 0.8939966636005579},
};
}
@Test(dataProvider = "valuesForSqrtDouble")
public void sqrtTestDouble(double a, double expectedResult) {
double result = calculator.sqrt(a);
Assert.assertEquals("Sqrt result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSqrtDouble")
public Object[][] valuesForSqrtDouble(){
return new Object[][] {
{4.0, 2.0},
{-4.0, 0.0},
{0.0, 0.0},
{13.0, 3.605551275463989},
};
}
@Test(dataProvider = "valuesForSubDouble")
public void subTestDouble(double a, double b, double expectedResult) {
double result = calculator.sub(a, b);
Assert.assertEquals("Sub result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSubDouble")
public Object[][] valuesForSubDouble(){
return new Object[][] {
{5.0, 2.0, 3.0},
{0.0, 0.0, 0.0},
{3.1, 1.5, 1.6},
{-5.0, 2.0, -7.0},
{5.0, -2.0, 7.0},
{-5.0, -2.0, -3.0},
};
}
@Test(dataProvider = "valuesForSubLong")
public void subTestLong(long a, long b, long expectedResult) {
long result = calculator.sub(a, b);
Assert.assertEquals("Sub result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSubLong")
public Object[][] valuesForSubLong(){
return new Object[][] {
{5, 2, 3},
{0, 0, 0},
{-5, 2, -7},
{5, -2, 7},
{-5, -2, -3},
};
}
@Test(dataProvider = "valuesForSumDouble")
public void sumTestDouble(double a, double b, double expectedResult) {
double result = calculator.sum(a, b);
Assert.assertEquals("Sum result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSumDouble")
public Object[][] valuesForSumDouble(){
return new Object[][] {
{1.0, 1.5, 2.5},
{0.0, 0.0, 0.0},
{-1.0, 2.5, 1.5},
{-1.1, -1.1, -2.2},
{-0.0, -0.0, 0.0},
};
}
@Test(dataProvider = "valuesForSumLong")
public void sumTestLong(long a, long b, long expectedResult) {
long result = calculator.sum(a, b);
Assert.assertEquals("Sum result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSumLong")
public Object[][] valuesForSumLong(){
return new Object[][] {
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
{-1, -1, -2},
{-0, -0, 0},
};
}
@Test(dataProvider = "valuesForTgDouble")
public void tgTestDouble(double a, double expectedResult) {
double result = calculator.tg(a);
Assert.assertEquals("Tg result is incorrect", expectedResult, result);
}
@DataProvider(name = "valuesForTgDouble")
public Object[][] valuesForTgDouble(){
return new Object[][] {
{0.0, 0.0},
{30.0, -6.4053312},
{45.0, 1.61977519},
{60.0, 0.32004039},
{90.0, -1.99520041},
};
}
}
|
UTF-8
|
Java
| 7,542 |
java
|
ParallelRun.java
|
Java
|
[] | null |
[] |
package com.epam.cdp.calc.parallelrun;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.epam.cdp.calc.TestResourcesTestNG;
import junit.framework.Assert;
public class ParallelRun extends TestResourcesTestNG{
@Test(dataProvider = "valuesForCosDouble")
public void cosTestDouble(double a, double expectedResult) {
double result = calculator.cos(a);
Assert.assertEquals("Cos result is incorrect", expectedResult, result);
}
@DataProvider(name = "valuesForCosDouble")
public Object[][] valuesForCosDouble(){
return new Object[][] {
{0.0, 1.0},
{30.0, 0.15425145},
{45.0, 0.52532199},
{60.0, -0.95241298},
{90.0, -0.44807362},
};
}
@Test(dataProvider = "valuesForCtgDouble")
public void ctgTestDouble(double a, double expectedResult) {
double result = calculator.ctg(a);
Assert.assertEquals("Ctg result is incorrect", expectedResult, result);
}
@DataProvider(name = "valuesForCtgDouble")
public Object[][] valuesForCtgDouble(){
Double x = Double.NaN;
return new Object[][] {
{0.0, x},
{30.0, -0.15611995},
{45.0, 0.6174},
{60.0, 3.1246},
{90.0, -0.50120278},
};
}
@Test(dataProvider = "valuesForDivDouble")
public void divTestDouble(double a, double b, double expectedResult) {
double result = calculator.div(a, b);
Assert.assertEquals("Div result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForDivDouble")
public Object[][] valuesForDivDouble(){
double x = Double.NaN;
return new Object[][] {
{2.0, 2.0, 1.0},
{-2.0, -2.0, 1.0},
{0.0, 0.0, x},
{-5.0, 2.0, -2.5},
{5.0, -2.0, -2.5},
};
}
@Test(dataProvider = "valuesForDivLong")
public void divTestLong(long a, long b, long expectedResult) {
long result = calculator.div(a, b);
Assert.assertEquals("Div result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForDivLong")
public Object[][] valuesForDivLong(){
return new Object[][] {
{2, 2, 1},
{-2, -2, 1},
{0, 0, 0},
{-5, 2, -2},
{5, -2, -2},
};
}
@Test(dataProvider = "valuesForNegativeLong")
public void isNegativeTestLong(long a, boolean expectedResult) {
boolean result = calculator.isNegative(a);
Assert.assertEquals(a + " is positive", result, expectedResult);
}
@DataProvider(name = "valuesForNegativeLong")
public Object[][] valuesForNegativeLong(){
return new Object[][] {
{1, false},
{-1, true},
{0, false},
};
}
@Test(dataProvider = "valuesForPositiveLong")
public void isPositiveTestLong(long a, boolean expectedResult) {
boolean result = calculator.isPositive(a);
Assert.assertEquals(a + " is negative", result, expectedResult);
}
@DataProvider(name = "valuesForPositiveLong")
public Object[][] valuesForPositiveLong(){
return new Object[][] {
{1, true},
{-1, false},
{0, false},
};
}
@Test(dataProvider = "valuesForMulDouble")
public void mulTestLong(double a, double b, double expectedResult) {
double result = calculator.mult(a, b);
Assert.assertEquals("Mul result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForMulDouble")
public Object[][] valuesForMulDouble(){
return new Object[][] {
{2.0, 2.0, 4.0},
{2.1, 2.1, 4.41},
{2.5, 2.5, 6.25},
{3.6, 3.6, 12,96},
{-2.0, 2.0, -4.0},
{2.0, -2.0, -4.0},
{-2.0, -2.0, 4.0},
{0.0, 0.0, 0.0},
{0.0, 2.0, 0.0},
{2.0, 0.0, 0.0},
};
}
@Test(dataProvider = "valuesForMulLong")
public void mulTestLong(long a, long b, long expectedResult) {
long result = calculator.mult(a, b);
Assert.assertEquals("Sum result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForMulLong")
public Object[][] valuesForMulLong(){
return new Object[][] {
{2, 2, 4},
{-2, 2, -4},
{2, -2, -4},
{-2, -2, 4},
{0, 0, 0},
{0, 2, 0},
{2, 0, 0},
};
}
@Test(dataProvider = "valuesForPowDouble")
public void powTestDouble(double a, double b, double expectedResult) {
double result = calculator.pow(a, b);
Assert.assertEquals("Pow result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForPowDouble")
public Object[][] valuesForPowDouble(){
return new Object[][] {
{2.0, 2.0, 4.0},
{10.0, 10.0, 10000000000.0},
{-2.0, 2.0, 4.0},
{2.0, -2.0, 0.25},
{3.0, 3.0, 27.0},
{0.0, 0.0, 1.0},
};
}
@Test(dataProvider = "valuesForSinDouble")
public void sinTestDouble(double a, double expectedResult) {
double result = calculator.sin(a);
Assert.assertEquals("Sin result is incorrect", expectedResult, result);
}
@DataProvider(name = "valuesForSinDouble")
public Object[][] valuesForSinDouble(){
return new Object[][] {
{0.0, 0.0},
{30.0, -0.9880316240928618},
{45.0, 0.8509035245341184},
{60.0, -0.3048106211022167},
{90.0, 0.8939966636005579},
};
}
@Test(dataProvider = "valuesForSqrtDouble")
public void sqrtTestDouble(double a, double expectedResult) {
double result = calculator.sqrt(a);
Assert.assertEquals("Sqrt result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSqrtDouble")
public Object[][] valuesForSqrtDouble(){
return new Object[][] {
{4.0, 2.0},
{-4.0, 0.0},
{0.0, 0.0},
{13.0, 3.605551275463989},
};
}
@Test(dataProvider = "valuesForSubDouble")
public void subTestDouble(double a, double b, double expectedResult) {
double result = calculator.sub(a, b);
Assert.assertEquals("Sub result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSubDouble")
public Object[][] valuesForSubDouble(){
return new Object[][] {
{5.0, 2.0, 3.0},
{0.0, 0.0, 0.0},
{3.1, 1.5, 1.6},
{-5.0, 2.0, -7.0},
{5.0, -2.0, 7.0},
{-5.0, -2.0, -3.0},
};
}
@Test(dataProvider = "valuesForSubLong")
public void subTestLong(long a, long b, long expectedResult) {
long result = calculator.sub(a, b);
Assert.assertEquals("Sub result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSubLong")
public Object[][] valuesForSubLong(){
return new Object[][] {
{5, 2, 3},
{0, 0, 0},
{-5, 2, -7},
{5, -2, 7},
{-5, -2, -3},
};
}
@Test(dataProvider = "valuesForSumDouble")
public void sumTestDouble(double a, double b, double expectedResult) {
double result = calculator.sum(a, b);
Assert.assertEquals("Sum result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSumDouble")
public Object[][] valuesForSumDouble(){
return new Object[][] {
{1.0, 1.5, 2.5},
{0.0, 0.0, 0.0},
{-1.0, 2.5, 1.5},
{-1.1, -1.1, -2.2},
{-0.0, -0.0, 0.0},
};
}
@Test(dataProvider = "valuesForSumLong")
public void sumTestLong(long a, long b, long expectedResult) {
long result = calculator.sum(a, b);
Assert.assertEquals("Sum result is incorrect.", result, expectedResult);
}
@DataProvider(name = "valuesForSumLong")
public Object[][] valuesForSumLong(){
return new Object[][] {
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
{-1, -1, -2},
{-0, -0, 0},
};
}
@Test(dataProvider = "valuesForTgDouble")
public void tgTestDouble(double a, double expectedResult) {
double result = calculator.tg(a);
Assert.assertEquals("Tg result is incorrect", expectedResult, result);
}
@DataProvider(name = "valuesForTgDouble")
public Object[][] valuesForTgDouble(){
return new Object[][] {
{0.0, 0.0},
{30.0, -6.4053312},
{45.0, 1.61977519},
{60.0, 0.32004039},
{90.0, -1.99520041},
};
}
}
| 7,542 | 0.636303 | 0.564704 | 288 | 25.1875 | 21.312969 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.041667 | false | false |
10
|
7c63b36b7b1658419b2f2fdf6dd7feba764bd893
| 19,275,813,283,367 |
4d893f7f59c38d703f90f1509944407862c8d0e9
|
/app/src/main/java/com/example/zxg/myprogram/widget/MovableView.java
|
2f8d0971600083481b785fdf9ffbd04746590668
|
[] |
no_license
|
thedayisantherday/myProgram
|
https://github.com/thedayisantherday/myProgram
|
b96b6d36c7974c22d18808ea51dbab145cda407c
|
e0bd8b778bbcf9a39f224ad79d90fdf14326f456
|
refs/heads/master
| 2023-09-06T05:27:18.195000 | 2023-08-25T07:36:09 | 2023-08-25T07:36:09 | 143,838,404 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.zxg.myprogram.widget;
import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import com.example.zxg.myprogram.utils.DPIUtil;
public class MovableView extends LinearLayout {
public static boolean isTouchedMovableView = false; // MovableView是否被touch
private Context mContext;
// 活动区域
private int startX, startY, offsetX, offsetY, mStatusBarHeight;
public int MIN_MOVE_DISTANCE = 5; // 滑动的最小阈值,只有大于该值才会认为时滑动
private int usableHeightPrevious;
private Rect mParentRect, mActiveRegionRect, mMarginRect = new Rect();
private ActiveRegionListener mActiveRegionListener;
public MovableView(Context context) {
this(context, null);
}
public MovableView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MovableView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
init();
}
private void init() {
isTouchedMovableView = false;
mStatusBarHeight = getStatusBarHeight();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mActiveRegionRect = getActiveRegionRect();
initRootViewLayoutListener();
}
}, 500);
}
public void initRootViewLayoutListener() {
final View viewObserving = getRootView().findViewById(android.R.id.content);
if (viewObserving != null) {
//给View添加全局的布局监听器
viewObserving.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
int usableHeightNow = computeUsableHeight(viewObserving);
int offset = usableHeightPrevious - usableHeightNow;
if (usableHeightPrevious != 0 && offset != 0) {
mActiveRegionRect = getActiveRegionRect();
int maxTop = mActiveRegionRect.bottom - getHeight();
if (maxTop - getY() < Math.abs(offset)) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams)getLayoutParams();
if (offset > 0) {
marginLayoutParams.topMargin = maxTop - mParentRect.top - offset;
} else {
marginLayoutParams.topMargin = maxTop - mParentRect.top;
}
marginLayoutParams.bottomMargin = mMarginRect.bottom;
setLayoutParams(marginLayoutParams);
} else if (getY() - mActiveRegionRect.top < Math.abs(offset)) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams)getLayoutParams();
marginLayoutParams.topMargin = mMarginRect.top;
if (offset > 0) {
marginLayoutParams.bottomMargin = mParentRect.bottom - (mActiveRegionRect.top + getHeight()) - offset;
} else {
marginLayoutParams.bottomMargin = mParentRect.bottom - (mActiveRegionRect.top + getHeight());
}
setLayoutParams(marginLayoutParams);
}
}
usableHeightPrevious = usableHeightNow;
}
});
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
Log.i("++onInterceptTouchEvent", "ACTION = " + event.getAction() + ", event.getX() = " + event.getX() + ", event.getY() = " + event.getY() + ", startX = " + startX + ", startY = " + startY);
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
startX = (int)event.getX();
startY = (int)event.getY();
setClickable(true);
break;
case MotionEvent.ACTION_MOVE: // 当子view处理事件时,才会执行
if (Math.abs(event.getX()-startX) > MIN_MOVE_DISTANCE || Math.abs(event.getY()-startY) > MIN_MOVE_DISTANCE)
return true;
break;
}
return super.onInterceptTouchEvent(event);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i("+++onTouchEvent", "ACTION = " + event.getAction() + ", event.getX() = " + event.getX() + ", event.getY() = " + event.getY() + ", startX = " + startX + ", startY = " + startY);
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
isTouchedMovableView = true;
if (Math.abs(event.getX()-startX) > MIN_MOVE_DISTANCE || Math.abs(event.getY()-startY) > MIN_MOVE_DISTANCE){
offsetX = (int)(event.getX()-startX);
offsetY = (int)(event.getY()-startY);
int left = Math.min(Math.max(offsetX + getLeft(), mActiveRegionRect.left), mActiveRegionRect.right - getWidth());
int top = Math.min(Math.max(offsetY + getTop(), mActiveRegionRect.top), mActiveRegionRect.bottom - getHeight());
layout(left, top, left + getWidth(), top + getHeight());
// 滑动时屏蔽点击事件
setClickable(false);
Log.i("+++onTouchEvent move", "offsetX = " + offsetX + ", offsetY = " + offsetY + ", getLeft() = " + getLeft() + ", getTop() = " + getTop() + ", getRight() = " + getRight() + ", getBottom() = " + getBottom());
}
break;
case MotionEvent.ACTION_UP:
offsetY = (int)(event.getY()-startY);
case MotionEvent.ACTION_CANCEL: // 有可能不执行ACTION_UP动作,而直接从ACTION_MOVE到ACTION_CANCEL
isTouchedMovableView = false;
int top = Math.min(Math.max(offsetY + getTop(), mActiveRegionRect.top), mActiveRegionRect.bottom - getHeight());
layout(mActiveRegionRect.right - getWidth(), top, mActiveRegionRect.right, top + getHeight());
// 设置LayoutParams,保证MovableView隐藏后在重新显示时在滑动的最后位置,不会回到初始位置
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams)getLayoutParams();
marginLayoutParams.bottomMargin = mParentRect.bottom - getBottom();
marginLayoutParams.topMargin = top - mParentRect.top;
setLayoutParams(marginLayoutParams);
Log.i("+++onTouchEvent up", "DPIUtil.getWidth() = " + DPIUtil.getWidth(mContext) + ", getWidth() = " + getWidth() + ", getLeft() = " + getLeft() + ", getTop() = " + getTop() + ", getRight() = " + getRight() + ", getBottom() = " + getBottom());
break;
}
return super.onTouchEvent(event);
}
/**
* 获取状态栏的高度
*/
public int getStatusBarHeight() {
int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return mContext.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
private int computeUsableHeight(View viewObserved) {
Rect r = new Rect();
viewObserved.getWindowVisibleDisplayFrame(r);
return (r.bottom - r.top);
}
public Rect getActiveRegionRect() {
if (mActiveRegionListener != null && mActiveRegionListener.getActiveRegion() != null) {
mMarginRect = mActiveRegionListener.getActiveRegion();
}
Rect parentRect = getParentRect();
int activeWidth = parentRect.right - parentRect.left - getWidth();
int activeHight = parentRect.bottom - parentRect.top - getHeight();
mMarginRect.left = mMarginRect.left > activeWidth ? activeWidth : mMarginRect.left;
mMarginRect.top = mMarginRect.top > activeHight ? activeHight : mMarginRect.top;
int l = parentRect.left + mMarginRect.left;
int t = parentRect.top + mMarginRect.top;
mMarginRect.right = parentRect.right - (l + getWidth()) > mMarginRect.right ? mMarginRect.right : parentRect.right - (l + getWidth());
mMarginRect.bottom = parentRect.bottom - (t + getHeight()) > mMarginRect.bottom ? mMarginRect.bottom : parentRect.bottom - (t + getHeight());
int r = parentRect.right - mMarginRect.right;
int b = parentRect.bottom - mMarginRect.bottom;
return new Rect(l, t, r, b);
}
private Rect getParentRect() {
View parentView = (View) getParent();
if (parentView == null) {
mParentRect = new Rect(0, 0, DPIUtil.getWidth(mContext), DPIUtil.getHeight(mContext) - mStatusBarHeight);
} else {
mParentRect = new Rect(parentView.getPaddingLeft(), parentView.getPaddingTop(),
parentView.getWidth() - parentView.getPaddingRight(), parentView.getHeight() - parentView.getPaddingBottom());
}
return mParentRect;
}
public void setActiveRegionListener(ActiveRegionListener activeRegionListener) {
this.mActiveRegionListener = activeRegionListener;
}
public interface ActiveRegionListener {
Rect getActiveRegion();
}
}
|
UTF-8
|
Java
| 9,971 |
java
|
MovableView.java
|
Java
|
[] | null |
[] |
package com.example.zxg.myprogram.widget;
import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import com.example.zxg.myprogram.utils.DPIUtil;
public class MovableView extends LinearLayout {
public static boolean isTouchedMovableView = false; // MovableView是否被touch
private Context mContext;
// 活动区域
private int startX, startY, offsetX, offsetY, mStatusBarHeight;
public int MIN_MOVE_DISTANCE = 5; // 滑动的最小阈值,只有大于该值才会认为时滑动
private int usableHeightPrevious;
private Rect mParentRect, mActiveRegionRect, mMarginRect = new Rect();
private ActiveRegionListener mActiveRegionListener;
public MovableView(Context context) {
this(context, null);
}
public MovableView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MovableView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
init();
}
private void init() {
isTouchedMovableView = false;
mStatusBarHeight = getStatusBarHeight();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mActiveRegionRect = getActiveRegionRect();
initRootViewLayoutListener();
}
}, 500);
}
public void initRootViewLayoutListener() {
final View viewObserving = getRootView().findViewById(android.R.id.content);
if (viewObserving != null) {
//给View添加全局的布局监听器
viewObserving.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
int usableHeightNow = computeUsableHeight(viewObserving);
int offset = usableHeightPrevious - usableHeightNow;
if (usableHeightPrevious != 0 && offset != 0) {
mActiveRegionRect = getActiveRegionRect();
int maxTop = mActiveRegionRect.bottom - getHeight();
if (maxTop - getY() < Math.abs(offset)) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams)getLayoutParams();
if (offset > 0) {
marginLayoutParams.topMargin = maxTop - mParentRect.top - offset;
} else {
marginLayoutParams.topMargin = maxTop - mParentRect.top;
}
marginLayoutParams.bottomMargin = mMarginRect.bottom;
setLayoutParams(marginLayoutParams);
} else if (getY() - mActiveRegionRect.top < Math.abs(offset)) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams)getLayoutParams();
marginLayoutParams.topMargin = mMarginRect.top;
if (offset > 0) {
marginLayoutParams.bottomMargin = mParentRect.bottom - (mActiveRegionRect.top + getHeight()) - offset;
} else {
marginLayoutParams.bottomMargin = mParentRect.bottom - (mActiveRegionRect.top + getHeight());
}
setLayoutParams(marginLayoutParams);
}
}
usableHeightPrevious = usableHeightNow;
}
});
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
Log.i("++onInterceptTouchEvent", "ACTION = " + event.getAction() + ", event.getX() = " + event.getX() + ", event.getY() = " + event.getY() + ", startX = " + startX + ", startY = " + startY);
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
startX = (int)event.getX();
startY = (int)event.getY();
setClickable(true);
break;
case MotionEvent.ACTION_MOVE: // 当子view处理事件时,才会执行
if (Math.abs(event.getX()-startX) > MIN_MOVE_DISTANCE || Math.abs(event.getY()-startY) > MIN_MOVE_DISTANCE)
return true;
break;
}
return super.onInterceptTouchEvent(event);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i("+++onTouchEvent", "ACTION = " + event.getAction() + ", event.getX() = " + event.getX() + ", event.getY() = " + event.getY() + ", startX = " + startX + ", startY = " + startY);
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
isTouchedMovableView = true;
if (Math.abs(event.getX()-startX) > MIN_MOVE_DISTANCE || Math.abs(event.getY()-startY) > MIN_MOVE_DISTANCE){
offsetX = (int)(event.getX()-startX);
offsetY = (int)(event.getY()-startY);
int left = Math.min(Math.max(offsetX + getLeft(), mActiveRegionRect.left), mActiveRegionRect.right - getWidth());
int top = Math.min(Math.max(offsetY + getTop(), mActiveRegionRect.top), mActiveRegionRect.bottom - getHeight());
layout(left, top, left + getWidth(), top + getHeight());
// 滑动时屏蔽点击事件
setClickable(false);
Log.i("+++onTouchEvent move", "offsetX = " + offsetX + ", offsetY = " + offsetY + ", getLeft() = " + getLeft() + ", getTop() = " + getTop() + ", getRight() = " + getRight() + ", getBottom() = " + getBottom());
}
break;
case MotionEvent.ACTION_UP:
offsetY = (int)(event.getY()-startY);
case MotionEvent.ACTION_CANCEL: // 有可能不执行ACTION_UP动作,而直接从ACTION_MOVE到ACTION_CANCEL
isTouchedMovableView = false;
int top = Math.min(Math.max(offsetY + getTop(), mActiveRegionRect.top), mActiveRegionRect.bottom - getHeight());
layout(mActiveRegionRect.right - getWidth(), top, mActiveRegionRect.right, top + getHeight());
// 设置LayoutParams,保证MovableView隐藏后在重新显示时在滑动的最后位置,不会回到初始位置
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams)getLayoutParams();
marginLayoutParams.bottomMargin = mParentRect.bottom - getBottom();
marginLayoutParams.topMargin = top - mParentRect.top;
setLayoutParams(marginLayoutParams);
Log.i("+++onTouchEvent up", "DPIUtil.getWidth() = " + DPIUtil.getWidth(mContext) + ", getWidth() = " + getWidth() + ", getLeft() = " + getLeft() + ", getTop() = " + getTop() + ", getRight() = " + getRight() + ", getBottom() = " + getBottom());
break;
}
return super.onTouchEvent(event);
}
/**
* 获取状态栏的高度
*/
public int getStatusBarHeight() {
int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return mContext.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
private int computeUsableHeight(View viewObserved) {
Rect r = new Rect();
viewObserved.getWindowVisibleDisplayFrame(r);
return (r.bottom - r.top);
}
public Rect getActiveRegionRect() {
if (mActiveRegionListener != null && mActiveRegionListener.getActiveRegion() != null) {
mMarginRect = mActiveRegionListener.getActiveRegion();
}
Rect parentRect = getParentRect();
int activeWidth = parentRect.right - parentRect.left - getWidth();
int activeHight = parentRect.bottom - parentRect.top - getHeight();
mMarginRect.left = mMarginRect.left > activeWidth ? activeWidth : mMarginRect.left;
mMarginRect.top = mMarginRect.top > activeHight ? activeHight : mMarginRect.top;
int l = parentRect.left + mMarginRect.left;
int t = parentRect.top + mMarginRect.top;
mMarginRect.right = parentRect.right - (l + getWidth()) > mMarginRect.right ? mMarginRect.right : parentRect.right - (l + getWidth());
mMarginRect.bottom = parentRect.bottom - (t + getHeight()) > mMarginRect.bottom ? mMarginRect.bottom : parentRect.bottom - (t + getHeight());
int r = parentRect.right - mMarginRect.right;
int b = parentRect.bottom - mMarginRect.bottom;
return new Rect(l, t, r, b);
}
private Rect getParentRect() {
View parentView = (View) getParent();
if (parentView == null) {
mParentRect = new Rect(0, 0, DPIUtil.getWidth(mContext), DPIUtil.getHeight(mContext) - mStatusBarHeight);
} else {
mParentRect = new Rect(parentView.getPaddingLeft(), parentView.getPaddingTop(),
parentView.getWidth() - parentView.getPaddingRight(), parentView.getHeight() - parentView.getPaddingBottom());
}
return mParentRect;
}
public void setActiveRegionListener(ActiveRegionListener activeRegionListener) {
this.mActiveRegionListener = activeRegionListener;
}
public interface ActiveRegionListener {
Rect getActiveRegion();
}
}
| 9,971 | 0.596101 | 0.594767 | 209 | 45.626793 | 43.380749 | 259 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.799043 | false | false |
10
|
28719df11a7712e075b87080eb561424ba16d093
| 15,564,961,547,728 |
04891604f6fa6f70b5fbe98d60cb093dcd96bddd
|
/src/main/java/com/yx/watchmall/interceptor/InterceptorConfig.java
|
94fb5d54c553ef7a7c4c1b246ea908cbafe0d27e
|
[] |
no_license
|
yx2512/watchmall
|
https://github.com/yx2512/watchmall
|
90a67067374bdff544d92a10e046bf449fd03926
|
2a7c56a915a3f9a903d9b631a6dacf583c3f5667
|
refs/heads/main
| 2023-07-16T05:42:44.055000 | 2021-09-02T19:53:37 | 2021-09-02T19:53:37 | 373,553,756 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yx.watchmall.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserLoginInterceptor())
.addPathPatterns("/shipments","/shipments/*","/cart","/cart/**", "/order","/orders/*");
//registry.addInterceptor(new AuthInterceptor()).addPathPatterns();
}
}
|
UTF-8
|
Java
| 656 |
java
|
InterceptorConfig.java
|
Java
|
[] | null |
[] |
package com.yx.watchmall.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserLoginInterceptor())
.addPathPatterns("/shipments","/shipments/*","/cart","/cart/**", "/order","/orders/*");
//registry.addInterceptor(new AuthInterceptor()).addPathPatterns();
}
}
| 656 | 0.762195 | 0.762195 | 15 | 42.733334 | 33.323597 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false |
10
|
cdc5fe1f290e930e556404a90d573a818213b391
| 28,192,165,331,769 |
a0d145fffb8e1dcd97f4919b517beddb01371e34
|
/src_124/home/shared/license/HWIDLicenseTicket.java
|
a05102fe917f11bda5a89f94e9cc633f10bbbfae
|
[
"Apache-2.0"
] |
permissive
|
markymarkmk2/MailSecurerLib
|
https://github.com/markymarkmk2/MailSecurerLib
|
4498c4303f542ec8ce97700fdd2eb924cfcffd85
|
ab58afe76bb309b5ec9af74643cca8360a7dfacc
|
refs/heads/master
| 2021-01-09T06:32:45.644000 | 2017-02-05T16:12:37 | 2017-02-05T16:12:37 | 81,003,745 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package home.shared.license;
import home.shared.Utilities.LogListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Random;
import org.apache.commons.codec.binary.Base64;
/**
*
* @author mw
*/
public class HWIDLicenseTicket extends LicenseTicket
{
private String hwid;
private static String VM_LICFILE = "diwhsm.reg";
/**
* @return the hwid
*/
public String getHwid()
{
return hwid;
}
public void createTicket( String p, int _serial, int un, int mod, String _hw_id ) throws IOException
{
hwid = _hw_id;
product = p;
modules = mod;
units = un;
serial = _serial;
type = LT_DEMO;
setKey( calculate_key() );
}
static boolean test_vm_machine = false;
public static String generate_hwid() throws IOException
{
try
{
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements())
{
NetworkInterface ni = en.nextElement();
// WE SKIP EMPTY OR TOO SHORT HW-ADDRESS, MUST BE AT LEAST 6 BYTE (48BIT)
if (ni.getName().startsWith("lo") || ni.getHardwareAddress() == null || ni.getHardwareAddress().length < 6)
continue;
byte[] mac = ni.getHardwareAddress();
int sum = 0;
for (int i = 0; i < 6; i++)
{
byte b = mac[i];
sum += b;
}
// WE DO NOT ACCEPT EMPTY, THIS IS PROBABLY A VIRTUAL MACHINE
if (sum == 0)
continue;
if (test_vm_machine)
continue;
String str_mac = new String(Base64.encodeBase64(mac), "UTF-8");
return str_mac;
}
}
catch (Exception exc)
{
throw new IOException(exc.getLocalizedMessage());
}
if (test_vm_machine)
System.err.println("WARNING!!!! TEST VM HWID!!!!!");
// IF WE GET HERE, WE CANNOT LICENSE VIA MAC, WE USE TIMESTAMP OF LICENSE DIRECTORY
File lic_file = new File(VM_LICFILE);
if (!lic_file.exists())
{
create_virtual_hw_lic_file();
}
String str_mac = read_virtual_hw_lic_file();
return str_mac;
}
public static boolean is_virtual_license()
{
return new File(VM_LICFILE).exists();
}
public static String read_virtual_license()
{
String str_mac = read_virtual_hw_lic_file();
return str_mac;
}
static void create_virtual_hw_lic_file()
{
File lic_file = new File(VM_LICFILE);
Random rnd = new Random(System.currentTimeMillis());
byte[] mac = new byte[6];
rnd.nextBytes(mac);
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(lic_file);
fos.write(mac);
}
catch (IOException iOException)
{
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (IOException iOException)
{
}
}
}
}
static String read_virtual_hw_lic_file()
{
File lic_file = new File(VM_LICFILE);
if (lic_file.exists())
{
byte[] mac = new byte[6];
FileInputStream fr = null;
int rlen = 0;
try
{
fr = new FileInputStream(lic_file);
rlen = fr.read(mac);
if (rlen == 6)
{
String str_mac = new String(Base64.encodeBase64(mac), "UTF-8");
return str_mac;
}
}
catch (IOException iOException)
{
}
finally
{
if (fr != null)
{
try
{
fr.close();
}
catch (IOException iOException)
{
}
}
}
}
return null;
}
@Override
public boolean isValid()
{
if (!super.isValid())
{
return false;
}
try
{
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements())
{
byte[] mac = en.nextElement().getHardwareAddress();
if (test_vm_machine)
continue;
if (mac != null)
{
String str_mac = new String(Base64.encodeBase64(mac), "UTF-8");
if (str_mac.compareToIgnoreCase(hwid) == 0)
{
return true;
}
}
}
String vhwid = read_virtual_hw_lic_file();
if (vhwid != null && vhwid.compareTo(hwid) == 0)
{
return true;
}
lastErrMessage = "HWID_does_not_match";
}
catch (Exception exc)
{
lastErrMessage = "Cannot_check_HWID: " + exc.getLocalizedMessage();
if (ll != null)
ll.log_msg(LogListener.LVL_ERR, LogListener.TYP_LICENSE, lastErrMessage);
}
return false;
}
@Override
String get_license_hash_str()
{
return super.get_license_hash_str() + "," +hwid;
}
@Override
public String toString()
{
return super.toString() + " HWID:" + hwid;
}
}
|
UTF-8
|
Java
| 6,075 |
java
|
HWIDLicenseTicket.java
|
Java
|
[
{
"context": "he.commons.codec.binary.Base64;\n\n/**\n *\n * @author mw\n */\npublic class HWIDLicenseTicket extends License",
"end": 444,
"score": 0.8514627814292908,
"start": 442,
"tag": "USERNAME",
"value": "mw"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package home.shared.license;
import home.shared.Utilities.LogListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Random;
import org.apache.commons.codec.binary.Base64;
/**
*
* @author mw
*/
public class HWIDLicenseTicket extends LicenseTicket
{
private String hwid;
private static String VM_LICFILE = "diwhsm.reg";
/**
* @return the hwid
*/
public String getHwid()
{
return hwid;
}
public void createTicket( String p, int _serial, int un, int mod, String _hw_id ) throws IOException
{
hwid = _hw_id;
product = p;
modules = mod;
units = un;
serial = _serial;
type = LT_DEMO;
setKey( calculate_key() );
}
static boolean test_vm_machine = false;
public static String generate_hwid() throws IOException
{
try
{
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements())
{
NetworkInterface ni = en.nextElement();
// WE SKIP EMPTY OR TOO SHORT HW-ADDRESS, MUST BE AT LEAST 6 BYTE (48BIT)
if (ni.getName().startsWith("lo") || ni.getHardwareAddress() == null || ni.getHardwareAddress().length < 6)
continue;
byte[] mac = ni.getHardwareAddress();
int sum = 0;
for (int i = 0; i < 6; i++)
{
byte b = mac[i];
sum += b;
}
// WE DO NOT ACCEPT EMPTY, THIS IS PROBABLY A VIRTUAL MACHINE
if (sum == 0)
continue;
if (test_vm_machine)
continue;
String str_mac = new String(Base64.encodeBase64(mac), "UTF-8");
return str_mac;
}
}
catch (Exception exc)
{
throw new IOException(exc.getLocalizedMessage());
}
if (test_vm_machine)
System.err.println("WARNING!!!! TEST VM HWID!!!!!");
// IF WE GET HERE, WE CANNOT LICENSE VIA MAC, WE USE TIMESTAMP OF LICENSE DIRECTORY
File lic_file = new File(VM_LICFILE);
if (!lic_file.exists())
{
create_virtual_hw_lic_file();
}
String str_mac = read_virtual_hw_lic_file();
return str_mac;
}
public static boolean is_virtual_license()
{
return new File(VM_LICFILE).exists();
}
public static String read_virtual_license()
{
String str_mac = read_virtual_hw_lic_file();
return str_mac;
}
static void create_virtual_hw_lic_file()
{
File lic_file = new File(VM_LICFILE);
Random rnd = new Random(System.currentTimeMillis());
byte[] mac = new byte[6];
rnd.nextBytes(mac);
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(lic_file);
fos.write(mac);
}
catch (IOException iOException)
{
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (IOException iOException)
{
}
}
}
}
static String read_virtual_hw_lic_file()
{
File lic_file = new File(VM_LICFILE);
if (lic_file.exists())
{
byte[] mac = new byte[6];
FileInputStream fr = null;
int rlen = 0;
try
{
fr = new FileInputStream(lic_file);
rlen = fr.read(mac);
if (rlen == 6)
{
String str_mac = new String(Base64.encodeBase64(mac), "UTF-8");
return str_mac;
}
}
catch (IOException iOException)
{
}
finally
{
if (fr != null)
{
try
{
fr.close();
}
catch (IOException iOException)
{
}
}
}
}
return null;
}
@Override
public boolean isValid()
{
if (!super.isValid())
{
return false;
}
try
{
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements())
{
byte[] mac = en.nextElement().getHardwareAddress();
if (test_vm_machine)
continue;
if (mac != null)
{
String str_mac = new String(Base64.encodeBase64(mac), "UTF-8");
if (str_mac.compareToIgnoreCase(hwid) == 0)
{
return true;
}
}
}
String vhwid = read_virtual_hw_lic_file();
if (vhwid != null && vhwid.compareTo(hwid) == 0)
{
return true;
}
lastErrMessage = "HWID_does_not_match";
}
catch (Exception exc)
{
lastErrMessage = "Cannot_check_HWID: " + exc.getLocalizedMessage();
if (ll != null)
ll.log_msg(LogListener.LVL_ERR, LogListener.TYP_LICENSE, lastErrMessage);
}
return false;
}
@Override
String get_license_hash_str()
{
return super.get_license_hash_str() + "," +hwid;
}
@Override
public String toString()
{
return super.toString() + " HWID:" + hwid;
}
}
| 6,075 | 0.4693 | 0.464198 | 240 | 24.316668 | 22.568224 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.395833 | false | false |
10
|
a162ff81842a89753e2d6be7c472edf2d4c64901
| 31,963,146,620,232 |
fb574a5eadd653e9b237bb3b2ca54a71b0ff2077
|
/app/src/main/java/cl/niclabs/moviedetector/descriptors/GrayHistogramDescriptor.java
|
dbbb1834fec19f23acf6ff56f6b9dbe284bf03f6
|
[] |
no_license
|
fquintan/MovieDetector
|
https://github.com/fquintan/MovieDetector
|
6b7d8fe2f014f87be3784ad3b2a5ec99464a661a
|
baa24da300ccb195a7598014e04ff8a8922c958f
|
refs/heads/master
| 2020-06-01T15:45:30.123000 | 2015-12-19T22:18:26 | 2015-12-19T22:18:26 | 42,885,009 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cl.niclabs.moviedetector.descriptors;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
/**
* Created by felipe on 23-09-15.
*/
public class GrayHistogramDescriptor extends ImageDescriptor{
private int zones_x;
private int zones_y;
private int bins;
public GrayHistogramDescriptor(double[] descriptor, long timestamp, int frameNumber) {
super(descriptor, timestamp, frameNumber);
}
public GrayHistogramDescriptor(double[] descriptor, long timestamp, int frameNumber, int zones_x, int zones_y, int bins) {
super(descriptor, timestamp, frameNumber);
this.zones_x = zones_x;
this.zones_y = zones_y;
this.bins = bins;
}
@Override
public String getType() {
return "GrayHistogram";
}
@Override
public String getSerializedOptions() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("zones_x", zones_x);
jsonObject.addProperty("zones_y", zones_y);
jsonObject.addProperty("bins", bins);
jsonObject.addProperty("quant", "4F");
return new Gson().toJson(jsonObject);
}
}
|
UTF-8
|
Java
| 1,211 |
java
|
GrayHistogramDescriptor.java
|
Java
|
[
{
"context": "fer;\nimport java.nio.IntBuffer;\n\n/**\n * Created by felipe on 23-09-15.\n */\npublic class GrayHistogramDescri",
"end": 192,
"score": 0.9559025764465332,
"start": 186,
"tag": "USERNAME",
"value": "felipe"
}
] | null |
[] |
package cl.niclabs.moviedetector.descriptors;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
/**
* Created by felipe on 23-09-15.
*/
public class GrayHistogramDescriptor extends ImageDescriptor{
private int zones_x;
private int zones_y;
private int bins;
public GrayHistogramDescriptor(double[] descriptor, long timestamp, int frameNumber) {
super(descriptor, timestamp, frameNumber);
}
public GrayHistogramDescriptor(double[] descriptor, long timestamp, int frameNumber, int zones_x, int zones_y, int bins) {
super(descriptor, timestamp, frameNumber);
this.zones_x = zones_x;
this.zones_y = zones_y;
this.bins = bins;
}
@Override
public String getType() {
return "GrayHistogram";
}
@Override
public String getSerializedOptions() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("zones_x", zones_x);
jsonObject.addProperty("zones_y", zones_y);
jsonObject.addProperty("bins", bins);
jsonObject.addProperty("quant", "4F");
return new Gson().toJson(jsonObject);
}
}
| 1,211 | 0.673823 | 0.668043 | 43 | 27.16279 | 26.131092 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.813953 | false | false |
10
|
b752987e74d602a30f1768da5dbcf62e9eee17cb
| 27,204,322,914,383 |
a7b9c49423aa0326dd628264a7793d13cc97d067
|
/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/container/ExecutorLoader.java
|
473341feb6488b6c65160329f6efb96852322467
|
[
"Apache-2.0"
] |
permissive
|
elloray/jstorm
|
https://github.com/elloray/jstorm
|
6de10f65cbf29650ff2ddb60d6526ee0573be28b
|
a201d98653d3742e966c0b558e20661129de2344
|
refs/heads/master
| 2021-01-13T03:35:04.053000 | 2017-03-04T14:15:03 | 2017-03-04T14:15:03 | 77,508,043 | 1 | 0 | null | true | 2016-12-28T06:14:34 | 2016-12-28T06:14:34 | 2016-12-27T10:51:27 | 2016-12-27T16:34:01 | 102,874 | 0 | 0 | 0 | null | null | null |
package com.alibaba.jstorm.yarn.container;
import com.alibaba.jstorm.yarn.constants.JOYConstants;
/**
* Created by fengjian on 16/4/21.
* concat load command string
*/
public class ExecutorLoader {
public static String loadCommand(String instanceName, String shellCommand, String startType, String containerId, String localDir, String deployPath,
String hadoopHome, String javaHome, String pythonHome, String dstPath, String portList, String shellArgs, String classpath,
String ExecShellStringPath, String applicationId, String logviewPort, String nimbusThriftPort) {
StringBuffer sbCommand = new StringBuffer();
sbCommand.append(javaHome).append(JOYConstants.JAVA_CP).append(JOYConstants.BLANK);
sbCommand.append(classpath).append(JOYConstants.EXECUTOR_CLASS).append(JOYConstants.BLANK);
sbCommand.append(instanceName).append(JOYConstants.BLANK).append(shellCommand).append(JOYConstants.BLANK);
sbCommand.append(startType).append(JOYConstants.BLANK).append(containerId).append(JOYConstants.BLANK).append(localDir).append(JOYConstants.BLANK);
sbCommand.append(deployPath).append(JOYConstants.BLANK).append(hadoopHome).append(JOYConstants.BLANK).append(javaHome).append(JOYConstants.BLANK);
sbCommand.append(pythonHome).append(JOYConstants.BLANK).append(dstPath).append(JOYConstants.BLANK).append(portList).append(JOYConstants.BLANK);
sbCommand.append(ExecShellStringPath).append(JOYConstants.BLANK).append(applicationId).append(JOYConstants.BLANK).append(logviewPort).append(JOYConstants.BLANK);
sbCommand.append(nimbusThriftPort).append(JOYConstants.BLANK).append(shellArgs);
return sbCommand.toString();
}
}
|
UTF-8
|
Java
| 1,777 |
java
|
ExecutorLoader.java
|
Java
|
[
{
"context": "rm.yarn.constants.JOYConstants;\n\n/**\n * Created by fengjian on 16/4/21.\n * concat load command string\n */\npub",
"end": 126,
"score": 0.9981460571289062,
"start": 118,
"tag": "USERNAME",
"value": "fengjian"
}
] | null |
[] |
package com.alibaba.jstorm.yarn.container;
import com.alibaba.jstorm.yarn.constants.JOYConstants;
/**
* Created by fengjian on 16/4/21.
* concat load command string
*/
public class ExecutorLoader {
public static String loadCommand(String instanceName, String shellCommand, String startType, String containerId, String localDir, String deployPath,
String hadoopHome, String javaHome, String pythonHome, String dstPath, String portList, String shellArgs, String classpath,
String ExecShellStringPath, String applicationId, String logviewPort, String nimbusThriftPort) {
StringBuffer sbCommand = new StringBuffer();
sbCommand.append(javaHome).append(JOYConstants.JAVA_CP).append(JOYConstants.BLANK);
sbCommand.append(classpath).append(JOYConstants.EXECUTOR_CLASS).append(JOYConstants.BLANK);
sbCommand.append(instanceName).append(JOYConstants.BLANK).append(shellCommand).append(JOYConstants.BLANK);
sbCommand.append(startType).append(JOYConstants.BLANK).append(containerId).append(JOYConstants.BLANK).append(localDir).append(JOYConstants.BLANK);
sbCommand.append(deployPath).append(JOYConstants.BLANK).append(hadoopHome).append(JOYConstants.BLANK).append(javaHome).append(JOYConstants.BLANK);
sbCommand.append(pythonHome).append(JOYConstants.BLANK).append(dstPath).append(JOYConstants.BLANK).append(portList).append(JOYConstants.BLANK);
sbCommand.append(ExecShellStringPath).append(JOYConstants.BLANK).append(applicationId).append(JOYConstants.BLANK).append(logviewPort).append(JOYConstants.BLANK);
sbCommand.append(nimbusThriftPort).append(JOYConstants.BLANK).append(shellArgs);
return sbCommand.toString();
}
}
| 1,777 | 0.755768 | 0.752954 | 24 | 73.041664 | 60.390728 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false |
15
|
81b47d6b77c22eeccfc70f561d77e1dd8e971c96
| 27,204,322,913,394 |
ab298fce6efb0ab28984f5417ffa6e3906022950
|
/src/main/java/com/anneagram/vo/BoardVO.java
|
c06bc441d2527765c41226024494f3319162ed87
|
[] |
no_license
|
phantomysy/Anneagram
|
https://github.com/phantomysy/Anneagram
|
b85dad3e755bc0a9496e3f09f81fb6ce67bde63b
|
4aaf0e8873bf1d8145062dd8fb2c206bf51183f1
|
refs/heads/master
| 2022-06-22T22:40:53.560000 | 2020-05-12T00:36:52 | 2020-05-12T00:36:52 | 262,943,954 | 0 | 0 | null | true | 2020-05-11T05:07:37 | 2020-05-11T05:07:36 | 2020-05-10T05:36:13 | 2020-05-10T05:36:11 | 4,421 | 0 | 0 | 0 | null | false | false |
package com.anneagram.vo;
import java.util.Date;
public class BoardVO {
/*
* bno number(30) primary key,
* user_id varchar2(50),
* title varchar2(200)
* content varchar2(4000),
* cnt number(30) default 0,
*regdate date,
moddate date
*/
private int bno;
private String user_id;
private String title;
private String content;
private int cnt;
private Date regdate;
private Date moddate;
private int start;
private int end;
public BoardVO() {
// TODO Auto-generated constructor stub
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getBno() {
return bno;
}
public void setBno(int bno) {
this.bno = bno;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public Date getModdate() {
return moddate;
}
public void setModdate(Date moddate) {
this.moddate = moddate;
}
}
|
UTF-8
|
Java
| 1,522 |
java
|
BoardVO.java
|
Java
|
[] | null |
[] |
package com.anneagram.vo;
import java.util.Date;
public class BoardVO {
/*
* bno number(30) primary key,
* user_id varchar2(50),
* title varchar2(200)
* content varchar2(4000),
* cnt number(30) default 0,
*regdate date,
moddate date
*/
private int bno;
private String user_id;
private String title;
private String content;
private int cnt;
private Date regdate;
private Date moddate;
private int start;
private int end;
public BoardVO() {
// TODO Auto-generated constructor stub
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getBno() {
return bno;
}
public void setBno(int bno) {
this.bno = bno;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public Date getModdate() {
return moddate;
}
public void setModdate(Date moddate) {
this.moddate = moddate;
}
}
| 1,522 | 0.658344 | 0.647175 | 104 | 13.634615 | 12.645353 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.269231 | false | false |
15
|
ac5fcceb1db28087fdfb2fd6987096e13d1dc19b
| 36,481,452,254,567 |
5fb993fe10049b12e4c7970e2cf1f870eb64e722
|
/src/main/java/devy/cave/server/search/service/daum/DaumVideoService.java
|
f613b0fa81d1cafe5a0cae0cf40822e853729aaa
|
[] |
no_license
|
DevYs/cave-server
|
https://github.com/DevYs/cave-server
|
de96e7f3066bb941569bdc1cc944c2a12567854a
|
bed3a206ff785711215ff0e450b71e0aab230d6d
|
refs/heads/master
| 2020-03-20T13:36:07.760000 | 2019-12-29T07:34:52 | 2019-12-29T07:34:52 | 137,460,619 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package devy.cave.server.search.service.daum;
import devy.cave.server.search.model.ClipVideo;
import devy.cave.server.search.parser.DocumentParser;
import devy.cave.server.search.parser.daum.DaumVideoPageParser;
import devy.cave.server.search.parser.daum.DaumVideoParser;
import devy.cave.server.search.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.logging.Logger;
@Service
public class DaumVideoService implements IService {
private final Logger logger = Logger.getLogger(DaumVideoService.class.getSimpleName());
private final String TAG_VIDEO_KEY = "{videoKey}";
private final String TAG_MOVIE_ID = "{movieId}";
private final String URL_VIDEO_PAGE_URL = "https://movie.daum.net/moviedb/video?id=" + TAG_MOVIE_ID;
private final String URL_VIDEO_URL = "https://kakaotv.daum.net/embed/player/cliplink/" + TAG_VIDEO_KEY + "?service=daum_movie&autoplay=true&profile=HIGH&playsinline=true";
@Autowired
private DocumentParser documentParser;
public ClipVideo requestVideoPage(String contentsId) {
String url = URL_VIDEO_PAGE_URL.replace(TAG_MOVIE_ID, contentsId);
logger.info("URL_VIDEO_PAGE_URL " + url);
return (ClipVideo) documentParser.parseHtml(url, new DaumVideoPageParser());
}
public ClipVideo requestVideo(String contentsId) {
ClipVideo clipVideo = requestVideoPage(contentsId);
String url = URL_VIDEO_URL.replace(TAG_VIDEO_KEY, clipVideo.getVideoKey() + "@my");
logger.info("URL_VIDEO_URL " + url);
String clipVideoUrl = (String) documentParser.parseHtml(url, new DaumVideoParser());
clipVideo.setClipVideoUrl(clipVideoUrl);
return clipVideo;
}
@Override
public String url() {
return "https://movie.daum.net/moviedb/video?id={movieId}";
}
}
|
UTF-8
|
Java
| 1,894 |
java
|
DaumVideoService.java
|
Java
|
[
{
"context": "eplace(TAG_VIDEO_KEY, clipVideo.getVideoKey() + \"@my\");\n logger.info(\"URL_VIDEO_URL \" + url);\n\n",
"end": 1552,
"score": 0.6965307593345642,
"start": 1550,
"tag": "KEY",
"value": "my"
}
] | null |
[] |
package devy.cave.server.search.service.daum;
import devy.cave.server.search.model.ClipVideo;
import devy.cave.server.search.parser.DocumentParser;
import devy.cave.server.search.parser.daum.DaumVideoPageParser;
import devy.cave.server.search.parser.daum.DaumVideoParser;
import devy.cave.server.search.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.logging.Logger;
@Service
public class DaumVideoService implements IService {
private final Logger logger = Logger.getLogger(DaumVideoService.class.getSimpleName());
private final String TAG_VIDEO_KEY = "{videoKey}";
private final String TAG_MOVIE_ID = "{movieId}";
private final String URL_VIDEO_PAGE_URL = "https://movie.daum.net/moviedb/video?id=" + TAG_MOVIE_ID;
private final String URL_VIDEO_URL = "https://kakaotv.daum.net/embed/player/cliplink/" + TAG_VIDEO_KEY + "?service=daum_movie&autoplay=true&profile=HIGH&playsinline=true";
@Autowired
private DocumentParser documentParser;
public ClipVideo requestVideoPage(String contentsId) {
String url = URL_VIDEO_PAGE_URL.replace(TAG_MOVIE_ID, contentsId);
logger.info("URL_VIDEO_PAGE_URL " + url);
return (ClipVideo) documentParser.parseHtml(url, new DaumVideoPageParser());
}
public ClipVideo requestVideo(String contentsId) {
ClipVideo clipVideo = requestVideoPage(contentsId);
String url = URL_VIDEO_URL.replace(TAG_VIDEO_KEY, clipVideo.getVideoKey() + "@my");
logger.info("URL_VIDEO_URL " + url);
String clipVideoUrl = (String) documentParser.parseHtml(url, new DaumVideoParser());
clipVideo.setClipVideoUrl(clipVideoUrl);
return clipVideo;
}
@Override
public String url() {
return "https://movie.daum.net/moviedb/video?id={movieId}";
}
}
| 1,894 | 0.732313 | 0.732313 | 49 | 37.653061 | 36.684284 | 175 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.591837 | false | false |
15
|
1697df4978319bebbece65f757fdb2ee73806fff
| 31,361,851,257,115 |
b00d5a6226b84ce0fecb44a05ebd0641f79b1a8b
|
/src/main/java/serviceDao/ServiceDaoImpl.java
|
fa5e88b9d3bdb5dd2f7af89af7e02399ffb3c366
|
[] |
no_license
|
olgahuzarewicz/CustomSpring
|
https://github.com/olgahuzarewicz/CustomSpring
|
e9dc4ecd3fbd7086b84f5050d8956a60eadc69fa
|
2373abe921525738bfec6fd2970909e6ba4ffd19
|
refs/heads/master
| 2023-08-10T07:12:58.143000 | 2023-07-26T10:53:47 | 2023-07-26T10:53:47 | 194,876,443 | 0 | 0 | null | false | 2023-07-26T10:55:29 | 2019-07-02T14:12:25 | 2023-07-26T10:53:51 | 2023-07-26T10:55:29 | 35 | 0 | 0 | 4 |
Java
| false | false |
package serviceDao;
import annotation.Autowired;
import annotation.Qualifier;
import companyDao.CompanyDao;
public class ServiceDaoImpl implements ServiceDao {
@Autowired
@Qualifier(name = "companyDAO")
private CompanyDao companyDAO;
public ServiceDaoImpl() {
System.out.println("created ServiceDaoImpl");
}
}
|
UTF-8
|
Java
| 342 |
java
|
ServiceDaoImpl.java
|
Java
|
[] | null |
[] |
package serviceDao;
import annotation.Autowired;
import annotation.Qualifier;
import companyDao.CompanyDao;
public class ServiceDaoImpl implements ServiceDao {
@Autowired
@Qualifier(name = "companyDAO")
private CompanyDao companyDAO;
public ServiceDaoImpl() {
System.out.println("created ServiceDaoImpl");
}
}
| 342 | 0.74269 | 0.74269 | 16 | 20.375 | 17.645378 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
15
|
cfe1155c002a84928b9c6a3cece3908747ba8c98
| 35,923,106,507,703 |
9f857c5e47ef456a3c67c57d1d6c3bd370109d3e
|
/MS Teams/src/com/actiance/APIs/MessageByReciveTime.java
|
78a5651d7caf22fa4c8f3da19eea87bdcde70ab0
|
[] |
no_license
|
keshriviks/SAMPLE
|
https://github.com/keshriviks/SAMPLE
|
1b4eea8b6026a556f4a80f015b65144e47d9bde8
|
7902c1a80fefebb73672497708916fbff2f0420c
|
refs/heads/master
| 2021-05-12T18:56:39.749000 | 2018-01-11T09:40:50 | 2018-01-11T09:40:50 | 117,076,473 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.actiance.APIs;
import java.util.Calendar;
import java.util.Date;
import com.independentsoft.exchange.IsGreaterThanOrEqualTo;
import com.independentsoft.exchange.Message;
import com.independentsoft.exchange.MessagePropertyPath;
import com.independentsoft.exchange.FindFolderResponse;
import com.independentsoft.exchange.FindItemResponse;
import com.independentsoft.exchange.Service;
import com.independentsoft.exchange.ServiceException;
import com.independentsoft.exchange.StandardFolder;
//////Find messages by receive time//////////
//MessageByReciveTime
public class MessageByReciveTime {
public static void main(String[] args) throws InterruptedException
{
try
{
Service service = new Service("https://outlook.office365.com/EWS/Exchange.asmx", "achandra@actiance.co.in", "FaceTime@123");
Calendar localCalendar = Calendar.getInstance();
localCalendar.add(Calendar.MINUTE, -25);
Date time = localCalendar.getTime();
String msgToValidate = "123zxc";
IsGreaterThanOrEqualTo restriction = new IsGreaterThanOrEqualTo(MessagePropertyPath.RECEIVED_TIME, time);
FindFolderResponse findFolderResponse1 = service.findFolder(StandardFolder.CONVERSATION_HISTORY);
FindItemResponse response = service.findItem(findFolderResponse1.getFolders().get(0).getFolderId(), MessagePropertyPath.getAllPropertyPaths(), restriction);
System.out.println(response.getItems().size());
boolean found = false;
long messageSentTime = System.currentTimeMillis();
long searchEndTime = 0;
System.out.println("Search started : "+messageSentTime);
int k =0;
while(!found){
System.out.println(k++);
for (int i = 0; i < response.getItems().size(); i++)
{
if (response.getItems().get(i) instanceof Message)
{
Message message = (Message) response.getItems().get(i);
// System.out.println("Subject = " + message.getSubject());
//System.out.println("ReceivedTime = " + message.getReceivedTime());
if (message.getFrom() != null)
{
System.out.println("From = " + message.getFrom().getName());
}
String fromMB = message.getBodyPlainText();
System.out.println("Body Preview = " +fromMB);
if(fromMB.equals(msgToValidate))
{
searchEndTime = System.currentTimeMillis();
found = true;
}
System.out.println("----------------------------------------------------------------");
}
}
Thread.sleep(5000);
}
System.out.println("Match Found at started : "+searchEndTime);
System.out.println("Time taken :" + (searchEndTime - messageSentTime));
}
catch (ServiceException e)
{
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 3,210 |
java
|
MessageByReciveTime.java
|
Java
|
[
{
"context": "ttps://outlook.office365.com/EWS/Exchange.asmx\", \"achandra@actiance.co.in\", \"FaceTime@123\");\n\n Calendar localCal",
"end": 829,
"score": 0.9999319911003113,
"start": 806,
"tag": "EMAIL",
"value": "achandra@actiance.co.in"
}
] | null |
[] |
package com.actiance.APIs;
import java.util.Calendar;
import java.util.Date;
import com.independentsoft.exchange.IsGreaterThanOrEqualTo;
import com.independentsoft.exchange.Message;
import com.independentsoft.exchange.MessagePropertyPath;
import com.independentsoft.exchange.FindFolderResponse;
import com.independentsoft.exchange.FindItemResponse;
import com.independentsoft.exchange.Service;
import com.independentsoft.exchange.ServiceException;
import com.independentsoft.exchange.StandardFolder;
//////Find messages by receive time//////////
//MessageByReciveTime
public class MessageByReciveTime {
public static void main(String[] args) throws InterruptedException
{
try
{
Service service = new Service("https://outlook.office365.com/EWS/Exchange.asmx", "<EMAIL>", "FaceTime@123");
Calendar localCalendar = Calendar.getInstance();
localCalendar.add(Calendar.MINUTE, -25);
Date time = localCalendar.getTime();
String msgToValidate = "123zxc";
IsGreaterThanOrEqualTo restriction = new IsGreaterThanOrEqualTo(MessagePropertyPath.RECEIVED_TIME, time);
FindFolderResponse findFolderResponse1 = service.findFolder(StandardFolder.CONVERSATION_HISTORY);
FindItemResponse response = service.findItem(findFolderResponse1.getFolders().get(0).getFolderId(), MessagePropertyPath.getAllPropertyPaths(), restriction);
System.out.println(response.getItems().size());
boolean found = false;
long messageSentTime = System.currentTimeMillis();
long searchEndTime = 0;
System.out.println("Search started : "+messageSentTime);
int k =0;
while(!found){
System.out.println(k++);
for (int i = 0; i < response.getItems().size(); i++)
{
if (response.getItems().get(i) instanceof Message)
{
Message message = (Message) response.getItems().get(i);
// System.out.println("Subject = " + message.getSubject());
//System.out.println("ReceivedTime = " + message.getReceivedTime());
if (message.getFrom() != null)
{
System.out.println("From = " + message.getFrom().getName());
}
String fromMB = message.getBodyPlainText();
System.out.println("Body Preview = " +fromMB);
if(fromMB.equals(msgToValidate))
{
searchEndTime = System.currentTimeMillis();
found = true;
}
System.out.println("----------------------------------------------------------------");
}
}
Thread.sleep(5000);
}
System.out.println("Match Found at started : "+searchEndTime);
System.out.println("Time taken :" + (searchEndTime - messageSentTime));
}
catch (ServiceException e)
{
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}
}
| 3,194 | 0.597508 | 0.590966 | 90 | 34.477779 | 33.70863 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633333 | false | false |
15
|
805d570e5acd71cc6844872e731ad1ac5e914eee
| 7,198,365,228,604 |
a9642fcaa360646f3ed861f3c44e450cb686796c
|
/VEJEZ/analisis/app/co/com/proteccion/advance/vejez/analisis/aplicacion/comandos/registrarrespuestaexcepciongpm/jsonobjects/Causal.java
|
9b2b0aad51053853124bdba1ffd82dc4606bb3b3
|
[] |
no_license
|
ronn/adv-reference
|
https://github.com/ronn/adv-reference
|
510aba8e0ed2f644e7e0d3482336554aeae2c1b5
|
c12a6f8884cfdd244cec38bb7ada0f4fcc178d66
|
refs/heads/master
| 2020-07-19T06:06:36.470000 | 2019-09-04T18:30:20 | 2019-09-04T18:30:20 | 206,386,319 | 0 | 0 | null | false | 2020-09-10T12:23:28 | 2019-09-04T18:28:07 | 2019-09-04T18:33:02 | 2020-09-10T12:23:27 | 97,429 | 0 | 0 | 13 |
Java
| false | false |
package co.com.proteccion.advance.vejez.analisis.aplicacion.comandos.registrarrespuestaexcepciongpm.jsonobjects;
public class Causal {
private final String idCausal;
private final String observaciones;
public Causal(String idCausal, String observaciones) {
this.idCausal = idCausal;
this.observaciones = observaciones;
}
public String getIdCausal() {
return idCausal;
}
public String getObservaciones() {
return observaciones;
}
@Override
public String toString() {
return "Causal{" +
"idCausal='" + idCausal + '\'' +
", observaciones='" + observaciones + '\'' +
'}';
}
}
|
UTF-8
|
Java
| 697 |
java
|
Causal.java
|
Java
|
[] | null |
[] |
package co.com.proteccion.advance.vejez.analisis.aplicacion.comandos.registrarrespuestaexcepciongpm.jsonobjects;
public class Causal {
private final String idCausal;
private final String observaciones;
public Causal(String idCausal, String observaciones) {
this.idCausal = idCausal;
this.observaciones = observaciones;
}
public String getIdCausal() {
return idCausal;
}
public String getObservaciones() {
return observaciones;
}
@Override
public String toString() {
return "Causal{" +
"idCausal='" + idCausal + '\'' +
", observaciones='" + observaciones + '\'' +
'}';
}
}
| 697 | 0.625538 | 0.625538 | 27 | 24.814816 | 24.692234 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false |
15
|
bd50a3b7c0ba1266db54dc4752e5c6f78971e746
| 14,044,543,098,903 |
961176493c91c697d661b474a8ec39a075313f37
|
/src/test/java/edu/utn/utnPhones/services/PhoneLineServiceTest.java
|
700e627b8ce2c596f13d0e6a258811202c32fd91
|
[] |
no_license
|
FedeAlesandro/UTNPhones
|
https://github.com/FedeAlesandro/UTNPhones
|
d3727db9a2d16663e8574329ef3bb1a26d72e4d2
|
21606e23b2d4f1fd098d44270d0b4356159cac0a
|
refs/heads/master
| 2022-12-29T21:00:21.244000 | 2020-06-26T02:05:15 | 2020-06-26T02:05:15 | 262,472,894 | 1 | 1 | null | false | 2020-10-14T00:27:10 | 2020-05-09T02:35:05 | 2020-07-01T23:24:21 | 2020-10-14T00:27:08 | 477 | 1 | 0 | 1 |
Java
| false | false |
package edu.utn.utnPhones.services;
import edu.utn.utnPhones.exceptions.AlreadyExistsException;
import edu.utn.utnPhones.exceptions.NotFoundException;
import edu.utn.utnPhones.models.City;
import edu.utn.utnPhones.models.PhoneLine;
import edu.utn.utnPhones.models.User;
import edu.utn.utnPhones.models.dtos.requests.PhoneLineDtoAdd;
import edu.utn.utnPhones.repositories.CityRepository;
import edu.utn.utnPhones.repositories.PhoneLineRepository;
import edu.utn.utnPhones.repositories.UserRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.Optional;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class PhoneLineServiceTest implements FactoryService{
private PhoneLineService phoneLineService;
@Mock
private PhoneLineRepository phoneLineRepository;
@Mock
private UserRepository userRepository;
@Mock
private CityRepository cityRepository;
@Before
public void setUp(){
initMocks(this);
phoneLineService = new PhoneLineService(phoneLineRepository, userRepository, cityRepository);
}
@Test
public void getAllTest(){
when(phoneLineRepository.getAll()).thenReturn(new ArrayList<PhoneLine>());
Assert.assertNotNull(phoneLineService.getAll());
}
@Test(expected = NotFoundException.class)
public void getByUserNameNotFoundException(){
when(userRepository.findByUserNameAndRemoved("Euvenias", false))
.thenReturn(Optional.empty());
phoneLineService.getByUserName("Euvenias");
}
@Test
public void getByUserNameOk(){
when(userRepository.findByUserNameAndRemoved("Euvenias", false)).thenReturn(Optional.of(new User()));
when(phoneLineRepository.getAll()).thenReturn(new ArrayList<PhoneLine>());
Assert.assertNotNull(phoneLineService.getByUserName("Euvenias"));
}
@Test(expected = NotFoundException.class)
public void addUserNotFoundException(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.empty());
phoneLineService.add(phoneLine);
}
@Test(expected = NotFoundException.class)
public void addCityNotFoundException(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.of(new User()));
when(cityRepository.findAreaCodeByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(Optional.empty());
phoneLineService.add(phoneLine);
}
@Test(expected = AlreadyExistsException.class)
public void addAlreadyExistsException(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.of(new User()));
when(cityRepository.findAreaCodeByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(createPhoneLine());
phoneLineService.add(phoneLine);
}
@Test
public void addRemovedPhoneLine(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
PhoneLine oldPhoneLine = createPhoneLineRemoved();
PhoneLine newPhoneLine = createPhoneLine();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.of(new User()));
when(cityRepository.findAreaCodeByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(oldPhoneLine);
when(phoneLineRepository.save(oldPhoneLine)).thenReturn(newPhoneLine);
Assert.assertEquals(newPhoneLine, phoneLineService.add(phoneLine));
}
@Test
public void addOk(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
PhoneLine newPhoneLine = createPhoneLine();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.of(new User()));
when(cityRepository.findAreaCodeByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(null);
when(phoneLineRepository.save(newPhoneLine)).thenReturn(newPhoneLine);
Assert.assertEquals(newPhoneLine, phoneLineService.add(phoneLine));
}
@Test(expected = NotFoundException.class)
public void updatePhoneLineNotFoundException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.empty());
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test(expected = NotFoundException.class)
public void updateAreaCodeNotFoundException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
when(cityRepository.findAreaCodeByPhoneNumber("2235860225")).thenReturn(Optional.empty());
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test(expected = AlreadyExistsException.class)
public void updateAlreadyExistsException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
when(cityRepository.findAreaCodeByPhoneNumber("2235860225")).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber("2235860225")).thenReturn(new PhoneLine());
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test(expected = NotFoundException.class)
public void updateUserNotFoundException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
when(cityRepository.findAreaCodeByPhoneNumber("2235860225")).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber("2235860225")).thenReturn(null);
when(userRepository.findByIdAndRemoved(1, false)).thenReturn(Optional.empty());
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test
public void updateOk(){
PhoneLine phoneLine = createPhoneLine();
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
when(cityRepository.findAreaCodeByPhoneNumber("2235860225")).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber("2235860225")).thenReturn(null);
when(userRepository.findByIdAndRemoved(1, false)).thenReturn(Optional.of(new User()));
when(phoneLineRepository.save(phoneLine)).thenReturn(phoneLine);
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test(expected = NotFoundException.class)
public void removeNotFoundException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.empty());
phoneLineService.remove(1);
}
@Test
public void removeOk(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
doNothing().when(phoneLineRepository).remove(1);
phoneLineService.remove(1);
}
}
|
UTF-8
|
Java
| 7,415 |
java
|
PhoneLineServiceTest.java
|
Java
|
[
{
"context": " when(userRepository.findByUserNameAndRemoved(\"Euvenias\", false))\n .thenReturn(Optional.em",
"end": 1596,
"score": 0.9990022778511047,
"start": 1588,
"tag": "USERNAME",
"value": "Euvenias"
},
{
"context": "empty());\n phoneLineService.getByUserName(\"Euvenias\");\n }\n\n @Test\n public void getByUserName",
"end": 1702,
"score": 0.9992985129356384,
"start": 1694,
"tag": "USERNAME",
"value": "Euvenias"
},
{
"context": " when(userRepository.findByUserNameAndRemoved(\"Euvenias\", false)).thenReturn(Optional.of(new User()));\n ",
"end": 1820,
"score": 0.9984797835350037,
"start": 1812,
"tag": "USERNAME",
"value": "Euvenias"
},
{
"context": "ert.assertNotNull(phoneLineService.getByUserName(\"Euvenias\"));\n }\n\n @Test(expected = NotFoundException",
"end": 2021,
"score": 0.9989631772041321,
"start": 2013,
"tag": "USERNAME",
"value": "Euvenias"
}
] | null |
[] |
package edu.utn.utnPhones.services;
import edu.utn.utnPhones.exceptions.AlreadyExistsException;
import edu.utn.utnPhones.exceptions.NotFoundException;
import edu.utn.utnPhones.models.City;
import edu.utn.utnPhones.models.PhoneLine;
import edu.utn.utnPhones.models.User;
import edu.utn.utnPhones.models.dtos.requests.PhoneLineDtoAdd;
import edu.utn.utnPhones.repositories.CityRepository;
import edu.utn.utnPhones.repositories.PhoneLineRepository;
import edu.utn.utnPhones.repositories.UserRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.Optional;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class PhoneLineServiceTest implements FactoryService{
private PhoneLineService phoneLineService;
@Mock
private PhoneLineRepository phoneLineRepository;
@Mock
private UserRepository userRepository;
@Mock
private CityRepository cityRepository;
@Before
public void setUp(){
initMocks(this);
phoneLineService = new PhoneLineService(phoneLineRepository, userRepository, cityRepository);
}
@Test
public void getAllTest(){
when(phoneLineRepository.getAll()).thenReturn(new ArrayList<PhoneLine>());
Assert.assertNotNull(phoneLineService.getAll());
}
@Test(expected = NotFoundException.class)
public void getByUserNameNotFoundException(){
when(userRepository.findByUserNameAndRemoved("Euvenias", false))
.thenReturn(Optional.empty());
phoneLineService.getByUserName("Euvenias");
}
@Test
public void getByUserNameOk(){
when(userRepository.findByUserNameAndRemoved("Euvenias", false)).thenReturn(Optional.of(new User()));
when(phoneLineRepository.getAll()).thenReturn(new ArrayList<PhoneLine>());
Assert.assertNotNull(phoneLineService.getByUserName("Euvenias"));
}
@Test(expected = NotFoundException.class)
public void addUserNotFoundException(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.empty());
phoneLineService.add(phoneLine);
}
@Test(expected = NotFoundException.class)
public void addCityNotFoundException(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.of(new User()));
when(cityRepository.findAreaCodeByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(Optional.empty());
phoneLineService.add(phoneLine);
}
@Test(expected = AlreadyExistsException.class)
public void addAlreadyExistsException(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.of(new User()));
when(cityRepository.findAreaCodeByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(createPhoneLine());
phoneLineService.add(phoneLine);
}
@Test
public void addRemovedPhoneLine(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
PhoneLine oldPhoneLine = createPhoneLineRemoved();
PhoneLine newPhoneLine = createPhoneLine();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.of(new User()));
when(cityRepository.findAreaCodeByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(oldPhoneLine);
when(phoneLineRepository.save(oldPhoneLine)).thenReturn(newPhoneLine);
Assert.assertEquals(newPhoneLine, phoneLineService.add(phoneLine));
}
@Test
public void addOk(){
PhoneLineDtoAdd phoneLine = createPhoneLineDtoAdd();
PhoneLine newPhoneLine = createPhoneLine();
when(userRepository.findByIdAndRemoved(phoneLine.getUser().getId(),false)).thenReturn(Optional.of(new User()));
when(cityRepository.findAreaCodeByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber(phoneLine.getPhoneNumber())).thenReturn(null);
when(phoneLineRepository.save(newPhoneLine)).thenReturn(newPhoneLine);
Assert.assertEquals(newPhoneLine, phoneLineService.add(phoneLine));
}
@Test(expected = NotFoundException.class)
public void updatePhoneLineNotFoundException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.empty());
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test(expected = NotFoundException.class)
public void updateAreaCodeNotFoundException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
when(cityRepository.findAreaCodeByPhoneNumber("2235860225")).thenReturn(Optional.empty());
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test(expected = AlreadyExistsException.class)
public void updateAlreadyExistsException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
when(cityRepository.findAreaCodeByPhoneNumber("2235860225")).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber("2235860225")).thenReturn(new PhoneLine());
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test(expected = NotFoundException.class)
public void updateUserNotFoundException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
when(cityRepository.findAreaCodeByPhoneNumber("2235860225")).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber("2235860225")).thenReturn(null);
when(userRepository.findByIdAndRemoved(1, false)).thenReturn(Optional.empty());
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test
public void updateOk(){
PhoneLine phoneLine = createPhoneLine();
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
when(cityRepository.findAreaCodeByPhoneNumber("2235860225")).thenReturn(Optional.of(new City()));
when(phoneLineRepository.findByPhoneNumber("2235860225")).thenReturn(null);
when(userRepository.findByIdAndRemoved(1, false)).thenReturn(Optional.of(new User()));
when(phoneLineRepository.save(phoneLine)).thenReturn(phoneLine);
phoneLineService.update(1, createPhoneLineDtoUpdate());
}
@Test(expected = NotFoundException.class)
public void removeNotFoundException(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.empty());
phoneLineService.remove(1);
}
@Test
public void removeOk(){
when(phoneLineRepository.findByIdAndState(1)).thenReturn(Optional.of(new PhoneLine()));
doNothing().when(phoneLineRepository).remove(1);
phoneLineService.remove(1);
}
}
| 7,415 | 0.739987 | 0.728254 | 180 | 40.188889 | 36.656483 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.572222 | false | false |
15
|
78adb86fe4d8c46439e608c906693b7759bbcbae
| 8,512,625,225,084 |
c208db4eb260d6ac4f1cc2b8dc949fc2e550d874
|
/jdbc/src/test16_1/dao/AccountDao.java
|
19f300cf7ecb10089145f9906a1c4ff0dadbf1dc
|
[] |
no_license
|
XiaoFangHappy/eclipseWorkSpace
|
https://github.com/XiaoFangHappy/eclipseWorkSpace
|
96004eb8eaa75951525d4357f62c32ef8f4f2539
|
6d1d4b8a6adac48e76b9c643a569f7537b4fa8f3
|
refs/heads/master
| 2021-01-15T22:01:56.922000 | 2017-08-10T05:03:18 | 2017-08-10T05:03:18 | 99,883,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package test16_1.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import test16_1.util.DbUtil;
public class AccountDao {
private Connection conn;
public AccountDao() {
super();
}
public AccountDao(Connection conn) {
super();
this.conn = conn;
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public int transMoney(int id,int money) throws SQLException {
PreparedStatement ps = null;
try {
String sql = "update account set money = money+? where id = ? and (money+?)>=0";
ps = conn.prepareStatement(sql);
ps.setInt(1, money);
ps.setInt(2, id);
ps.setInt(3, money);
return ps.executeUpdate();
}finally {
DbUtil.close(null, ps, null);
}
}
}
|
UTF-8
|
Java
| 836 |
java
|
AccountDao.java
|
Java
|
[] | null |
[] |
package test16_1.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import test16_1.util.DbUtil;
public class AccountDao {
private Connection conn;
public AccountDao() {
super();
}
public AccountDao(Connection conn) {
super();
this.conn = conn;
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public int transMoney(int id,int money) throws SQLException {
PreparedStatement ps = null;
try {
String sql = "update account set money = money+? where id = ? and (money+?)>=0";
ps = conn.prepareStatement(sql);
ps.setInt(1, money);
ps.setInt(2, id);
ps.setInt(3, money);
return ps.executeUpdate();
}finally {
DbUtil.close(null, ps, null);
}
}
}
| 836 | 0.650718 | 0.638756 | 58 | 13.413794 | 16.921762 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.62069 | false | false |
15
|
8121034155b7c4042c836759d2e599e8824c8e77
| 23,965,917,551,705 |
adb0071dfdd943f3d839f26689c5da82cddae37b
|
/src/main/java/com/hr/pojo/Lea.java
|
901a6b6e3737c98b2ec054dd79ddca7bcce401c0
|
[] |
no_license
|
Memory-0309/HRSSM
|
https://github.com/Memory-0309/HRSSM
|
4891bda60d00d3f6a04f4f5abb4ce999f188491c
|
bde4ec3a6dd24d75106f8958c63900775e80ee9e
|
refs/heads/master
| 2022-11-28T19:45:08.850000 | 2020-08-14T09:11:01 | 2020-08-14T09:11:01 | 286,410,970 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hr.pojo;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@ToString
@Accessors(chain = true)
public class Lea {
private Integer id;
private Integer employeeNumber;
private Integer departmentNumber;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date startTime;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date endTime;
private String days;
private String reason;
private String type;
private String manager;
private String status;
private String notes;
}
|
UTF-8
|
Java
| 646 |
java
|
Lea.java
|
Java
|
[] | null |
[] |
package com.hr.pojo;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@ToString
@Accessors(chain = true)
public class Lea {
private Integer id;
private Integer employeeNumber;
private Integer departmentNumber;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date startTime;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date endTime;
private String days;
private String reason;
private String type;
private String manager;
private String status;
private String notes;
}
| 646 | 0.744582 | 0.744582 | 27 | 22.925926 | 13.952103 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false |
15
|
ffb0327daf30964d1d0bd430637cd5f372e329a3
| 31,370,441,177,123 |
e62c3b93b38d2d7781d38ba1cdbabfea2c1cf7af
|
/bocbiiclient/src/main/java/com/boc/bocsoft/mobile/bii/bus/loan/model/PsnLOANPayeeAcountCheck/PsnLOANPayeeAcountCheckResponse.java
|
35217f534bafe7be6bee5bbf2ef609d1a2e1e32e
|
[] |
no_license
|
soghao/zgyh
|
https://github.com/soghao/zgyh
|
df34779708a8d6088b869d0efc6fe1c84e53b7b1
|
09994dda29f44b6c1f7f5c7c0b12f956fc9a42c1
|
refs/heads/master
| 2021-06-19T07:36:53.910000 | 2017-06-23T14:23:10 | 2017-06-23T14:23:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.boc.bocsoft.mobile.bii.bus.loan.model.PsnLOANPayeeAcountCheck;
import com.boc.bocsoft.mobile.bii.common.model.BIIResponse;
import java.util.List;
/**
* Created by lxw4566 on 2016/6/28.
*/
public class PsnLOANPayeeAcountCheckResponse extends BIIResponse<PsnLOANPayeeAcountCheckResult> {
}
|
UTF-8
|
Java
| 305 |
java
|
PsnLOANPayeeAcountCheckResponse.java
|
Java
|
[
{
"context": "sponse;\n\nimport java.util.List;\n\n/**\n * Created by lxw4566 on 2016/6/28.\n */\npublic class PsnLOANPayeeAcount",
"end": 186,
"score": 0.9991199374198914,
"start": 179,
"tag": "USERNAME",
"value": "lxw4566"
}
] | null |
[] |
package com.boc.bocsoft.mobile.bii.bus.loan.model.PsnLOANPayeeAcountCheck;
import com.boc.bocsoft.mobile.bii.common.model.BIIResponse;
import java.util.List;
/**
* Created by lxw4566 on 2016/6/28.
*/
public class PsnLOANPayeeAcountCheckResponse extends BIIResponse<PsnLOANPayeeAcountCheckResult> {
}
| 305 | 0.806557 | 0.770492 | 11 | 26.727272 | 33.352364 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false |
15
|
db34a38c57e629965643dd78a8d56421c518332c
| 7,258,494,765,503 |
808282d7d071fdd272f17a4986f87322feefa282
|
/Source/Controller/src/main/java/io/dolittle/moose/controller/model/LabelSelector.java
|
a9b26febc1c42c19208ae5a4a30b25cf6cbcc7c2
|
[
"MIT"
] |
permissive
|
dolittle-platform/Moose
|
https://github.com/dolittle-platform/Moose
|
78f1262b57fe05e273ff3f84036230d59b34e987
|
a057e036291cb716b75be8ff1c98c111ba827bd4
|
refs/heads/master
| 2023-05-06T18:40:09.307000 | 2020-06-15T07:20:58 | 2020-06-15T07:20:58 | 268,812,685 | 0 | 0 |
MIT
| false | 2021-06-04T21:58:38 | 2020-06-02T13:45:06 | 2020-06-15T07:21:03 | 2021-06-04T21:58:36 | 118 | 0 | 0 | 2 |
Java
| false | false |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package io.dolittle.moose.controller.model;
import lombok.Data;
@Data
public class LabelSelector {
private String labelKey;
private String labelValue;
public String getSelector() {
return labelKey + "=" + labelValue;
}
}
|
UTF-8
|
Java
| 400 |
java
|
LabelSelector.java
|
Java
|
[
{
"context": "// Copyright (c) Dolittle. All rights reserved.\n// Licensed under the MIT l",
"end": 25,
"score": 0.6186632513999939,
"start": 20,
"tag": "NAME",
"value": "ittle"
}
] | null |
[] |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package io.dolittle.moose.controller.model;
import lombok.Data;
@Data
public class LabelSelector {
private String labelKey;
private String labelValue;
public String getSelector() {
return labelKey + "=" + labelValue;
}
}
| 400 | 0.72 | 0.72 | 17 | 22.529411 | 25.950445 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false |
15
|
3cb4925c04d0bdcb70f3636e4bcb71176ddfaf95
| 27,839,978,065,682 |
10ff5d8959e49f02646acdf415962b12555e72cd
|
/src/test/java/pages/AddProjectPage.java
|
940f324ab12e091fedb5f3e84ddbf658c344aa28
|
[] |
no_license
|
aalbuerner87/tareaCesSelenium
|
https://github.com/aalbuerner87/tareaCesSelenium
|
52d814e91194b2235d5dd02b3709aa6ecc4139be
|
0c40dccbe37dfbafec34198d2f51797a16e5e8ea
|
refs/heads/main
| 2023-07-16T11:43:07.987000 | 2021-08-27T12:46:02 | 2021-08-27T12:46:02 | 396,610,052 | 0 | 0 | null | false | 2021-08-25T04:12:59 | 2021-08-16T04:05:00 | 2021-08-24T19:25:56 | 2021-08-25T04:12:58 | 23,818 | 0 | 0 | 0 |
HTML
| false | false |
package pages;
import org.openqa.selenium.By;
import properties.*;
public class AddProjectPage extends BasePage {
SelectorAddProyProperties locator=new SelectorAddProyProperties();
By titulo = locator.getTitulo();
By num = locator.getNum();
By save = locator.getSave();
By category = locator.getCategory();
By members = locator.getMembers();
By membersSelect = locator.getMembersSelect();
By addMemBoton = locator.getAddMemBoton();
String id = "";
public AddProjectPage (){
super( driver );
}
public void escribirProyecto ( String idGenerado , String tituloProyecto ){
write( titulo , tituloProyecto );
write( num , idGenerado );
}
public String generarIdProyecto (){
int numero = (int) (Math.random() * 10000 + 1);
id = "id-proyecto" + "-" + numero;
return id;
}
public void guardarCambios (){
click( save );
String ventana = winHandles( 0 );
switchToVentana( ventana );
}
public void agregarRecursoMiembro ( String Miembro ){
String ventana = winHandles( 1 );
switchToVentana( ventana );
click( category );
String video = "29";
selectOption( category , video );
enter( category );
click( members );
click( membersSelect );
selectOptionByText( membersSelect , Miembro );
enter( membersSelect );
click( addMemBoton );
}
}
|
UTF-8
|
Java
| 1,479 |
java
|
AddProjectPage.java
|
Java
|
[] | null |
[] |
package pages;
import org.openqa.selenium.By;
import properties.*;
public class AddProjectPage extends BasePage {
SelectorAddProyProperties locator=new SelectorAddProyProperties();
By titulo = locator.getTitulo();
By num = locator.getNum();
By save = locator.getSave();
By category = locator.getCategory();
By members = locator.getMembers();
By membersSelect = locator.getMembersSelect();
By addMemBoton = locator.getAddMemBoton();
String id = "";
public AddProjectPage (){
super( driver );
}
public void escribirProyecto ( String idGenerado , String tituloProyecto ){
write( titulo , tituloProyecto );
write( num , idGenerado );
}
public String generarIdProyecto (){
int numero = (int) (Math.random() * 10000 + 1);
id = "id-proyecto" + "-" + numero;
return id;
}
public void guardarCambios (){
click( save );
String ventana = winHandles( 0 );
switchToVentana( ventana );
}
public void agregarRecursoMiembro ( String Miembro ){
String ventana = winHandles( 1 );
switchToVentana( ventana );
click( category );
String video = "29";
selectOption( category , video );
enter( category );
click( members );
click( membersSelect );
selectOptionByText( membersSelect , Miembro );
enter( membersSelect );
click( addMemBoton );
}
}
| 1,479 | 0.610548 | 0.603786 | 65 | 21.753845 | 20.407412 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.569231 | false | false |
15
|
15a7ab27bfc531410233ea58196830b2b9ac2ddf
| 31,353,261,326,721 |
5dc5a9a973013e98fbabe51339f9dfd0b90819f3
|
/demos/2017-02/ViewsDemos/app/src/main/java/com/example/minkov/viewsdemos/game/colliders/ICollisionDetector.java
|
26738c0a858d29a47292c5b8f17e57cd539e30b3
|
[
"MIT"
] |
permissive
|
ta-fork/Mobile-Applications-for-Android
|
https://github.com/ta-fork/Mobile-Applications-for-Android
|
5cc04b0072b97a456bb82e25ed6eb0fe8fe0bea1
|
878fe476783a6dc3e9f5482e13b7f377037d9c2c
|
refs/heads/master
| 2020-06-25T04:11:00.861000 | 2017-10-06T14:04:57 | 2017-10-06T14:04:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.minkov.viewsdemos.game.colliders;
import com.example.minkov.viewsdemos.game.objects.IShape;
/**
* Created by minkov on 2/22/17.
*/
public interface ICollisionDetector {
boolean areColliding(IShape s1, IShape s2);
boolean areColliding(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2);
}
|
UTF-8
|
Java
| 334 |
java
|
ICollisionDetector.java
|
Java
|
[
{
"context": "viewsdemos.game.objects.IShape;\n\n/**\n * Created by minkov on 2/22/17.\n */\n\npublic interface ICollisionDetec",
"end": 138,
"score": 0.9996738433837891,
"start": 132,
"tag": "USERNAME",
"value": "minkov"
}
] | null |
[] |
package com.example.minkov.viewsdemos.game.colliders;
import com.example.minkov.viewsdemos.game.objects.IShape;
/**
* Created by minkov on 2/22/17.
*/
public interface ICollisionDetector {
boolean areColliding(IShape s1, IShape s2);
boolean areColliding(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2);
}
| 334 | 0.730539 | 0.685629 | 12 | 26.833334 | 28.809238 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
15
|
1121f88df74460ba07343f1dc3800ceae41de460
| 19,404,662,291,587 |
7c4a1403c750ded1dc38689044a2ff1e76d58c78
|
/src/main/java/org/techouts/hibernate/client/Client.java
|
2644e4fccbf4926b499390bd3b1587b6abeae38a
|
[] |
no_license
|
somarouthuhema/second
|
https://github.com/somarouthuhema/second
|
e96de48c0a251af9b5442e781f8170b9d2bb1218
|
acdbb722653ee5d286341296c5cf666d5729e7cb
|
refs/heads/master
| 2020-06-02T23:23:15.216000 | 2019-06-11T09:46:58 | 2019-06-11T09:46:58 | 191,342,203 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.techouts.hibernate.client;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.techouts.hibernate.pojos.ChequePayment;
import org.techouts.hibernate.pojos.CreditCard;
public class Client {
public static void main(String[] args)
{
Configuration cg=new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf=cg.buildSessionFactory();
Session s=sf.openSession();
Transaction tx=s.beginTransaction();
CreditCard cc =new CreditCard();
cc.setPayId(4);
cc.setAmount(4000);
cc.setCardType("ICICI");
CreditCard cc1=new CreditCard();
cc1.setPayId(6);
cc1.setAmount(6000);
cc1.setCardType("HDFC");
ChequePayment cp=new ChequePayment();
cp.setPayId(7);
cp.setAmount(5000);
cp.setChequeType("cheque");
s.persist(cc);
s.persist(cc1);
s.persist(cp);
tx.commit();
s.close();
System.out.println("success");
}
}
|
UTF-8
|
Java
| 1,202 |
java
|
Client.java
|
Java
|
[] | null |
[] |
package org.techouts.hibernate.client;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.techouts.hibernate.pojos.ChequePayment;
import org.techouts.hibernate.pojos.CreditCard;
public class Client {
public static void main(String[] args)
{
Configuration cg=new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf=cg.buildSessionFactory();
Session s=sf.openSession();
Transaction tx=s.beginTransaction();
CreditCard cc =new CreditCard();
cc.setPayId(4);
cc.setAmount(4000);
cc.setCardType("ICICI");
CreditCard cc1=new CreditCard();
cc1.setPayId(6);
cc1.setAmount(6000);
cc1.setCardType("HDFC");
ChequePayment cp=new ChequePayment();
cp.setPayId(7);
cp.setAmount(5000);
cp.setChequeType("cheque");
s.persist(cc);
s.persist(cc1);
s.persist(cp);
tx.commit();
s.close();
System.out.println("success");
}
}
| 1,202 | 0.594842 | 0.578203 | 48 | 23.041666 | 17.649313 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.979167 | false | false |
15
|
c884c09029076bb918ef9e563c753de42d084c4d
| 27,779,848,530,113 |
ffab2846c669bd4d083f1d3e07d96e73a39c6cda
|
/ITC/src/Design_Pattern/AbstractFectory/PizzaStore/domain/calms/FrozenCalms.java
|
c121568615ddb900231cbedf20c9f762d3247cf6
|
[] |
no_license
|
AYashchuk/java-training
|
https://github.com/AYashchuk/java-training
|
a4b1840009ff957dabd8d34993f0eeb2ee4382e2
|
07242afd048b6ba6516afdfe693f215b079b7aec
|
refs/heads/master
| 2021-05-29T18:45:19.803000 | 2015-12-11T22:20:52 | 2015-12-11T22:20:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Design_Pattern.AbstractFectory.PizzaStore.domain.calms;
public class FrozenCalms extends Clams {
}
|
UTF-8
|
Java
| 108 |
java
|
FrozenCalms.java
|
Java
|
[] | null |
[] |
package Design_Pattern.AbstractFectory.PizzaStore.domain.calms;
public class FrozenCalms extends Clams {
}
| 108 | 0.833333 | 0.833333 | 4 | 26 | 26.767517 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
15
|
048f950e5a71d40f12ff26745b4eb7055c544e23
| 15,229,954,033,030 |
979c7e052ee23a37f154590990be3d0c0f8411d7
|
/day26/src/main/java/com/springboot/day26/task/PrintTask.java
|
eed0958d954816b0826e4ac99b358018c51518f7
|
[] |
no_license
|
honghhh/springboot
|
https://github.com/honghhh/springboot
|
aa52e24970df581270f7117ea409ea00b0697e60
|
718dfcc25dfafe33a3f6e0b65e257796e2b7e317
|
refs/heads/master
| 2023-06-22T20:10:52.755000 | 2021-12-05T04:43:31 | 2021-12-05T04:43:31 | 174,921,390 | 1 | 0 | null | false | 2023-06-20T18:32:31 | 2019-03-11T03:46:43 | 2021-12-05T04:43:39 | 2023-06-20T18:32:30 | 5,506 | 0 | 0 | 6 |
Java
| false | false |
package com.springboot.day26.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 测试定时器
* @author: huangh
*/
@Component
public class PrintTask {
/**
* 这是一个时间表达式,可以通过简单的配置就能完成各种时间的配置,我们通过CRON表达式几乎可以完成任意的时间搭配,它包含了六或七个域:
* Seconds : 可出现", - * /"四个字符,有效范围为0-59的整数
* Minutes : 可出现", - * /"四个字符,有效范围为0-59的整数
* Hours : 可出现", - * /"四个字符,有效范围为0-23的整数
* DayofMonth : 可出现", - * / ? L W C"八个字符,有效范围为0-31的整数
* Month : 可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc
* DayofWeek : 可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
* Year : 可出现", - * /"四个字符,有效范围为1970-2099年
*
* 下面简单举几个例子:
* "0 0 12 * * ?" 每天中午十二点触发
* "0 15 10 ? * *" 每天早上10:15触发
* "0 15 10 * * ?" 每天早上10:15触发
* "0 15 10 * * ?" 每天早上10:15触发
* "0 15 10 * * ? 2005" 2005年的每天早上10:15触发
* "0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发
* "0 0/5 14 * * ?" 每天从下午2点开始到2:55分结束每5分钟一次触发
* "0 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
* "0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发
* "0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发
* "0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发
*/
/**
* 每小时的10分执行该方法
*/
@Scheduled(cron = "0 10 * * * *")
public void cron() throws Exception {
System.out.println("执行测试cron时间:" + new Date(System.currentTimeMillis()));
}
/**
* 是上一个调用开始后再次调用的延时(不用等待上一次调用完成)
*/
@Scheduled(fixedRate = 1000 * 1)
public void fixedRate() throws Exception {
Thread.sleep(2000);
System.out.println("执行测试fixedRate时间:" + new Date(System.currentTimeMillis()));
}
/**
* 上一个调用完成后再次调用的延时调用
*/
@Scheduled(fixedDelay = 1000 * 1)
public void fixedDelay() throws Exception {
Thread.sleep(3000);
System.out.println("执行测试fixedDelay时间" + new Date(System.currentTimeMillis()));
}
/**
* 第一次被调用前的延时,单位毫秒
*/
@Scheduled(initialDelay = 1000 * 1, fixedDelay = 1000 * 2)
public void initialDelay() throws Exception {
System.out.println("执行测试initialDelay时间" + new Date(System.currentTimeMillis()));
}
}
|
UTF-8
|
Java
| 3,129 |
java
|
PrintTask.java
|
Java
|
[
{
"context": "\n\nimport java.util.Date;\n\n/**\n * 测试定时器\n * @author: huangh\n */\n@Component\npublic class PrintTask {\n\n /**\n",
"end": 201,
"score": 0.9991639256477356,
"start": 195,
"tag": "USERNAME",
"value": "huangh"
}
] | null |
[] |
package com.springboot.day26.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 测试定时器
* @author: huangh
*/
@Component
public class PrintTask {
/**
* 这是一个时间表达式,可以通过简单的配置就能完成各种时间的配置,我们通过CRON表达式几乎可以完成任意的时间搭配,它包含了六或七个域:
* Seconds : 可出现", - * /"四个字符,有效范围为0-59的整数
* Minutes : 可出现", - * /"四个字符,有效范围为0-59的整数
* Hours : 可出现", - * /"四个字符,有效范围为0-23的整数
* DayofMonth : 可出现", - * / ? L W C"八个字符,有效范围为0-31的整数
* Month : 可出现", - * /"四个字符,有效范围为1-12的整数或JAN-DEc
* DayofWeek : 可出现", - * / ? L C #"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
* Year : 可出现", - * /"四个字符,有效范围为1970-2099年
*
* 下面简单举几个例子:
* "0 0 12 * * ?" 每天中午十二点触发
* "0 15 10 ? * *" 每天早上10:15触发
* "0 15 10 * * ?" 每天早上10:15触发
* "0 15 10 * * ?" 每天早上10:15触发
* "0 15 10 * * ? 2005" 2005年的每天早上10:15触发
* "0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发
* "0 0/5 14 * * ?" 每天从下午2点开始到2:55分结束每5分钟一次触发
* "0 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
* "0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发
* "0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发
* "0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发
*/
/**
* 每小时的10分执行该方法
*/
@Scheduled(cron = "0 10 * * * *")
public void cron() throws Exception {
System.out.println("执行测试cron时间:" + new Date(System.currentTimeMillis()));
}
/**
* 是上一个调用开始后再次调用的延时(不用等待上一次调用完成)
*/
@Scheduled(fixedRate = 1000 * 1)
public void fixedRate() throws Exception {
Thread.sleep(2000);
System.out.println("执行测试fixedRate时间:" + new Date(System.currentTimeMillis()));
}
/**
* 上一个调用完成后再次调用的延时调用
*/
@Scheduled(fixedDelay = 1000 * 1)
public void fixedDelay() throws Exception {
Thread.sleep(3000);
System.out.println("执行测试fixedDelay时间" + new Date(System.currentTimeMillis()));
}
/**
* 第一次被调用前的延时,单位毫秒
*/
@Scheduled(initialDelay = 1000 * 1, fixedDelay = 1000 * 2)
public void initialDelay() throws Exception {
System.out.println("执行测试initialDelay时间" + new Date(System.currentTimeMillis()));
}
}
| 3,129 | 0.590399 | 0.509197 | 73 | 29.534246 | 25.398243 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.273973 | false | false |
15
|
c4a59159ad9d238559080c4431ec4b22219d9680
| 936,302,903,696 |
33ce76f5ca55723f46bd85e4b22258c7b4f3aea9
|
/java/com/tShirt/TShirtFinal.java
|
ec6246430fe0a3ab027cee2436145f88096b837e
|
[] |
no_license
|
Raguselvaraj/ProjectDemo
|
https://github.com/Raguselvaraj/ProjectDemo
|
8ccd7fab20db0b53f66215fbfba13709666dab62
|
3cb87656ac9efb423357f7bfc9f55ff8e4e3eb9e
|
refs/heads/master
| 2023-02-18T15:59:55.944000 | 2021-01-18T11:27:09 | 2021-01-18T11:27:09 | 330,628,898 | 0 | 0 | null | false | 2021-01-18T11:27:10 | 2021-01-18T10:20:29 | 2021-01-18T11:04:57 | 2021-01-18T11:27:10 | 5,514 | 0 | 0 | 0 |
Java
| false | false |
package com.tShirt;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.base.BaseClass;
public class TShirtFinal extends BaseClass {
public static void main(String[] args) {
launchBrowser("GOOgle");
launchUrl("http://www.tshirtelephant.com/");
BaseClass b=new BaseClass();
TShirt1 shirt=new TShirt1();
b.isDisplayed(shirt.getAppLogo());
b.isDisplayed(shirt.getCountryFlag());
b.isDisplayed(shirt.getContact_number());
b.isDisplayed(shirt.getEmailId());
b.isDisplayed(shirt.getSignIn());
b.isDisplayed(shirt.getStarted());
b.isDisplayed(shirt.getProducts());
b.isDisplayed(shirt.getServices());
b.isDisplayed(shirt.getAbout());
b.isDisplayed(shirt.getDesignNow());
b.isDisplayed(shirt.getContactNow());
b.isDisplayed(shirt.gettShirts());
b.isDisplayed(shirt.getSportsJersey());
b.isDisplayed(shirt.getMadeInCanada());
b.isDisplayed(shirt.getTankTops());
b.isDisplayed(shirt.getPerformance());
b.isDisplayed(shirt.getWomen());
b.isDisplayed(shirt.getHats());
b.isDisplayed(shirt.getFollowOnInstagram());
b.isDisplayed(shirt.getCustomTShirts());
b.isDisplayed(shirt.getGetStartedBelowCustom());
b.isDisplayed(shirt.getCustomersSaying());
b.isDisplayed(shirt.getPlacingOrder());
b.isDisplayed(shirt.getGetInTouch());
b.isDisplayed(shirt.getAddress());
}
}
|
UTF-8
|
Java
| 1,356 |
java
|
TShirtFinal.java
|
Java
|
[] | null |
[] |
package com.tShirt;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.base.BaseClass;
public class TShirtFinal extends BaseClass {
public static void main(String[] args) {
launchBrowser("GOOgle");
launchUrl("http://www.tshirtelephant.com/");
BaseClass b=new BaseClass();
TShirt1 shirt=new TShirt1();
b.isDisplayed(shirt.getAppLogo());
b.isDisplayed(shirt.getCountryFlag());
b.isDisplayed(shirt.getContact_number());
b.isDisplayed(shirt.getEmailId());
b.isDisplayed(shirt.getSignIn());
b.isDisplayed(shirt.getStarted());
b.isDisplayed(shirt.getProducts());
b.isDisplayed(shirt.getServices());
b.isDisplayed(shirt.getAbout());
b.isDisplayed(shirt.getDesignNow());
b.isDisplayed(shirt.getContactNow());
b.isDisplayed(shirt.gettShirts());
b.isDisplayed(shirt.getSportsJersey());
b.isDisplayed(shirt.getMadeInCanada());
b.isDisplayed(shirt.getTankTops());
b.isDisplayed(shirt.getPerformance());
b.isDisplayed(shirt.getWomen());
b.isDisplayed(shirt.getHats());
b.isDisplayed(shirt.getFollowOnInstagram());
b.isDisplayed(shirt.getCustomTShirts());
b.isDisplayed(shirt.getGetStartedBelowCustom());
b.isDisplayed(shirt.getCustomersSaying());
b.isDisplayed(shirt.getPlacingOrder());
b.isDisplayed(shirt.getGetInTouch());
b.isDisplayed(shirt.getAddress());
}
}
| 1,356 | 0.74115 | 0.739676 | 46 | 28.47826 | 16.423391 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.152174 | false | false |
15
|
a77d537189b9e45532617c2119152bf44b279ea9
| 936,302,903,141 |
d8d796dd8b1a01d59d5eb59841bc791737625271
|
/LAMP_OALT/src/main/java/com/lamp/lease/logic/rcv/impl/Rcv0001s02LogicImpl.java
|
dc6d23d8496ba1d43edce671c0241325b21d3b19
|
[] |
no_license
|
weixiumei/project
|
https://github.com/weixiumei/project
|
f5ab9ea197bbc8d8def4f62fea21c3b645a1a528
|
bea8b8a759ff74bfa0d1790ad70d3766b29065e0
|
refs/heads/master
| 2017-12-03T17:18:07.714000 | 2017-03-24T10:23:49 | 2017-03-24T10:23:49 | 86,030,911 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lamp.lease.logic.rcv.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.poi.ss.usermodel.Workbook;
import org.seasar.framework.util.BigDecimalConversionUtil;
import org.seasar.teeda.core.util.ConverterUtil;
import com.lamp.base.dao.raw.BranchMstDao;
import com.lamp.base.dao.raw.BundleCreateHistoryDao;
import com.lamp.base.dao.raw.CaseMstDao;
import com.lamp.base.dao.raw.CurrencyMstDao;
import com.lamp.base.dao.raw.DataObjectWorktableDao;
import com.lamp.base.dao.raw.LogHistoryDao;
import com.lamp.base.dto.PagingBaseCondDto;
import com.lamp.base.entity.BaseEntity;
import com.lamp.base.entity.raw.BranchMstEntity;
import com.lamp.base.entity.raw.BundleCreateHistoryEntity;
import com.lamp.base.entity.raw.CaseMstEntity;
import com.lamp.base.entity.raw.CurrencyMstEntity;
import com.lamp.base.entity.raw.DataObjectWorktableEntity;
import com.lamp.base.entity.raw.LogHistoryEntity;
import com.lamp.base.logic.impl.PagingBaseLogicImpl;
import com.lamp.base.util.ClassUtil;
import com.lamp.base.util.DatetimeUtil;
import com.lamp.base.util.ListUtil;
import com.lamp.base.util.config.ConfigUtil;
import com.lamp.base.util.constants.CodeKeyValue;
import com.lamp.base.util.constants.CodeMstKbn;
import com.lamp.base.util.constants.CommonConfigKey;
import com.lamp.base.util.constants.CommonConstants;
import com.lamp.base.util.constants.MessageID;
import com.lamp.base.util.constants.MessageParamConst;
import com.lamp.base.util.constants.StringParam;
import com.lamp.base.util.constants.TemplateConfigKey;
import com.lamp.base.util.exception.PromoteMessageException;
import com.lamp.base.util.excle.ExcelSheetUtil;
import com.lamp.base.util.excle.xls.SheetData;
import com.lamp.base.util.string.StringFormatType;
import com.lamp.base.util.string.StringUtil;
import com.lamp.common.dto.DropdownListDto;
import com.lamp.common.util.AccountUtil;
import com.lamp.common.util.CaseUtil;
import com.lamp.common.util.CurrencyUtil;
import com.lamp.common.util.DropdownListUtil;
import com.lamp.lease.dao.rcv.Rcv0001s02Dao;
import com.lamp.lease.dto.rcv.Rcv0001s02Dto;
import com.lamp.lease.dto.rcv.Rcv0001s02UpdateDto;
import com.lamp.lease.entity.rcv.Rcv0001s02Entity;
import com.lamp.lease.logic.rcv.Rcv0001s02Logic;
/**
* 請求回収一覧Logic
*
* @author caiwenhai
* @version 3.00, 2011/05/16
*/
public class Rcv0001s02LogicImpl extends PagingBaseLogicImpl implements
Rcv0001s02Logic {
////////////////////////定数定義////////////////////////////////////////////////////////////
/**
* 換行
*/
private static final String NEW_LINE = "\n";
/**
* 連結
*/
private static final String TILDE = "~";
/**
* 括弧_右
*/
private static final String BRACKET_RIGHT = ")";
/**
* 括弧_左
*/
private static final String BRACKET_LEFT = "(";
/**
* アンダーライン
*/
private static final String STR_LINE = "-";
/**
* アンダーライン
*/
private static final String UNDERLINE = "_";
/**
* 文字列","
*/
private static final String STR_MARK = ",";
/**
* 回収済/已回收コード
*/
private static final String STR_WITHDRAW_CODE = CodeKeyValue.WITHDRAWED.value();
/**
* :
*/
private static final String COLON = ":";
/**
* MESSAGE_LINE
*/
private static final String MESSAGE_LINE = "||";
/**
* CHECK_ON
*/
private static final String CHECK_ON = "true";
/**
* EXECL_CONFIG_NAME
*/
private static final String EXECL_CONFIG_NAME = "Sheet1";
/**
* EXECL_CASEID
*/
private static final String EXECL_CASENO = "CASENO";
// LAMP製品化対応 zlw add start
/**
* EXECL_BRANCHNAME
*/
private static final String EXECL_BRANCHNAME = "BRANCHNAME";
// LAMP製品化対応 zlw add end
// LAMP製品化対応 redmine#48 hxh add start
/**
* EXECL_CONTRACTSTATUS
*/
private static final String EXECL_CONTRACTSTATUS = "CONTRACTSTATUS";
// LAMP製品化対応 redmine#48 hxh add end
/**
* EXECL_AGENCYNAME
*/
private static final String AGENCYNAME = "AGENCYNAME";
/**
* EXECL_SYSDATETIME
*/
private static final String SYSDATETIME = "SYSDATETIME";
/**
* EXECL_CASEID
*/
private static final String CONTRACTNO = "CONTRACTNO";
/**
* EXECL_CASEID
*/
private static final String CUSTOMERNAME = "CUSTOMERNAME";
/**
* EXECL_WITHDRAW_METHOD
*/
private static final String SCHEDULEWITHDRAWMETHODNAME = "SCHEDULEWITHDRAWMETHODNAME";
/**
* EXECL_CASEID
*/
private static final String RECYCLEDATE = "RECYCLEDATE";
/**
* EXECL_DELAYEDDATE
*/
private static final String DELAYEDDATE = "DELAYEDDATE";
/**
* EXECL_BANK
*/
private static final String BANK = "BANK";
/**
* EXECL_CASEID
*/
private static final String COLLCTIONTYPE = "COLLCTIONTYPE";
/**
* EXECL_COLLCTIONSTATUS
*/
private static final String COLLCTIONSTATUS = "COLLCTIONSTATUS";
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun del 2013/05/02 start********************/
/**
* EXECL_SUM
*/
// private static final String SUM = "SUM";
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun del 2013/05/02 end**********************/
/**
* EXECL_ENFORCEFLAG
*/
private static final String ENFORCEFLAG = "ENFORCEFLAG";
/**
* EXECL_通貨
*/
private static final String CURRENCY = "CURRENCY";
/**
* EXECL_回収方法モード
*/
private static final String METHODMODE = "METHODMODE";
/**
* EXECL_回収日モード
*/
private static final String DATEMODE = "DATEMODE";
/**
* EXECL_回収銀行モード
*/
private static final String BANKMODE = "BANKMODE";
/**
* EXECL_DATA_LIST
*/
private static final String EXECL_DATA_LIST = "TRANSFERLIST";
/**
* 通货List
*/
public String[] list = { "", "", "" };
/**
* ファイル一括消込ワークDao
*/
DataObjectWorktableDao dataObjectWorktableDao;
/**
* 請求回収一覧Dao
*/
private Rcv0001s02Dao dao;
/**
* 案件番号Dao
*/
private CaseMstDao caseNodao;
/**
* 消込履歴ワークDao
*/
private BundleCreateHistoryDao bundleCreateHistoryDao;
/**
* ログDAO
*/
private LogHistoryDao logHistoryDao;
/**
* 貨マスタDao
*/
private CurrencyMstDao currencyMstDao;
// LAMP製品化対応 zlw add start
/**
* 拠点マスタDao
*/
private BranchMstDao branchMstDao;
// LAMP製品化対応 zlw add end
/**
* 検索条件をセット
*
* @param dto
* 検索条件Dto
* @return 検索条件Dto
*/
private Rcv0001s02Dto setSelCondition(Rcv0001s02Dto dto) {
// プルダウンリスト中で「null」っだことを判断する
String all = ConfigUtil.commonConfig(CommonConfigKey.SelectAllValue);
// 銀行名:[null]
if (all.equals(dto.getBankSearch())) {
dto.setBankSearch(null);
}
// 基軸通貨:[null]
if (all.equals(dto.getKeyCurrency())) {
dto.setKeyCurrency(null);
}
// 案件情報取得
CaseMstEntity caseMstEntity = CaseUtil.getCaseMstEntityItems(dto
.getCaseDivionSearch());
if (null != caseMstEntity
&& null != caseMstEntity.getForceUnleaseDelayCoupons()) {
// 強制解約回数
dto.setForceUnleaseDelayCoupons(caseMstEntity.getForceUnleaseDelayCoupons());
}
/**MULT_160320_Current Month Receivable の修正 dengfeibing 2016/4/20 add start**/
// 契約状況From:[null]
if (all.equals(dto.getContractConditionFromSearch())) {
dto.setContractConditionFromSearch(null);
}
// 契約状況To:[null]
if (all.equals(dto.getContractConditionToSearch())) {
dto.setContractConditionToSearch(null);
}
/**MULT_160320_Current Month Receivable の修正 dengfeibing 2016/4/20 add end**/
// 免除フラグ
dto.setExemptionFlg(CodeKeyValue.OFF.value());
return dto;
}
/**
* 明細検索処理
*
* @param condDto
* 検索条件Dto
* @return 明細配列
*/
@Override
protected BaseEntity[] search(PagingBaseCondDto condDto) {
// 自分のDtoに変換する
Rcv0001s02Dto dto = (Rcv0001s02Dto) condDto;
// 検索条件をセット
setSelCondition(dto);
Rcv0001s02Dto oldDto = new Rcv0001s02Dto();
Rcv0001s02Entity[] resultList = null;
if (session.getCondDto(session.getLinkInfo().getCurrentPageId()) == null
|| (session.getCondDto(session.getLinkInfo().getCurrentPageId()) != null
&& !RETURN_FLG_YES.equals(session.getCondDto(
session.getLinkInfo().getCurrentPageId()).getReturnFlg()))) {
oldDto = (Rcv0001s02Dto) ClassUtil.copyFields(oldDto, dto);
} else {
oldDto = (Rcv0001s02Dto) session.getCondDto(session.getLinkInfo()
.getCurrentPageId());
}
// 回収ステータス
oldDto.setWithdrawStatus(CodeMstKbn.COLLECTION_STATUS.value());
// 回収種別
oldDto.setWithdrawCasus(CodeMstKbn.BILL_FLG.value());
// 予定回収方法SCHEDULE_WITHDRAW_METHOD
oldDto.setScheduleWithdrawMethod(CodeMstKbn.REAL_COLLECTION_WAY.value());
/*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add start ***/
// 予定回収方法SCHEDULE_WITHDRAW_METHOD
oldDto.setInvoiceType(CodeMstKbn.BILL_TYPE.value());
/*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add end ***/
// 実回収方法REAL_WITHDRAW_METHOD
oldDto.setRealWithdrawMethod(CodeMstKbn.REAL_COLLECTION_WAY.value());
// 回収先区分
oldDto.setRealWithdrawKbn(CodeMstKbn.REAL_WITHDRAW_KBN.value());
// セッションで一覧情報が存在しない場合、検索します
if (oldDto.getRstAllList() == null) {
// 初期検索場合は、DBから一覧情報を取得する
//その他 53,65,97,90,71,76,67,68,69
oldDto.setKbnOtherSearchList(
new String[]{
CodeKeyValue.BILL_DUTY_STAMP.value(),
//CodeKeyValue.BILL_NOTICE_FEE.value(),
CodeKeyValue.BILL_INSURANCE_CTF.value(),
CodeKeyValue.BILL_OTHER.value(),
CodeKeyValue.BILL_BURDEN_INTEREST.value(),
// CodeKeyValue.BILL_ADVANCED_PAYMENT.value(),
CodeKeyValue.BILL_BANK_TRANSFER_FEE_CASHPRICE.value(),
CodeKeyValue.BILL_BANK_TRANSFER_FEE_COMMISSION.value(),
CodeKeyValue.BILL_BANK_TRANSFER_FEE_CAMPAIGN.value(),});
//名義変更手数料 54,55
oldDto.setBillTransferList(
new String[]{
CodeKeyValue.BILL_TRANSFER_OWNERSHIP_GOV.value(),
CodeKeyValue.BILL_TRANSFER_OWNERSHIP_OALT.value()});
/************ weixiumei 20161108 start **********/
//保険料94,95,96
oldDto.setKbnInsuranceSearchList(
new String[]{
CodeKeyValue.BILL_INSURANCE_CO.value(),
CodeKeyValue.BILL_INSURANCE_VO.value(),
CodeKeyValue.BILL_INSURANCE_CS.value()});
//督促手数料('INV', 'TI', 'R')
oldDto.setBillTypeList(new String[]{CodeKeyValue.BILL_TYPE_INVOICE_INV.value(),
CodeKeyValue.BILL_TYPE_INVOICE_TI.value(), CodeKeyValue.BILL_TYPE_INVOICE_R.value()});
// oldDto.setCountryId(Integer.valueOf(CodeKeyValue.LANGUAGE_SIMPLIFIED_THAILAND.value()));
/************ weixiumei 20161108 end **********/
/************ weixiumei 2017/02/03 add start **********/
//('TI', 'R')
oldDto.setBillTypeInvoiceTiR(new String[]{
CodeKeyValue.BILL_TYPE_INVOICE_TI.value(),
CodeKeyValue.BILL_TYPE_INVOICE_R.value()});
/************ weixiumei 2017/02/03 add end **********/
// 未回収
oldDto.setKbnPaidStatusNotRequestSearch0(CodeKeyValue.NOT_WITHDRAWED.value());
// 依頼中
oldDto.setKbnPaidStatusRequest1(CodeKeyValue.WITHDRAWING.value());
// 一部入金
oldDto.setKbnPartWithdrawedSearch2(CodeKeyValue.PART_WITHDRAWED.value());
// 回収済
oldDto.setKbnWithdrawStatusSearch3(CodeKeyValue.WITHDRAWED.value());
// 業務日時
oldDto.setDateTypeTime(DatetimeUtil.currentAppDateTime());
// 免除フラグ
oldDto.setExemptionFlg(CodeKeyValue.EXEMPTION_ON.value());
/**MULT_160320_Current Month Receivable の修正 dengfeibing 2016/4/20 add start**/
// プルダウンリスト中で「null」っだことを判断する
String all = ConfigUtil.commonConfig(CommonConfigKey.SelectAllValue);
// 契約状況From:[null]
if (all.equals(oldDto.getContractConditionFromSearch())) {
oldDto.setContractConditionFromSearch(null);
}
// 契約状況To:[null]
if (all.equals(oldDto.getContractConditionToSearch())) {
oldDto.setContractConditionToSearch(null);
}
/**MULT_160320_Current Month Receivable の修正 dengfeibing 2016/4/20 add end**/
//wanghuan mult1.5 2016.1.12 start
// 業務日付取得
Date dtType = DatetimeUtil.currentAppDateTime();
//wanghuan mult1.5 2016.1.12 end
// OALT STEP1 redmine #322 「Branch」にたいして「空白」検索可能とする modify by hao 20170203 start
List<String> branchSearchListTmp = new ArrayList<String>();
if (StringUtil.isEmpty(oldDto.getBranchSearch())) {
for (DropdownListDto d : session.getLoginInfo().getAplBranchInfoItems()) {
branchSearchListTmp.add(d.getValue());
}
} else {
branchSearchListTmp.add(oldDto.getBranchSearch());
}
oldDto.setBranchSearchList(branchSearchListTmp);
// OALT STEP1 redmine #322 「Branch」にたいして「空白」検索可能とする modify by hao 20170203 end
// 一覧検索する
// resultList = (Rcv0001s02Entity[])ListUtil.pageMaxRowConvert(
// dao.getTransferDataItems(oldDto,
// CommonConstants.PAGING_MAXROW.value()
// //wanghuan mult1.5 2016.1.12 start
// ,dtType
// ));
// //wanghuan mult1.5 2016.1.12 end
resultList = dao.getTransferDataItems(oldDto,
CommonConstants.PAGING_MAXROW.value()
,dtType);
/********weixiumei 20161109 add start ********************/
//パラメータ.単据管理番号 =null
//パラメータ.index =0;
String billManagementNoParam = null;
int index = 0;
List<Rcv0001s02Entity> resultListNoDuplicate = new ArrayList<Rcv0001s02Entity>();
// 毎項目設定する
for (int i = 0; i < resultList.length; i++) {
//IF 抽出したデータ「i」.単据管理番号 <> パラメータ.単据管理番号
if(resultList[i].getBillManagementNo()!=null){
String billType = "";
if(resultList[i].getBillType() != null){
billType = resultList[i].getBillType().replace(" ", "");
}
if(!resultList[i].getBillManagementNo().equals(billManagementNoParam)){
//パラメータ.単据管理番号 = 抽出したデータ「i」.単据管理番号
//パラメータ.index = i ;
billManagementNoParam = resultList[i].getBillManagementNo();
//抽出したデータ「i」.単据管理番号 == 'INV'
if(CodeKeyValue.BILL_TYPE_INVOICE_INV.value().equals(billType)){
//抽出したデータ「パラメータ.index」.Invoice No == 抽出したデータ「i」.単据番号
resultList[i].setInvoiceNo1(resultList[i].getBillNo());
}else if(CodeKeyValue.BILL_TYPE_INVOICE_TI.value().equals(billType)){//抽出したデータ「i」.単据管理番号 == 'TI'
//抽出したデータ「パラメータ.index」.Tax Invoice No == 抽出したデータ「i」.単据番号
resultList[i].setTaxInvoiceNo(resultList[i].getBillNo());
}else if(CodeKeyValue.BILL_TYPE_INVOICE_R.value().equals(billType)){//抽出したデータ「i」.単据管理番号 == 'R'
//抽出したデータ「パラメータ.index」.Receipt No == 抽出したデータ「i」.単据番号
resultList[i].setReceiptNo1(resultList[i].getBillNo());
}
}else{
//抽出したデータ「i」.単据管理番号 == 'INV'
if(CodeKeyValue.BILL_TYPE_INVOICE_INV.value().equals(billType)){
//抽出したデータ「パラメータ.index」.Invoice No ==
//抽出したデータ「i」.単据番号 +”,”+抽出したデータ「パラメータ.index」.Invoice No
if (StringUtil.isEmpty(resultListNoDuplicate.get(index-1).getInvoiceNo1())){
resultListNoDuplicate.get(index-1).setInvoiceNo1( resultList[i].getBillNo());
}else{
resultListNoDuplicate.get(index-1).setInvoiceNo1(resultListNoDuplicate.get(index-1).getInvoiceNo1() +
STR_MARK + resultList[i].getBillNo());
}
}else if(CodeKeyValue.BILL_TYPE_INVOICE_TI.value().equals(billType)){//抽出したデータ「i」.単据管理番号 == 'TI'
//抽出したデータ「パラメータ.index」.Tax Invoice No
//== 抽出したデータ「i」.単据番号 +””+ 抽出したデータ「パラメータ.index」.Tax Invoice No
if (StringUtil.isEmpty(resultListNoDuplicate.get(index-1).getTaxInvoiceNo())){
resultListNoDuplicate.get(index-1).setTaxInvoiceNo(resultList[i].getBillNo());
}else{
resultListNoDuplicate.get(index-1).setTaxInvoiceNo(resultListNoDuplicate.get(index-1).getTaxInvoiceNo() +
STR_MARK + resultList[i].getBillNo());
}
}else if(CodeKeyValue.BILL_TYPE_INVOICE_R.value().equals(billType)){//抽出したデータ「i」.単据管理番号 == 'R'
//抽出したデータ「パラメータ.index」.Receipt No
//== 抽出したデータ「i」.単据番号 +”,”+ 抽出したデータ「パラメータ.index」.Receipt No
if (StringUtil.isEmpty(resultListNoDuplicate.get(index-1).getReceiptNo1())){
resultListNoDuplicate.get(index-1).setReceiptNo1(resultList[i].getBillNo());
}else{
resultListNoDuplicate.get(index-1).setReceiptNo1(resultListNoDuplicate.get(index-1).getReceiptNo1() +
STR_MARK + resultList[i].getBillNo());
}
}
continue;
}
}
resultListNoDuplicate.add(resultList[i]);
index++;
}
resultList = (Rcv0001s02Entity[])resultListNoDuplicate.toArray(new Rcv0001s02Entity[resultListNoDuplicate.size()]);;
//TODO
resultList = (Rcv0001s02Entity[])ListUtil.pageMaxRowConvert(resultList);
/********weixiumei 20161109 add end ********************/
for (int i = 0; i < resultList.length; i++) {
resultList[i].setIndex(i);
// 回数-回数連番
if (resultList[i].getCouponSeq() != null) {
resultList[i].setLblLine(STR_LINE);
}
// 【 延滞開始日~延滞終了日(延滞日数)】
if (resultList[i].getDelayedStartDate() != null) {
resultList[i].setDelayDateDsp(StringUtil.formatDate(
resultList[i].getDelayedStartDate(),
StringFormatType.DATE_FORMAT_MM_DD)
+ TILDE
+ StringUtil.formatDate(resultList[i]
.getDelayedAccountDate(),
StringFormatType.DATE_FORMAT_MM_DD));
// (延滞日数)
resultList[i].setDelayDays(BRACKET_LEFT
+ resultList[i].getDelayedDays().toString()
+ BRACKET_RIGHT);
}
// 回収済/已回收:
resultList[i].setCountWithdrawResultAmount(resultList[i].getWithdrawResultAmount());
if (resultList[i].getWithdrawResultAmount() != null
&& ConverterUtil.convertToInt(resultList[i].getWithdrawResultAmount()) > 0
&& !resultList[i].getWithdrawStatus().equals(
CodeKeyValue.WITHDRAWED.value())) {
resultList[i].setWithdrawresultText(DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, STR_WITHDRAW_CODE, dto.getCountryId())
+ COLON
+ StringUtil.formatNumber(resultList[i]
.getWithdrawResultAmount(),
StringFormatType.NUMBER_FORMAT_MONEY));
} else if (resultList[i].getWithdrawStatus().equals(
CodeKeyValue.WITHDRAWED.value())) {
resultList[i].setCountWithdrawResultAmount(resultList[i]
.getWithdrawResultAmount());
} else {
resultList[i]
.setCountWithdrawResultAmount(BigDecimalConversionUtil
.toBigDecimal(0));
}
// 物件名称
if (resultList[i].getWithdrawCasus().equals(
CodeKeyValue.BILL_SUPPLIES_DISPOSAL.value())) {
resultList[i].setSuppliesName(BRACKET_LEFT
+ resultList[i].getSuppliesName() + BRACKET_RIGHT);
}
resultList[i].setDetailKey(resultList[i].getContractNo() + STR_MARK + resultList[i].getWithdrawCasus() + STR_MARK + resultList[i].getCoupon());
}
// 初回検索結果を格納する
oldDto.setRstAllList(resultList);
// 総件数をセットする。
oldDto.setCount(resultList.length);
// 初期化ページ情報
dto.setCount(resultList.length);
if (!PagingBaseLogicImpl.RETURN_FLG_YES.equals(dto.getReturnFlg())) {
dto.setCurrentIndex(0);
dto.setCurrentPage(1);
} else {
dto.setCurrentIndex(dto.getCurrentPage() - 1);
}
dto.setHdnPageAllCnt(resultList.length);
dto.setRstAllList(resultList);
} else {
// セッションから検索結果を取得する
resultList = (Rcv0001s02Entity[]) oldDto.getRstAllList();
}
// (計XX件)
dto.setAllCntShow(ConfigUtil.getConstantsValue(
MessageParamConst.ALL_CNT_TITLE, String.valueOf(oldDto.getCount())));
// //////////////////////すべてレコードを取得し、画面でページ制御処理//////////////////////////
// 当ページの最大レコード順番を計算する
int recMaxPos = 0;
int offset = dto.getCurrentIndex() * dto.getPageMaxCount();
if (resultList.length >= (dto.getCurrentIndex() + 1) * dto.getPageMaxCount()) {
recMaxPos = (dto.getCurrentIndex() + 1) * dto.getPageMaxCount();
} else {
recMaxPos = resultList.length;
}
// 当ページの明細初期化
Rcv0001s02Entity[] resultPageList = new Rcv0001s02Entity[recMaxPos
- offset];
// 画面明細可視性属性のセット
for (int i = offset; i < recMaxPos; i++) {
resultPageList[i - offset] = new Rcv0001s02Entity();
// 当ページの明細内容をセットする
ClassUtil.copyFields(resultPageList[i - offset], resultList[i]);
}
// ////////////////////////////////////////////////////////////////////////////////
// 当画面の明細をセット
dto.setTransferDataItems(resultPageList);
// 検索結果を戻る
return dto.getTransferDataItems();
}
/**
* 書類作成&口座引落ファイル作成処理
*
* @param dto
* 引落予定一覧Dto
* @return 引落予定一覧Dto
*/
public Rcv0001s02Dto doFileCreateCheck(Rcv0001s02Dto dto) {
// 案件情報取得
CaseMstEntity caseMstEntity = caseNodao.selectById(dto
.getCaseDivionSearch());
// リース料・延滞利息回収順番
String withdrawNo = null;
if (null != caseMstEntity) {
// リース料・延滞利息回収順番設定
withdrawNo = caseMstEntity.getLeaseDelayInterestReteWithdrawNo();
// 案件情報.案件略称設定
dto.setCasesNameAbr(caseMstEntity.getCasesNameAbr());
}
// チェックフラグ初期化
Boolean checkFlg = false;
// 契約番号Flg
Boolean contractNoCheckflg = false;
// ワーニングメッセージフラグ--WRCV0005
Boolean warn05Flg = false;
// ワーニングメッセージリスト
StringBuffer warnMessageList = new StringBuffer();
// ワーニングメッセージ(temp)
StringBuffer tempList = new StringBuffer();
// ワーニングメッセージ(tempWarn)
StringBuffer tempWarn = new StringBuffer();
// セッション情報取得
Rcv0001s02Dto condDto = (Rcv0001s02Dto) session.getCondDto(session
.getLinkInfo().getCurrentPageId());
// セッションから検索結果を取得
Rcv0001s02Entity[] resultList = (Rcv0001s02Entity[]) condDto
.getRstAllList();
// 選択項目判断
tempWarn = new StringBuffer();
contractNoCheckflg = false;
for (int j = 0; j < resultList.length; j++) {
// チェックしているチェックボックス
if (CHECK_ON.equals(resultList[j].getSelectedCheck())) {
checkFlg = true;
contractNoCheckflg = true;
// 回収ステータスが依頼中のレコードが一件でも存在する場合
if (CodeKeyValue.WITHDRAWING.value().equals(
resultList[j].getWithdrawStatus())
&& !warn05Flg) {
// WRCV0005
warn05Flg = true;
}
}
// 案件属性マスタ.リース料・延滞利息回収順番 = リース料先にに の場合
if (CodeKeyValue.LEASE_DELAY_WITHDRAW_SORT_LEASE.value()
.equals(withdrawNo)) {
// 契約ごとに、延滞利息を選択する場合
if (CHECK_ON
.equals(resultList[j].getSelectedCheck())
&& CodeKeyValue.BILL_DELAYED.value().equals(
resultList[j].getCodeId())) {
// リース料を選択しない項目の存在をチェックする
for (int k = 0; k < resultList.length; k++) {
// リース料を選択しない項目の存在する場合
if (!CHECK_ON.equals(resultList[k]
.getSelectedCheck())
&& CodeKeyValue.BILL_LEASE.value().equals(
resultList[k].getCodeId())
&& resultList[j].getCoupon().compareTo(
resultList[k].getCoupon()) == 0) {
// WRCV0015
tempWarn
.append(ConfigUtil
.getMessage(
MessageID.WRCV0015,
resultList[j].getContractNo(),
ConfigUtil
.getConstantsValue(MessageParamConst.DELAYED),
ConfigUtil
.getConstantsValue(MessageParamConst.LEASE_FEE)));
tempWarn.append(MESSAGE_LINE);
}
}
}
// 案件属性マスタ.リース料・延滞利息回収順番 = 延滞利息先に の場合
} else if (CodeKeyValue.LEASE_DELAY_WITHDRAW_SORT_DELAY.value()
.equals(withdrawNo)) {
// 契約ごとに、リース料を選択する場合
if (CHECK_ON
.equals(resultList[j].getSelectedCheck())
&& CodeKeyValue.BILL_LEASE.value().equals(
resultList[j].getCodeId())) {
// 延滞利息を選択しない項目の存在をチェックする
for (int k = 0; k < resultList.length; k++) {
// 延滞利息を選択しない項目の存在する場合
if (!CHECK_ON.equals(resultList[k]
.getSelectedCheck())
&& CodeKeyValue.BILL_DELAYED.value().equals(
resultList[k].getCodeId())
&& resultList[j].getCoupon().compareTo(
resultList[k].getCoupon()) == 0) {
// WRCV0015
tempWarn
.append(ConfigUtil
.getMessage(
MessageID.WRCV0015,
resultList[j].getContractNo(),
ConfigUtil
.getConstantsValue(MessageParamConst.LEASE_FEE),
ConfigUtil
.getConstantsValue(MessageParamConst.DELAYED)));
tempWarn.append(MESSAGE_LINE);
}
}
}
}
//}
// ワーニングメッセージ(temp)
if (contractNoCheckflg) {
tempList.append(tempWarn);
}
}
// チェックしているチェックボックスが存在しない場合
if (!checkFlg) {
// エラー出力
throw new PromoteMessageException(false, MessageID.ERCV0002);
}
// ワーニングメッセージ--WRCV0005
if (warn05Flg) {
warnMessageList.append(ConfigUtil.getMessage(MessageID.WRCV0005));
warnMessageList.append(MESSAGE_LINE);
}
// ワーニングメッセージリスト設定
dto.setWarnMessageList(warnMessageList.append(tempList));
return dto;
}
/**
* 対象データワークテーブル削除&追加
*
* @param dto
* 引落予定一覧Dto
* @param processFlag
* 処理区分 0:請求書出力 1:催告書出力 2:引落ファイル 3:未回収状況 4:引落依頼取消 5:Tax Invoice/Receipt
* @return 新規件数
*/
public int targetWorkTableFunction(Rcv0001s02Dto dto, int processFlag) {
// 新規件数
int updateNum = 0;
// 删除当前sessionId既成的记录
DataObjectWorktableEntity[] dataObjectWorktableEntityList
= this.dataObjectWorktableDao.selectBySessionId(session.getSessionId());
// dataObjectWorktableDao.deleteBatch(dataObjectWorktableEntityList);
// セッション情報取得
Rcv0001s02Dto condDto = (Rcv0001s02Dto) session.getCondDto(session
.getLinkInfo().getCurrentPageId());
Rcv0001s02Entity[] resultList = (Rcv0001s02Entity[]) condDto
.getRstAllList();
boolean insertFlag = false;
// 登録処理
// 請求書出力の場合
if (processFlag == 0) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
// 回収状況 = 回収済以外 且つ 請求書出力要否 = 要 且つ 回収方法 = GIRO以外
/***********【TFS向け仕様追加・変更対応】 zhou update start 2013/01/07**************/
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
// // 契約状況
// int contractCondition = 0;
// if (!StringUtil.isEmpty(resultList[i].getContractCondition())) {
// contractCondition = Integer.parseInt(resultList[i].getContractCondition());
// }
// // 契約状況区分 034:31.開始済
// int alreadyStarted = Integer.parseInt(CodeKeyValue.ALREADY_STARTED.value());
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
if (
// ((CodeKeyValue.BILL_LEASE.value().equals(
// resultList[i].getWithdrawCasus())
//
// /***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/26**************/
// //&& resultList[i].getCoupon() > 0
// && (resultList[i].getCoupon() == 0 || contractCondition >= alreadyStarted)
// )
// //******* LAMP Step2向け対応 by tangzhiming 2013/04/15 start *********/
//// || CodeKeyValue.BILL_DEPOSIT.value().equals(
//// resultList[i].getWithdrawCasus())
//// /***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/26**************/
//// || CodeKeyValue.BILL_DELAYED.value().equals(
//// resultList[i].getWithdrawCasus())
//// || CodeKeyValue.BILL_EXPIRY_OPTIONS
//// .value().equals(resultList[i].getWithdrawCasus())
// || !CodeKeyValue.BILL_LEASE.value().equals(
// resultList[i].getWithdrawCasus())
// || (CodeKeyValue.BILL_LEASE.value().equals(resultList[i].getWithdrawCasus())
// && resultList[i].getCoupon() > 0)
// //******* LAMP Step2向け対応 by tangzhiming 2013/04/15 end *********/
// )
// &&
!CodeKeyValue.WITHDRAWED.value().equals(
resultList[i].getWithdrawStatus())
// && CodeKeyValue.IS_APPLY_BOOK_CREATE_ON.value().equals(
// resultList[i].getRequestFileOutput())
/*&& !CodeKeyValue.REAL_SDAPPROPRIATE.value().equals(
resultList[i].getScheduleWithdrawMethod())*/) {
/***********【TFS向け仕様追加・変更対応】 zhou update end 2013/01/07****************/
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1007);
}
// 催告書出力の場合
} else if (processFlag == 1) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
// 回収状況 = 回収済以外 且つ 回収方法:GIRO以外
if (!CodeKeyValue.WITHDRAWED.value().equals(
resultList[i].getWithdrawStatus())
/***********【TFS向け仕様追加・変更対応】 caowei add 2012/1/6 start******************/
//&& !CodeKeyValue.COLLECTION_WAY_GIRO.value().equals(
&& !CodeKeyValue.REAL_SDAPPROPRIATE.value().equals(
/***********【TFS向け仕様追加・変更対応】 caowei add 2012/1/6 end********************/
resultList[i].getScheduleWithdrawMethod())) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1008);
}
// 引落ファイル
} else if (processFlag == 2) {
for (int i = 0; i < resultList.length; i++) {
// 銀行区分
String bankDiv = AccountUtil.getBankKbn(resultList[i]
.getScheduleWithdrawAccountNo());
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
// 契約状況
int contractCondition = 0;
if (!StringUtil.isEmpty(resultList[i].getContractCondition())) {
contractCondition = Integer.parseInt(resultList[i].getContractCondition());
}
// 契約状況区分 034:31.開始済
int alreadyStarted = Integer.parseInt(CodeKeyValue.ALREADY_STARTED.value());
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
if (((CodeKeyValue.BILL_LEASE.value().equals(
resultList[i].getWithdrawCasus())
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
//&& resultList[i].getCoupon() > 0
&& (resultList[i].getCoupon() == 0 || contractCondition >= alreadyStarted)
)
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
|| CodeKeyValue.BILL_DELAYED.value().equals(
resultList[i].getWithdrawCasus())
|| CodeKeyValue.BILL_EXPIRY_OPTIONS
.value().equals(resultList[i].getWithdrawCasus()))
&& !CodeKeyValue.WITHDRAWED.value().equals(
resultList[i].getWithdrawStatus())
&& CodeKeyValue.REAL_WITHDRAWAL.value().equals(
resultList[i].getScheduleWithdrawMethod())
&& (CodeKeyValue.BANK_DIV_NONGYE.value().equals(bankDiv)
|| CodeKeyValue.BANK_DIV_KOUSYOU.value().equals(bankDiv))) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1009);
}
// 未回収状況
} else if (processFlag == 3) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
if (CodeKeyValue.BILL_LEASE.value().equals(
resultList[i].getWithdrawCasus())
&& !CodeKeyValue.WITHDRAWED.value().equals(
resultList[i].getWithdrawStatus())
&& !StringUtil.isEmpty(resultList[i].getDelayedNo())) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1010);
}
// 依頼取消
} else if (processFlag == 4) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
// 契約状況
int contractCondition = 0;
if (!StringUtil.isEmpty(resultList[i].getContractCondition())) {
contractCondition = Integer.parseInt(resultList[i].getContractCondition());
}
// 契約状況区分 034:31.開始済
int alreadyStarted = Integer.parseInt(CodeKeyValue.ALREADY_STARTED.value());
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
if (((CodeKeyValue.BILL_LEASE.value().equals(resultList[i].getWithdrawCasus())
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
// && resultList[i].getCoupon() > 0
&& (resultList[i].getCoupon() == 0 || contractCondition >= alreadyStarted)
)
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
|| CodeKeyValue.BILL_DELAYED.value().equals(
resultList[i].getWithdrawCasus())
|| CodeKeyValue.BILL_EXPIRY_OPTIONS.value().
equals(resultList[i].getWithdrawCasus()))
&& CodeKeyValue.WITHDRAWING.value().equals(
resultList[i].getWithdrawStatus())) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
if (resultList[i].getWithdrawCasus() != null) {
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
}
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1006);
}
// OALT STEP1 20161201 modify by カク start
// Tax Invoice/Receipt
} else if (processFlag == 5) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回数
dataObjectWorktableEntity.setCoupon(resultList[i].getCoupon());
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV0068);
}
}
// OALT STEP1 20161201 modify by カク end
return updateNum;
}
/**
* 口座ファイル一括作成管理テーブルにデータを追加処理
*
* @param dto
* 引落予定一覧Dto
* @param fileName
* ZIPファイルのファイル名
* @param realWithdrawScheduleDate
* 実回収予定日
* @param businessDate
* 業務日付
* @param withdrawKbn
* 回収区分
* @return 更新件数
*/
public int doBundleCreateHistoryInsert(Rcv0001s02Dto dto, String fileName,
Date realWithdrawScheduleDate, Date businessDate, String withdrawKbn) {
// 作成ファイルパス
String filePath = ConfigUtil
.commonConfig(CommonConfigKey.RequestOutPutPath);
// 更新対象
BundleCreateHistoryEntity insertEntity = new BundleCreateHistoryEntity();
// 案件番号
insertEntity.setCaseNo(dto.getCaseDivionSearch());
/*** zlw 2013/12/23 add start ***/
// 拠点
insertEntity.setBranchCode(dto.getBranchSearch());
/*** zlw 2013/12/23 add end ***/
// 請求処理区分
insertEntity
.setRequestKbn(CodeKeyValue.REQUEST_KBN_SINGLE_WITHDRAWAL_FILE
.value());
// 一括実施日時
insertEntity.setBundleTime(DatetimeUtil.dateToTimestamp(businessDate));
// 処理ステータス
insertEntity.setBundleStatus(CodeKeyValue.SUM_UP_STATUS_COMPLETE
.value());
// 作成ファイルパス
insertEntity.setFilePath(filePath);
// 作成ファイル名
insertEntity.setFileName(fileName);
// 画面.回収予定日FROM
insertEntity.setWithdrawScheduleDateFrom(DatetimeUtil.dateToSQLDate(dto
.getApplyDateFromSearch()));
// 画面.回収予定日TO
insertEntity.setWithdrawScheduleDateTo(DatetimeUtil.dateToSQLDate(dto
.getApplyDateToSearch()));
return bundleCreateHistoryDao.insert(insertEntity);
}
/**
* 依頼取消処理
*
* @param dto
* 引落予定一覧Dto
* @param updateNum
* updateNum
* @return 引落予定一覧Dto
*/
public Rcv0001s02Dto doRequestCancellation(Rcv0001s02Dto dto, int updateNum) {
// セッション情報取得
Rcv0001s02Dto condDto = (Rcv0001s02Dto) session.getCondDto(session
.getLinkInfo().getCurrentPageId());
// セッションから検索結果を取得
Rcv0001s02Entity[] resultList = (Rcv0001s02Entity[]) condDto
.getRstAllList();
// 操作ログエンティティ リスト
List < LogHistoryEntity > logHistoryList =
new ArrayList < LogHistoryEntity > ();
// 業務日時取得
Date businessDate = DatetimeUtil.currentAppDateTime();
// 選択し対象を操作ログテーブルにデータを追加する
for (int i = 0; i < resultList.length; i++) {
// チェックしているチェックボックス
if (CHECK_ON.equals(resultList[i]
.getSelectedCheck())) {
// ログを新規する
LogHistoryEntity logHistoryEntity = new LogHistoryEntity();
// 操作日付 = 業務日時
logHistoryEntity.setOperationTime(DatetimeUtil
.dateToTimestamp(businessDate));
// ログタイプ = 1:作業ログ
logHistoryEntity.setLogType(CodeKeyValue.LOG_BUSNESS.value());
// ユーザーID = ユーザーID
logHistoryEntity.setUserId(session.getLoginInfo().getUserId());
// 部門ID = システムに登録したユーザーの部門ID
logHistoryEntity.setDeptId(session.getLoginInfo().getDeptId());
// ログのコメント:選択した契約番号+"_"+回数+"_"+回数連番+"_"+備考(備考 = "依頼取消")
logHistoryEntity.setComment(resultList[i].getContractNo() + UNDERLINE
+ String.valueOf(resultList[i].getCoupon()) + UNDERLINE
+ String.valueOf(resultList[i].getCouponSeq()) + UNDERLINE
+ ConfigUtil.getConstantsValue(MessageParamConst.REQUEST_CANCEL
.value()));
// ログロストに追加する
logHistoryList.add(logHistoryEntity);
}
}
// 操作ログテーブルにデータを一括追加する
// ログのコメント:ワークテーブルの契約番号+"_"+回数+"_"+回数連番+"_"+備考
doInsertLogBatch(logHistoryList);
// DB更新を行う
// 当月請求テーブルに対応するレコードを削除する
dao.deleteMonthData();
// 引落予定更新 Dto
Rcv0001s02UpdateDto updateDto = new Rcv0001s02UpdateDto();
// 回収ステータス 0:"未回収"を設定する
updateDto.setWithdrawStatusNo(CodeKeyValue.NOT_WITHDRAWED.value());
// 回収ステータス 2:"一部入金"を設定する
updateDto.setWithdrawStatusPart(CodeKeyValue.PART_WITHDRAWED.value());
// セッションIDを設定する
updateDto.setSessionId(session.getSessionId());
// 回収種別:10:リース料を設定する
updateDto.setWithdrawCasus(CodeKeyValue.BILL_LEASE.value());
// 新規者/更新者を設定する
updateDto.setModifyUser(session.getLoginInfo().getUserId());
// 新規日付/更新日付を設定する
updateDto.setModifyDate(DatetimeUtil.dateToTimestamp(businessDate));
// 排他日時
updateDto.setLastModifyDate(dto.getLastModifyDate());
// 請求書作成フラグを設定する
updateDto.setRequstFileCreatFlgOff(CodeKeyValue.REQUST_FILE_CREAT_FLG_OFF
.value());
// 請求回収情報に対応するレコード更新
int requestNum = dao.updateRequstWithdrawInfo(updateDto);
// 回収種別:20:延滞利息を設定する
updateDto.setWithdrawCasus(CodeKeyValue.BILL_DELAYED.value());
// 延滞情報に対応するレコード更新
int delayNum = dao.updateDelayedInfo(updateDto);
// 回収種別:50:満了時オプション売却金を設定する
updateDto.setWithdrawCasus(CodeKeyValue.BILL_EXPIRY_OPTIONS.value());
// 満了オプション買取金
int buyOptNum = dao.updateBuyOptionWhithdrawInfo(updateDto);
// 請求回収情報に更新した件数 + 延滞情報に更新した件数 <> 対象件数 の場合
if (updateNum != requestNum + delayNum + buyOptNum) {
throw new PromoteMessageException(false, MessageID.ERCV0019);
}
return dto;
}
/**
* 操作ログテーブルにデータを一括追加する
*
* @param logHistoryList
* 操作ログ エンティティ リスト
*/
private void doInsertLogBatch(List < LogHistoryEntity > logHistoryList) {
// アレイを定義する
LogHistoryEntity[] logHistoryEntities = new LogHistoryEntity[logHistoryList
.size()];
// リストをアレイに転換する
logHistoryList.toArray(logHistoryEntities);
// DBに追加する
logHistoryDao.insertBatch(logHistoryEntities);
}
/**
* EXCEL出力処理
*
* @param dto
* 引落予定一覧Dto
* @return 引落予定一覧Dto
*/
public Rcv0001s02Dto doExcel(Rcv0001s02Dto dto) {
// EXCELファイル
String fileName = "";
// SheetData
SheetData sheetData = null;
// List作成
List < SheetData > dataList = new ArrayList < SheetData > ();
// EXCEL対応内容
Workbook workBook = null;
// HashMap作成
Map < StringParam, String > paramMap = new HashMap < StringParam, String > ();
// ログインユーザID
String userId = null;
// 業務日時
String date = null;
// SheetData作成
sheetData = createTransferSheet(dto);
// Listにデータセット
dataList.add(sheetData);
// EXCELファイル内容作成
workBook = ExcelSheetUtil
.fillData(TemplateConfigKey.rcv0001r16, dataList);
// 支払種別に従って、該当種別の一括支払申請書を作成する。
// ログインユーザID
userId = session.getLoginInfo().getUserId();
// 業務日時
date = StringUtil.formatDate(DatetimeUtil.currentAppDateTime(),
StringFormatType.DATE_FORMAT_YYYYMMDDHHMMSS);
// HashMapセット
paramMap.put(StringParam.TEMPLATE_FILE_USER, userId);
paramMap.put(StringParam.TEMPLATE_FILE_DATETIME, date);
// EXCELファイル名取得
fileName = ConfigUtil.generateXLSFileName(TemplateConfigKey.rcv0001r16,
paramMap);
// EXCEL内容セット
dto.setWorkBook(workBook);
// EXCELファイル名セット
dto.setFileName(fileName);
// 返回DTO
return dto;
}
/**
* 請求回収一覧sheet
*
* @param dto
* 請求回収一覧Dto
* @return 請求回収一覧SheetData
*/
private SheetData createTransferSheet(Rcv0001s02Dto dto) {
// 通貨情報を全取得する
CurrencyMstEntity[] currencyInfo = currencyMstDao.selectAll();
// 通貨マップを定義する
Map < String, String > currencyMap = new HashMap < String, String > ();
// 通貨情報を繰り返す
for (CurrencyMstEntity cur : currencyInfo) {
// マップを設定
currencyMap.put(cur.getCurrencyId(), cur.getCurrencySign());
}
// SheetData
SheetData sheetData = new SheetData(ConfigUtil
.getConstantsValue(MessageParamConst.TRANSFER_SCHEDULE_SHEET_NAME),
EXECL_CONFIG_NAME);
// セッション情報取得
Rcv0001s02Dto condDto = (Rcv0001s02Dto) session.getCondDto(session
.getLinkInfo().getCurrentPageId());
// セッションから検索結果を取得
Rcv0001s02Entity[] resultList = (Rcv0001s02Entity[]) condDto
.getRstAllList();
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/02/18 start******************/
/**** Lease产品化-课题及改善内容 redmine#3553 kuangweijun modify 2015/08/28 start ****/
// 英国のカントリーIDを取得
Integer countryBritainId = ConfigUtil.getCountryId(Locale.ENGLISH);
// // 中国のカントリーIDを取得
// Integer countryBritainId = ConfigUtil.getCountryId(Locale.CHINA);
/**** Lease产品化-课题及改善内容 redmine#3553 kuangweijun modify 2015/08/28 end ****/
// LAMP製品化対応 zlw add start
// OALT STEP1 redmine #322 「Branch」にたいして「空白」検索可能とする modify by hao 20170203 start
if (StringUtil.isEmpty(dto.getBranchSearch())) {
sheetData.addData(EXECL_BRANCHNAME, null);
} else {
// 国ID
String countryId = ConfigUtil.getCountryId(session.getLoginInfo().getLocale()).toString();
BranchMstEntity branchMstEntity = branchMstDao.getSiteName(dto.getBranchSearch(), countryId);
sheetData.addData(EXECL_BRANCHNAME, branchMstEntity.getBranchName());
}
// OALT STEP1 redmine #322 「Branch」にたいして「空白」検索可能とする modify by hao 20170203 end
// LAMP製品化対応 zlw add end
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/02/18 end******************/
// LAMP製品化対応 redmine#48 hxh add start
// 契約状況From
String contractConditionFromSearch = DropdownListUtil.getCodeNameByCode(CodeMstKbn.CONTACT_STATUS_KBN, dto.getContractConditionFromSearch());
// 契約状況To
String contractConditionToSearch = DropdownListUtil.getCodeNameByCode(CodeMstKbn.CONTACT_STATUS_KBN, dto.getContractConditionToSearch());
// 契約状況
String contractConditionSearch = "";
// 契約状況From != null || 契約状況To != nullの場合、契約状況の中で「~」を追加すること。
if(!(contractConditionFromSearch.equals("") && contractConditionToSearch.equals(""))){
contractConditionSearch = contractConditionFromSearch + TILDE + contractConditionToSearch;
}
sheetData.addData(EXECL_CONTRACTSTATUS, contractConditionSearch);
// LAMP製品化対応 redmine#48 hxh add end
// 案件名称
sheetData.addData(EXECL_CASENO, DropdownListUtil.getCodeNameByCode(
CodeMstKbn.CASE_ATTR, condDto.getCaseDivionSearch(),
countryBritainId));
// 売主
sheetData.addData(AGENCYNAME, condDto.getAgencyNameSearch());
// 出力日時
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
/*sheetData.addData(SYSDATETIME, DatetimeUtil.dateToTimestamp(DatetimeUtil
.currentAppDate()));*/
sheetData.addData(SYSDATETIME, StringUtil.formatDate(DatetimeUtil
.currentAppDateTime(),
StringFormatType.DATE_FORMAT_YYYY_M_D));
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
// 契約番号
sheetData.addData(CONTRACTNO, condDto.getContractNoForSearch());
// 顧客
sheetData.addData(CUSTOMERNAME, condDto.getCustNameSearch());
// 回収方法モード
sheetData.addData(METHODMODE, DropdownListUtil.getCodeNameByCode(
CodeMstKbn.SEARCH_MODE, dto.getSchedulRealModelWay(),
countryBritainId));
// 回収方法
sheetData.addData(SCHEDULEWITHDRAWMETHODNAME, DropdownListUtil
.getCodeNameByCode(CodeMstKbn.REAL_COLLECTION_WAY, dto
.getRealCollectionWay(), countryBritainId));
// 回収日
if (condDto.getApplyDateToSearch() != null
&& condDto.getApplyDateFromSearch() != null) {
sheetData.addData(RECYCLEDATE, StringUtil.formatDate(condDto
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
// .getApplyDateFromSearch(), StringFormatType.DATE_FORMAT_DDMMMYYYY)
.getApplyDateFromSearch(), StringFormatType.DATE_FORMAT_YYYY_M_D)
+ TILDE + StringUtil.formatDate(condDto.getApplyDateToSearch(),
// StringFormatType.DATE_FORMAT_DDMMMYYYY));
StringFormatType.DATE_FORMAT_YYYY_M_D));
} else if (condDto.getApplyDateFromSearch() != null) {
sheetData.addData(RECYCLEDATE, StringUtil.formatDate(condDto
.getApplyDateFromSearch(),
// StringFormatType.DATE_FORMAT_DDMMMYYYY));
StringFormatType.DATE_FORMAT_YYYY_M_D));
} else if (condDto.getApplyDateToSearch() != null) {
sheetData.addData(RECYCLEDATE, TILDE
+ StringUtil.formatDate(condDto.getApplyDateToSearch(),
// StringFormatType.DATE_FORMAT_DDMMMYYYY));
StringFormatType.DATE_FORMAT_YYYY_M_D));
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
}
// 回収日モード
sheetData.addData(DATEMODE, DropdownListUtil.getCodeNameByCode(
CodeMstKbn.SEARCH_MODE, dto.getSchedulRealModelDay(),
countryBritainId));
// 遅延
sheetData.addData(DELAYEDDATE, condDto.getDelayedDateSearch());
// 回収銀行
sheetData.addData(BANK, condDto.getBankBranchNameCon());
// 回収銀行モード
sheetData.addData(BANKMODE, DropdownListUtil.getCodeNameByCode(
CodeMstKbn.SEARCH_MODE, dto.getSchedulRealModelBank(),
countryBritainId));
// 回収種別
String collectionType = "";
// リース料
if (CHECK_ON.equals(condDto.getKbnLeaseAmountSearch())) {
collectionType = DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_LEASE.value(), countryBritainId);
}
// 延滞利息
if (CHECK_ON.equals(condDto.getKbnDelayAmountSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_DELAYED.value(), countryBritainId);
}
// 解約損害金
if (CHECK_ON.equals(condDto.getKbnContractCancellationSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_END_AGREEMENT.value(), countryBritainId);
}
// 物件処分金
if (CHECK_ON.equals(condDto.getKbnThingMoneySearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_SUPPLIES_DISPOSAL.value(), countryBritainId);
}
// 満了買取金
if (CHECK_ON.equals(condDto.getKbnAcceptanceDateSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_EXPIRY_OPTIONS.value(), countryBritainId);
}
// 保証金
if (CHECK_ON.equals(condDto.getKbnDepositSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_DEPOSIT.value(), countryBritainId);
}
// 管理費
if (CHECK_ON.equals(condDto.getKbnAdministrationFeeSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_ADMINISTRATION_FEE.value(), countryBritainId);
}
// 前渡金利息
if (CHECK_ON.equals(condDto.getKbnAdvancedPaymentInterestSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_ADVANCED_PAYMENT_INTEREST.value(),
countryBritainId);
}
// 据置利息
if (CHECK_ON.equals(condDto.getKbnGracePeriodInterestSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_GRACE_PERIOD_INTEREST.value(),
countryBritainId);
}
// その他
if (CHECK_ON.equals(condDto.getKbnOtherSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_OTHER.value(), countryBritainId);
}
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun add 2013/05/16 start********************/
// 保証金(元本)
if (CHECK_ON.equals(condDto.getKbnGuaranteeDepositSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_GUARANTEE_DEPOSIT.value(), countryBritainId);
}
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun add 2013/05/16 end ********************/
// 前受利息
if (CHECK_ON.equals(condDto.getKbnPrepaidInterestSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_PREPAID_INTEREST.value(), countryBritainId);
}
// 繰上返済金
if (CHECK_ON.equals(condDto.getKbnPrepaymentSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_PREPAYMENT.value(), countryBritainId);
}
sheetData.addData(COLLCTIONTYPE, collectionType);
// 回収状況
String collctionStatus = "";
// 未回収
if (CHECK_ON.equals(condDto.getKbnPaidStatusNotRequestSearch())) {
collctionStatus = DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, CodeKeyValue.NOT_WITHDRAWED
.value(), countryBritainId);
}
// 依頼中
if (CHECK_ON.equals(condDto.getKbnPaidStatusRequest())) {
if (!collctionStatus.equals("")) {
collctionStatus = collctionStatus + STR_MARK;
}
collctionStatus += DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, CodeKeyValue.WITHDRAWING.value(),
countryBritainId);
}
// 一部入金
if (CHECK_ON.equals(condDto.getKbnPartWithdrawedSearch())) {
if (!collctionStatus.equals("")) {
collctionStatus = collctionStatus + STR_MARK;
}
collctionStatus += DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, CodeKeyValue.PART_WITHDRAWED
.value(), countryBritainId);
}
// 回収済
if (CHECK_ON.equals(condDto.getKbnWithdrawStatusSearch())) {
if (!collctionStatus.equals("")) {
collctionStatus = collctionStatus + STR_MARK;
}
collctionStatus += DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, CodeKeyValue.WITHDRAWED.value(),
countryBritainId);
}
sheetData.addData(COLLCTIONSTATUS, collctionStatus);
// 通貨
sheetData.addData(CURRENCY, CurrencyUtil.getCurrencyName(condDto
.getKeyCurrency()));
// 強制解約予定
if (condDto.getEnforceEndAgreeScheduldSearch()) {
sheetData.addData(ENFORCEFLAG, 1);
} else {
sheetData.addData(ENFORCEFLAG, 0);
}
sheetData.addData(COLLCTIONSTATUS, collctionStatus);
// dropdownLists
DropdownListDto[] currencyNameItems = CurrencyUtil.getCurrencyList(
false, CodeKeyValue.CURRENCY_LIST_KBN_CONTRACT.value());
if (!ListUtil.isEmpty(currencyNameItems)) {
for (int i = 0; i < currencyNameItems.length && i < 3; i++) {
list[i] = "***合计(" + currencyNameItems[i].getLabel()
+ ")***";
}
}
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun del 2013/05/02 start********************/
// sheetData.addData(SUM, list[0]);
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun del 2013/05/02 end**********************/
// ローデータ保存用
List < Object > rowDataList = new ArrayList < Object > ();
// ファイルレコード項目保存用
List < List < Object > > transferScheduleList = new ArrayList < List < Object > > ();
// 番号
int listNum = 1;
for (int i = 0; i < resultList.length; i++) {
// ローデータ保存用
rowDataList = new ArrayList < Object > ();
// 番号
rowDataList.add(listNum);
// 売主番号
rowDataList.add(resultList[i].getAgencyCustCode());
// 売主名
rowDataList.add(resultList[i].getAgencyName());
// 顧客番号
rowDataList.add(resultList[i].getCustomerCode());
// 顧客名
rowDataList.add(resultList[i].getCustomerName());
// 契約番号
rowDataList.add(resultList[i].getContractNo());
// LAMP製品化対応 zlw add start
// 拠点名
rowDataList.add(resultList[i].getBranchNm());
// LAMP製品化対応 zlw add end
// 回収種別
rowDataList.add(resultList[i].getWithdrawCasusName());
// 物件番号
rowDataList.add(resultList[i].getSuppliesNo());
// 物件名
rowDataList.add(resultList[i].getSuppliesName());
//wanghuan mult1.5 2016.1.12 start
// 契約状況
rowDataList.add(resultList[i].getContractConditionNow());
//wanghuan mult1.5 2016.1.12 end
// 回数
if (resultList[i].getCouponSeq() != null) {
rowDataList.add(resultList[i].getCoupon().toString()
+ STR_LINE + resultList[i].getCouponSeq());
} else {
rowDataList.add(resultList[i].getCoupon());
}
// 回収状況
rowDataList.add(resultList[i].getWithdrawStatusName());
// 回収予定日
String scheduleDate = "";
scheduleDate = StringUtil.formatDate(resultList[i].getWithdrawScheduleDate(),
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
// StringFormatType.DATE_FORMAT_DDMMMYYYY);
StringFormatType.DATE_FORMAT_YYYY_M_D);
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
// 【 延滞開始日~延滞終了日(延滞日数)】
if (resultList[i].getDelayedStartDate() != null) {
scheduleDate = scheduleDate + "\t\n" + StringUtil.formatDate(
resultList[i].getDelayedStartDate(),
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
//StringFormatType.DATE_FORMAT_DDMMMYYYY)
StringFormatType.DATE_FORMAT_YYYY_M_D)
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
+ TILDE
+ StringUtil.formatDate(resultList[i]
.getDelayedAccountDate(),
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
// StringFormatType.DATE_FORMAT_DDMMMYYYY);
StringFormatType.DATE_FORMAT_YYYY_M_D);
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
// (延滞日数)
scheduleDate += BRACKET_LEFT
+ resultList[i].getDelayedDays().toString()
+ BRACKET_RIGHT;
}
rowDataList.add(scheduleDate);
// 回収予定日の営業日
rowDataList.add(DatetimeUtil.getWorkDate(resultList[i]
.getWithdrawScheduleDate(), resultList[i]
.getWithdrawWorkdayFlg(), CodeKeyValue.WORKDAY_FLG_BEFORE
.value(), resultList[i].getKeyCurrencyId()));
// 回収先コード
rowDataList.add(resultList[i].getWithdrawScheduleCustomerCode());
// 回収先名
rowDataList.add(resultList[i].getWithdrawScheduleCustomerName());
// 予定回収方法
rowDataList.add(resultList[i].getScheduleWithdrawMethodName());
// 予定回収先区分
rowDataList.add(resultList[i].getScheduleWithdrawKbnName());
// 予定回収銀行
if (resultList[i].getScheduleBankBranchName() != null) {
rowDataList.add(resultList[i].getScheduleBankBranchName() + NEW_LINE
+ resultList[i].getScheduleWithdrawAccountNo());
} else {
rowDataList.add(null);
}
// 取引通貨Name
rowDataList.add(StringUtil.trim(resultList[i].getKeyCurrencyIdName()));
// 取引通貨ID(非表示)
rowDataList.add(resultList[i].getKeyCurrencyId());
// 回収予定金額
rowDataList.add(resultList[i].getWithdrawScheduleAmount());
// 未回収金額
if (resultList[i].getNotWithdrawAmount() != null) {
rowDataList.add(resultList[i].getNotWithdrawAmount());
} else {
rowDataList.add(BigDecimal.ZERO);
}
// 回収済金額
if (resultList[i].getWithdrawResultAmount() != null) {
rowDataList.add(resultList[i].getWithdrawResultAmount());
} else {
rowDataList.add(BigDecimal.ZERO);
}
// 回収実績日
rowDataList.add(StringUtil.formatDate(resultList[i].getWithdrawResultDate(),
StringFormatType.DATE_FORMAT_YYYY_M_D));
// 実回収方法
rowDataList.add(resultList[i].getRealWithdrawMethodName());
// 実回収先区分
rowDataList.add(resultList[i].getRealWithdrawKbnName());
// 実回収銀行
if (resultList[i].getRealBankBranchName() != null) {
rowDataList.add(resultList[i].getRealBankBranchName() + NEW_LINE
+ resultList[i].getRealWithdrawAccountNo());
} else {
rowDataList.add(null);
}
rowDataList.add(resultList[i].getDebitNoteOutputDate());
// 請求書番号
rowDataList.add(resultList[i].getInvoiceNo());
/*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add start ***/
// 発票分類
rowDataList.add(resultList[i].getInvType());
// 発票発行金額
rowDataList.add(resultList[i].getInvIssueAmount());
// 領収書番号
rowDataList.add(resultList[i].getReceiptNo());
// 領収書発行日
rowDataList.add(resultList[i].getReceiptSsueDate());
// 領収書発行金額
rowDataList.add(resultList[i].getReceiptIssueAmount());
/*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add end ***/
transferScheduleList.add(rowDataList);
// 番号
listNum++;
}
// Listにデータをセット
sheetData.addData(EXECL_DATA_LIST, transferScheduleList);
return sheetData;
}
/**
* 設置 請求回収一覧dao
*
* @param dao
* 請求回収一覧dao
*/
public void setDao(Rcv0001s02Dao dao) {
this.dao = dao;
}
/**
* 設置 案件番号Dao
*
* @param caseNodao
* 案件番号Dao
*/
public void setCaseNodao(CaseMstDao caseNodao) {
this.caseNodao = caseNodao;
}
/**
* 设置ファイル一括消込ワークDao
*
* @param dataObjectWorktableDao ファイル一括消込ワークDao
*/
public void setDataObjectWorktableDao(
DataObjectWorktableDao dataObjectWorktableDao) {
this.dataObjectWorktableDao = dataObjectWorktableDao;
}
/**
* 设置 消込履歴ワークDao
*
* @param bundleCreateHistoryDao
* 消込履歴ワークDao
*/
public void setBundleCreateHistoryDao(
BundleCreateHistoryDao bundleCreateHistoryDao) {
this.bundleCreateHistoryDao = bundleCreateHistoryDao;
}
/**
* ログDAOを設定する
*
* @param logHistoryDao
* ログDAO
*/
public void setLogHistoryDao(LogHistoryDao logHistoryDao) {
this.logHistoryDao = logHistoryDao;
}
/**
* 貨マスタDaoを設定する
*
* @param currencyMstDao
* 貨マスタDao
*/
public void setCurrencyMstDao(CurrencyMstDao currencyMstDao) {
this.currencyMstDao = currencyMstDao;
}
/**
* 设置branchMstDao
*
* @param branchMstDao branchMstDao
*/
public void setBranchMstDao(BranchMstDao branchMstDao) {
this.branchMstDao = branchMstDao;
}
}
|
UTF-8
|
Java
| 88,979 |
java
|
Rcv0001s02LogicImpl.java
|
Java
|
[
{
"context": "cv0001s02Logic;\n\n/**\n * 請求回収一覧Logic\n * \n * @author caiwenhai\n * @version 3.00, 2011/05/16\n */\npublic class Rcv",
"end": 2418,
"score": 0.9993046522140503,
"start": 2409,
"tag": "USERNAME",
"value": "caiwenhai"
},
{
"context": "/\n private static final String CUSTOMERNAME = \"CUSTOMERNAME\";\n\n /**\n * EXECL_WITHDRAW_METHOD\n */\n ",
"end": 4521,
"score": 0.9991292357444763,
"start": 4509,
"tag": "USERNAME",
"value": "CUSTOMERNAME"
},
{
"context": " //******* LAMP Step2向け対応 by tangzhiming 2013/04/15 start *********/\n//// ",
"end": 32896,
"score": 0.9991235733032227,
"start": 32885,
"tag": "USERNAME",
"value": "tangzhiming"
},
{
"context": " //******* LAMP Step2向け対応 by tangzhiming 2013/04/15 end *********/\n// ",
"end": 33864,
"score": 0.9990739226341248,
"start": 33853,
"tag": "USERNAME",
"value": "tangzhiming"
},
{
"context": " }\n // OALT STEP1 20161201 modify by カク start\n // Tax Invoice/Receipt\n } el",
"end": 48899,
"score": 0.6513270735740662,
"start": 48897,
"tag": "NAME",
"value": "カク"
},
{
"context": "ltList[i].getInvoiceNo()); \n /*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add start ***",
"end": 78794,
"score": 0.5107818841934204,
"start": 78792,
"tag": "USERNAME",
"value": "li"
},
{
"context": "ist[i].getInvoiceNo()); \n /*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add start ***/\n ",
"end": 78799,
"score": 0.8713692426681519,
"start": 78794,
"tag": "NAME",
"value": "uheng"
}
] | null |
[] |
package com.lamp.lease.logic.rcv.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.poi.ss.usermodel.Workbook;
import org.seasar.framework.util.BigDecimalConversionUtil;
import org.seasar.teeda.core.util.ConverterUtil;
import com.lamp.base.dao.raw.BranchMstDao;
import com.lamp.base.dao.raw.BundleCreateHistoryDao;
import com.lamp.base.dao.raw.CaseMstDao;
import com.lamp.base.dao.raw.CurrencyMstDao;
import com.lamp.base.dao.raw.DataObjectWorktableDao;
import com.lamp.base.dao.raw.LogHistoryDao;
import com.lamp.base.dto.PagingBaseCondDto;
import com.lamp.base.entity.BaseEntity;
import com.lamp.base.entity.raw.BranchMstEntity;
import com.lamp.base.entity.raw.BundleCreateHistoryEntity;
import com.lamp.base.entity.raw.CaseMstEntity;
import com.lamp.base.entity.raw.CurrencyMstEntity;
import com.lamp.base.entity.raw.DataObjectWorktableEntity;
import com.lamp.base.entity.raw.LogHistoryEntity;
import com.lamp.base.logic.impl.PagingBaseLogicImpl;
import com.lamp.base.util.ClassUtil;
import com.lamp.base.util.DatetimeUtil;
import com.lamp.base.util.ListUtil;
import com.lamp.base.util.config.ConfigUtil;
import com.lamp.base.util.constants.CodeKeyValue;
import com.lamp.base.util.constants.CodeMstKbn;
import com.lamp.base.util.constants.CommonConfigKey;
import com.lamp.base.util.constants.CommonConstants;
import com.lamp.base.util.constants.MessageID;
import com.lamp.base.util.constants.MessageParamConst;
import com.lamp.base.util.constants.StringParam;
import com.lamp.base.util.constants.TemplateConfigKey;
import com.lamp.base.util.exception.PromoteMessageException;
import com.lamp.base.util.excle.ExcelSheetUtil;
import com.lamp.base.util.excle.xls.SheetData;
import com.lamp.base.util.string.StringFormatType;
import com.lamp.base.util.string.StringUtil;
import com.lamp.common.dto.DropdownListDto;
import com.lamp.common.util.AccountUtil;
import com.lamp.common.util.CaseUtil;
import com.lamp.common.util.CurrencyUtil;
import com.lamp.common.util.DropdownListUtil;
import com.lamp.lease.dao.rcv.Rcv0001s02Dao;
import com.lamp.lease.dto.rcv.Rcv0001s02Dto;
import com.lamp.lease.dto.rcv.Rcv0001s02UpdateDto;
import com.lamp.lease.entity.rcv.Rcv0001s02Entity;
import com.lamp.lease.logic.rcv.Rcv0001s02Logic;
/**
* 請求回収一覧Logic
*
* @author caiwenhai
* @version 3.00, 2011/05/16
*/
public class Rcv0001s02LogicImpl extends PagingBaseLogicImpl implements
Rcv0001s02Logic {
////////////////////////定数定義////////////////////////////////////////////////////////////
/**
* 換行
*/
private static final String NEW_LINE = "\n";
/**
* 連結
*/
private static final String TILDE = "~";
/**
* 括弧_右
*/
private static final String BRACKET_RIGHT = ")";
/**
* 括弧_左
*/
private static final String BRACKET_LEFT = "(";
/**
* アンダーライン
*/
private static final String STR_LINE = "-";
/**
* アンダーライン
*/
private static final String UNDERLINE = "_";
/**
* 文字列","
*/
private static final String STR_MARK = ",";
/**
* 回収済/已回收コード
*/
private static final String STR_WITHDRAW_CODE = CodeKeyValue.WITHDRAWED.value();
/**
* :
*/
private static final String COLON = ":";
/**
* MESSAGE_LINE
*/
private static final String MESSAGE_LINE = "||";
/**
* CHECK_ON
*/
private static final String CHECK_ON = "true";
/**
* EXECL_CONFIG_NAME
*/
private static final String EXECL_CONFIG_NAME = "Sheet1";
/**
* EXECL_CASEID
*/
private static final String EXECL_CASENO = "CASENO";
// LAMP製品化対応 zlw add start
/**
* EXECL_BRANCHNAME
*/
private static final String EXECL_BRANCHNAME = "BRANCHNAME";
// LAMP製品化対応 zlw add end
// LAMP製品化対応 redmine#48 hxh add start
/**
* EXECL_CONTRACTSTATUS
*/
private static final String EXECL_CONTRACTSTATUS = "CONTRACTSTATUS";
// LAMP製品化対応 redmine#48 hxh add end
/**
* EXECL_AGENCYNAME
*/
private static final String AGENCYNAME = "AGENCYNAME";
/**
* EXECL_SYSDATETIME
*/
private static final String SYSDATETIME = "SYSDATETIME";
/**
* EXECL_CASEID
*/
private static final String CONTRACTNO = "CONTRACTNO";
/**
* EXECL_CASEID
*/
private static final String CUSTOMERNAME = "CUSTOMERNAME";
/**
* EXECL_WITHDRAW_METHOD
*/
private static final String SCHEDULEWITHDRAWMETHODNAME = "SCHEDULEWITHDRAWMETHODNAME";
/**
* EXECL_CASEID
*/
private static final String RECYCLEDATE = "RECYCLEDATE";
/**
* EXECL_DELAYEDDATE
*/
private static final String DELAYEDDATE = "DELAYEDDATE";
/**
* EXECL_BANK
*/
private static final String BANK = "BANK";
/**
* EXECL_CASEID
*/
private static final String COLLCTIONTYPE = "COLLCTIONTYPE";
/**
* EXECL_COLLCTIONSTATUS
*/
private static final String COLLCTIONSTATUS = "COLLCTIONSTATUS";
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun del 2013/05/02 start********************/
/**
* EXECL_SUM
*/
// private static final String SUM = "SUM";
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun del 2013/05/02 end**********************/
/**
* EXECL_ENFORCEFLAG
*/
private static final String ENFORCEFLAG = "ENFORCEFLAG";
/**
* EXECL_通貨
*/
private static final String CURRENCY = "CURRENCY";
/**
* EXECL_回収方法モード
*/
private static final String METHODMODE = "METHODMODE";
/**
* EXECL_回収日モード
*/
private static final String DATEMODE = "DATEMODE";
/**
* EXECL_回収銀行モード
*/
private static final String BANKMODE = "BANKMODE";
/**
* EXECL_DATA_LIST
*/
private static final String EXECL_DATA_LIST = "TRANSFERLIST";
/**
* 通货List
*/
public String[] list = { "", "", "" };
/**
* ファイル一括消込ワークDao
*/
DataObjectWorktableDao dataObjectWorktableDao;
/**
* 請求回収一覧Dao
*/
private Rcv0001s02Dao dao;
/**
* 案件番号Dao
*/
private CaseMstDao caseNodao;
/**
* 消込履歴ワークDao
*/
private BundleCreateHistoryDao bundleCreateHistoryDao;
/**
* ログDAO
*/
private LogHistoryDao logHistoryDao;
/**
* 貨マスタDao
*/
private CurrencyMstDao currencyMstDao;
// LAMP製品化対応 zlw add start
/**
* 拠点マスタDao
*/
private BranchMstDao branchMstDao;
// LAMP製品化対応 zlw add end
/**
* 検索条件をセット
*
* @param dto
* 検索条件Dto
* @return 検索条件Dto
*/
private Rcv0001s02Dto setSelCondition(Rcv0001s02Dto dto) {
// プルダウンリスト中で「null」っだことを判断する
String all = ConfigUtil.commonConfig(CommonConfigKey.SelectAllValue);
// 銀行名:[null]
if (all.equals(dto.getBankSearch())) {
dto.setBankSearch(null);
}
// 基軸通貨:[null]
if (all.equals(dto.getKeyCurrency())) {
dto.setKeyCurrency(null);
}
// 案件情報取得
CaseMstEntity caseMstEntity = CaseUtil.getCaseMstEntityItems(dto
.getCaseDivionSearch());
if (null != caseMstEntity
&& null != caseMstEntity.getForceUnleaseDelayCoupons()) {
// 強制解約回数
dto.setForceUnleaseDelayCoupons(caseMstEntity.getForceUnleaseDelayCoupons());
}
/**MULT_160320_Current Month Receivable の修正 dengfeibing 2016/4/20 add start**/
// 契約状況From:[null]
if (all.equals(dto.getContractConditionFromSearch())) {
dto.setContractConditionFromSearch(null);
}
// 契約状況To:[null]
if (all.equals(dto.getContractConditionToSearch())) {
dto.setContractConditionToSearch(null);
}
/**MULT_160320_Current Month Receivable の修正 dengfeibing 2016/4/20 add end**/
// 免除フラグ
dto.setExemptionFlg(CodeKeyValue.OFF.value());
return dto;
}
/**
* 明細検索処理
*
* @param condDto
* 検索条件Dto
* @return 明細配列
*/
@Override
protected BaseEntity[] search(PagingBaseCondDto condDto) {
// 自分のDtoに変換する
Rcv0001s02Dto dto = (Rcv0001s02Dto) condDto;
// 検索条件をセット
setSelCondition(dto);
Rcv0001s02Dto oldDto = new Rcv0001s02Dto();
Rcv0001s02Entity[] resultList = null;
if (session.getCondDto(session.getLinkInfo().getCurrentPageId()) == null
|| (session.getCondDto(session.getLinkInfo().getCurrentPageId()) != null
&& !RETURN_FLG_YES.equals(session.getCondDto(
session.getLinkInfo().getCurrentPageId()).getReturnFlg()))) {
oldDto = (Rcv0001s02Dto) ClassUtil.copyFields(oldDto, dto);
} else {
oldDto = (Rcv0001s02Dto) session.getCondDto(session.getLinkInfo()
.getCurrentPageId());
}
// 回収ステータス
oldDto.setWithdrawStatus(CodeMstKbn.COLLECTION_STATUS.value());
// 回収種別
oldDto.setWithdrawCasus(CodeMstKbn.BILL_FLG.value());
// 予定回収方法SCHEDULE_WITHDRAW_METHOD
oldDto.setScheduleWithdrawMethod(CodeMstKbn.REAL_COLLECTION_WAY.value());
/*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add start ***/
// 予定回収方法SCHEDULE_WITHDRAW_METHOD
oldDto.setInvoiceType(CodeMstKbn.BILL_TYPE.value());
/*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add end ***/
// 実回収方法REAL_WITHDRAW_METHOD
oldDto.setRealWithdrawMethod(CodeMstKbn.REAL_COLLECTION_WAY.value());
// 回収先区分
oldDto.setRealWithdrawKbn(CodeMstKbn.REAL_WITHDRAW_KBN.value());
// セッションで一覧情報が存在しない場合、検索します
if (oldDto.getRstAllList() == null) {
// 初期検索場合は、DBから一覧情報を取得する
//その他 53,65,97,90,71,76,67,68,69
oldDto.setKbnOtherSearchList(
new String[]{
CodeKeyValue.BILL_DUTY_STAMP.value(),
//CodeKeyValue.BILL_NOTICE_FEE.value(),
CodeKeyValue.BILL_INSURANCE_CTF.value(),
CodeKeyValue.BILL_OTHER.value(),
CodeKeyValue.BILL_BURDEN_INTEREST.value(),
// CodeKeyValue.BILL_ADVANCED_PAYMENT.value(),
CodeKeyValue.BILL_BANK_TRANSFER_FEE_CASHPRICE.value(),
CodeKeyValue.BILL_BANK_TRANSFER_FEE_COMMISSION.value(),
CodeKeyValue.BILL_BANK_TRANSFER_FEE_CAMPAIGN.value(),});
//名義変更手数料 54,55
oldDto.setBillTransferList(
new String[]{
CodeKeyValue.BILL_TRANSFER_OWNERSHIP_GOV.value(),
CodeKeyValue.BILL_TRANSFER_OWNERSHIP_OALT.value()});
/************ weixiumei 20161108 start **********/
//保険料94,95,96
oldDto.setKbnInsuranceSearchList(
new String[]{
CodeKeyValue.BILL_INSURANCE_CO.value(),
CodeKeyValue.BILL_INSURANCE_VO.value(),
CodeKeyValue.BILL_INSURANCE_CS.value()});
//督促手数料('INV', 'TI', 'R')
oldDto.setBillTypeList(new String[]{CodeKeyValue.BILL_TYPE_INVOICE_INV.value(),
CodeKeyValue.BILL_TYPE_INVOICE_TI.value(), CodeKeyValue.BILL_TYPE_INVOICE_R.value()});
// oldDto.setCountryId(Integer.valueOf(CodeKeyValue.LANGUAGE_SIMPLIFIED_THAILAND.value()));
/************ weixiumei 20161108 end **********/
/************ weixiumei 2017/02/03 add start **********/
//('TI', 'R')
oldDto.setBillTypeInvoiceTiR(new String[]{
CodeKeyValue.BILL_TYPE_INVOICE_TI.value(),
CodeKeyValue.BILL_TYPE_INVOICE_R.value()});
/************ weixiumei 2017/02/03 add end **********/
// 未回収
oldDto.setKbnPaidStatusNotRequestSearch0(CodeKeyValue.NOT_WITHDRAWED.value());
// 依頼中
oldDto.setKbnPaidStatusRequest1(CodeKeyValue.WITHDRAWING.value());
// 一部入金
oldDto.setKbnPartWithdrawedSearch2(CodeKeyValue.PART_WITHDRAWED.value());
// 回収済
oldDto.setKbnWithdrawStatusSearch3(CodeKeyValue.WITHDRAWED.value());
// 業務日時
oldDto.setDateTypeTime(DatetimeUtil.currentAppDateTime());
// 免除フラグ
oldDto.setExemptionFlg(CodeKeyValue.EXEMPTION_ON.value());
/**MULT_160320_Current Month Receivable の修正 dengfeibing 2016/4/20 add start**/
// プルダウンリスト中で「null」っだことを判断する
String all = ConfigUtil.commonConfig(CommonConfigKey.SelectAllValue);
// 契約状況From:[null]
if (all.equals(oldDto.getContractConditionFromSearch())) {
oldDto.setContractConditionFromSearch(null);
}
// 契約状況To:[null]
if (all.equals(oldDto.getContractConditionToSearch())) {
oldDto.setContractConditionToSearch(null);
}
/**MULT_160320_Current Month Receivable の修正 dengfeibing 2016/4/20 add end**/
//wanghuan mult1.5 2016.1.12 start
// 業務日付取得
Date dtType = DatetimeUtil.currentAppDateTime();
//wanghuan mult1.5 2016.1.12 end
// OALT STEP1 redmine #322 「Branch」にたいして「空白」検索可能とする modify by hao 20170203 start
List<String> branchSearchListTmp = new ArrayList<String>();
if (StringUtil.isEmpty(oldDto.getBranchSearch())) {
for (DropdownListDto d : session.getLoginInfo().getAplBranchInfoItems()) {
branchSearchListTmp.add(d.getValue());
}
} else {
branchSearchListTmp.add(oldDto.getBranchSearch());
}
oldDto.setBranchSearchList(branchSearchListTmp);
// OALT STEP1 redmine #322 「Branch」にたいして「空白」検索可能とする modify by hao 20170203 end
// 一覧検索する
// resultList = (Rcv0001s02Entity[])ListUtil.pageMaxRowConvert(
// dao.getTransferDataItems(oldDto,
// CommonConstants.PAGING_MAXROW.value()
// //wanghuan mult1.5 2016.1.12 start
// ,dtType
// ));
// //wanghuan mult1.5 2016.1.12 end
resultList = dao.getTransferDataItems(oldDto,
CommonConstants.PAGING_MAXROW.value()
,dtType);
/********weixiumei 20161109 add start ********************/
//パラメータ.単据管理番号 =null
//パラメータ.index =0;
String billManagementNoParam = null;
int index = 0;
List<Rcv0001s02Entity> resultListNoDuplicate = new ArrayList<Rcv0001s02Entity>();
// 毎項目設定する
for (int i = 0; i < resultList.length; i++) {
//IF 抽出したデータ「i」.単据管理番号 <> パラメータ.単据管理番号
if(resultList[i].getBillManagementNo()!=null){
String billType = "";
if(resultList[i].getBillType() != null){
billType = resultList[i].getBillType().replace(" ", "");
}
if(!resultList[i].getBillManagementNo().equals(billManagementNoParam)){
//パラメータ.単据管理番号 = 抽出したデータ「i」.単据管理番号
//パラメータ.index = i ;
billManagementNoParam = resultList[i].getBillManagementNo();
//抽出したデータ「i」.単据管理番号 == 'INV'
if(CodeKeyValue.BILL_TYPE_INVOICE_INV.value().equals(billType)){
//抽出したデータ「パラメータ.index」.Invoice No == 抽出したデータ「i」.単据番号
resultList[i].setInvoiceNo1(resultList[i].getBillNo());
}else if(CodeKeyValue.BILL_TYPE_INVOICE_TI.value().equals(billType)){//抽出したデータ「i」.単据管理番号 == 'TI'
//抽出したデータ「パラメータ.index」.Tax Invoice No == 抽出したデータ「i」.単据番号
resultList[i].setTaxInvoiceNo(resultList[i].getBillNo());
}else if(CodeKeyValue.BILL_TYPE_INVOICE_R.value().equals(billType)){//抽出したデータ「i」.単据管理番号 == 'R'
//抽出したデータ「パラメータ.index」.Receipt No == 抽出したデータ「i」.単据番号
resultList[i].setReceiptNo1(resultList[i].getBillNo());
}
}else{
//抽出したデータ「i」.単据管理番号 == 'INV'
if(CodeKeyValue.BILL_TYPE_INVOICE_INV.value().equals(billType)){
//抽出したデータ「パラメータ.index」.Invoice No ==
//抽出したデータ「i」.単据番号 +”,”+抽出したデータ「パラメータ.index」.Invoice No
if (StringUtil.isEmpty(resultListNoDuplicate.get(index-1).getInvoiceNo1())){
resultListNoDuplicate.get(index-1).setInvoiceNo1( resultList[i].getBillNo());
}else{
resultListNoDuplicate.get(index-1).setInvoiceNo1(resultListNoDuplicate.get(index-1).getInvoiceNo1() +
STR_MARK + resultList[i].getBillNo());
}
}else if(CodeKeyValue.BILL_TYPE_INVOICE_TI.value().equals(billType)){//抽出したデータ「i」.単据管理番号 == 'TI'
//抽出したデータ「パラメータ.index」.Tax Invoice No
//== 抽出したデータ「i」.単据番号 +””+ 抽出したデータ「パラメータ.index」.Tax Invoice No
if (StringUtil.isEmpty(resultListNoDuplicate.get(index-1).getTaxInvoiceNo())){
resultListNoDuplicate.get(index-1).setTaxInvoiceNo(resultList[i].getBillNo());
}else{
resultListNoDuplicate.get(index-1).setTaxInvoiceNo(resultListNoDuplicate.get(index-1).getTaxInvoiceNo() +
STR_MARK + resultList[i].getBillNo());
}
}else if(CodeKeyValue.BILL_TYPE_INVOICE_R.value().equals(billType)){//抽出したデータ「i」.単据管理番号 == 'R'
//抽出したデータ「パラメータ.index」.Receipt No
//== 抽出したデータ「i」.単据番号 +”,”+ 抽出したデータ「パラメータ.index」.Receipt No
if (StringUtil.isEmpty(resultListNoDuplicate.get(index-1).getReceiptNo1())){
resultListNoDuplicate.get(index-1).setReceiptNo1(resultList[i].getBillNo());
}else{
resultListNoDuplicate.get(index-1).setReceiptNo1(resultListNoDuplicate.get(index-1).getReceiptNo1() +
STR_MARK + resultList[i].getBillNo());
}
}
continue;
}
}
resultListNoDuplicate.add(resultList[i]);
index++;
}
resultList = (Rcv0001s02Entity[])resultListNoDuplicate.toArray(new Rcv0001s02Entity[resultListNoDuplicate.size()]);;
//TODO
resultList = (Rcv0001s02Entity[])ListUtil.pageMaxRowConvert(resultList);
/********weixiumei 20161109 add end ********************/
for (int i = 0; i < resultList.length; i++) {
resultList[i].setIndex(i);
// 回数-回数連番
if (resultList[i].getCouponSeq() != null) {
resultList[i].setLblLine(STR_LINE);
}
// 【 延滞開始日~延滞終了日(延滞日数)】
if (resultList[i].getDelayedStartDate() != null) {
resultList[i].setDelayDateDsp(StringUtil.formatDate(
resultList[i].getDelayedStartDate(),
StringFormatType.DATE_FORMAT_MM_DD)
+ TILDE
+ StringUtil.formatDate(resultList[i]
.getDelayedAccountDate(),
StringFormatType.DATE_FORMAT_MM_DD));
// (延滞日数)
resultList[i].setDelayDays(BRACKET_LEFT
+ resultList[i].getDelayedDays().toString()
+ BRACKET_RIGHT);
}
// 回収済/已回收:
resultList[i].setCountWithdrawResultAmount(resultList[i].getWithdrawResultAmount());
if (resultList[i].getWithdrawResultAmount() != null
&& ConverterUtil.convertToInt(resultList[i].getWithdrawResultAmount()) > 0
&& !resultList[i].getWithdrawStatus().equals(
CodeKeyValue.WITHDRAWED.value())) {
resultList[i].setWithdrawresultText(DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, STR_WITHDRAW_CODE, dto.getCountryId())
+ COLON
+ StringUtil.formatNumber(resultList[i]
.getWithdrawResultAmount(),
StringFormatType.NUMBER_FORMAT_MONEY));
} else if (resultList[i].getWithdrawStatus().equals(
CodeKeyValue.WITHDRAWED.value())) {
resultList[i].setCountWithdrawResultAmount(resultList[i]
.getWithdrawResultAmount());
} else {
resultList[i]
.setCountWithdrawResultAmount(BigDecimalConversionUtil
.toBigDecimal(0));
}
// 物件名称
if (resultList[i].getWithdrawCasus().equals(
CodeKeyValue.BILL_SUPPLIES_DISPOSAL.value())) {
resultList[i].setSuppliesName(BRACKET_LEFT
+ resultList[i].getSuppliesName() + BRACKET_RIGHT);
}
resultList[i].setDetailKey(resultList[i].getContractNo() + STR_MARK + resultList[i].getWithdrawCasus() + STR_MARK + resultList[i].getCoupon());
}
// 初回検索結果を格納する
oldDto.setRstAllList(resultList);
// 総件数をセットする。
oldDto.setCount(resultList.length);
// 初期化ページ情報
dto.setCount(resultList.length);
if (!PagingBaseLogicImpl.RETURN_FLG_YES.equals(dto.getReturnFlg())) {
dto.setCurrentIndex(0);
dto.setCurrentPage(1);
} else {
dto.setCurrentIndex(dto.getCurrentPage() - 1);
}
dto.setHdnPageAllCnt(resultList.length);
dto.setRstAllList(resultList);
} else {
// セッションから検索結果を取得する
resultList = (Rcv0001s02Entity[]) oldDto.getRstAllList();
}
// (計XX件)
dto.setAllCntShow(ConfigUtil.getConstantsValue(
MessageParamConst.ALL_CNT_TITLE, String.valueOf(oldDto.getCount())));
// //////////////////////すべてレコードを取得し、画面でページ制御処理//////////////////////////
// 当ページの最大レコード順番を計算する
int recMaxPos = 0;
int offset = dto.getCurrentIndex() * dto.getPageMaxCount();
if (resultList.length >= (dto.getCurrentIndex() + 1) * dto.getPageMaxCount()) {
recMaxPos = (dto.getCurrentIndex() + 1) * dto.getPageMaxCount();
} else {
recMaxPos = resultList.length;
}
// 当ページの明細初期化
Rcv0001s02Entity[] resultPageList = new Rcv0001s02Entity[recMaxPos
- offset];
// 画面明細可視性属性のセット
for (int i = offset; i < recMaxPos; i++) {
resultPageList[i - offset] = new Rcv0001s02Entity();
// 当ページの明細内容をセットする
ClassUtil.copyFields(resultPageList[i - offset], resultList[i]);
}
// ////////////////////////////////////////////////////////////////////////////////
// 当画面の明細をセット
dto.setTransferDataItems(resultPageList);
// 検索結果を戻る
return dto.getTransferDataItems();
}
/**
* 書類作成&口座引落ファイル作成処理
*
* @param dto
* 引落予定一覧Dto
* @return 引落予定一覧Dto
*/
public Rcv0001s02Dto doFileCreateCheck(Rcv0001s02Dto dto) {
// 案件情報取得
CaseMstEntity caseMstEntity = caseNodao.selectById(dto
.getCaseDivionSearch());
// リース料・延滞利息回収順番
String withdrawNo = null;
if (null != caseMstEntity) {
// リース料・延滞利息回収順番設定
withdrawNo = caseMstEntity.getLeaseDelayInterestReteWithdrawNo();
// 案件情報.案件略称設定
dto.setCasesNameAbr(caseMstEntity.getCasesNameAbr());
}
// チェックフラグ初期化
Boolean checkFlg = false;
// 契約番号Flg
Boolean contractNoCheckflg = false;
// ワーニングメッセージフラグ--WRCV0005
Boolean warn05Flg = false;
// ワーニングメッセージリスト
StringBuffer warnMessageList = new StringBuffer();
// ワーニングメッセージ(temp)
StringBuffer tempList = new StringBuffer();
// ワーニングメッセージ(tempWarn)
StringBuffer tempWarn = new StringBuffer();
// セッション情報取得
Rcv0001s02Dto condDto = (Rcv0001s02Dto) session.getCondDto(session
.getLinkInfo().getCurrentPageId());
// セッションから検索結果を取得
Rcv0001s02Entity[] resultList = (Rcv0001s02Entity[]) condDto
.getRstAllList();
// 選択項目判断
tempWarn = new StringBuffer();
contractNoCheckflg = false;
for (int j = 0; j < resultList.length; j++) {
// チェックしているチェックボックス
if (CHECK_ON.equals(resultList[j].getSelectedCheck())) {
checkFlg = true;
contractNoCheckflg = true;
// 回収ステータスが依頼中のレコードが一件でも存在する場合
if (CodeKeyValue.WITHDRAWING.value().equals(
resultList[j].getWithdrawStatus())
&& !warn05Flg) {
// WRCV0005
warn05Flg = true;
}
}
// 案件属性マスタ.リース料・延滞利息回収順番 = リース料先にに の場合
if (CodeKeyValue.LEASE_DELAY_WITHDRAW_SORT_LEASE.value()
.equals(withdrawNo)) {
// 契約ごとに、延滞利息を選択する場合
if (CHECK_ON
.equals(resultList[j].getSelectedCheck())
&& CodeKeyValue.BILL_DELAYED.value().equals(
resultList[j].getCodeId())) {
// リース料を選択しない項目の存在をチェックする
for (int k = 0; k < resultList.length; k++) {
// リース料を選択しない項目の存在する場合
if (!CHECK_ON.equals(resultList[k]
.getSelectedCheck())
&& CodeKeyValue.BILL_LEASE.value().equals(
resultList[k].getCodeId())
&& resultList[j].getCoupon().compareTo(
resultList[k].getCoupon()) == 0) {
// WRCV0015
tempWarn
.append(ConfigUtil
.getMessage(
MessageID.WRCV0015,
resultList[j].getContractNo(),
ConfigUtil
.getConstantsValue(MessageParamConst.DELAYED),
ConfigUtil
.getConstantsValue(MessageParamConst.LEASE_FEE)));
tempWarn.append(MESSAGE_LINE);
}
}
}
// 案件属性マスタ.リース料・延滞利息回収順番 = 延滞利息先に の場合
} else if (CodeKeyValue.LEASE_DELAY_WITHDRAW_SORT_DELAY.value()
.equals(withdrawNo)) {
// 契約ごとに、リース料を選択する場合
if (CHECK_ON
.equals(resultList[j].getSelectedCheck())
&& CodeKeyValue.BILL_LEASE.value().equals(
resultList[j].getCodeId())) {
// 延滞利息を選択しない項目の存在をチェックする
for (int k = 0; k < resultList.length; k++) {
// 延滞利息を選択しない項目の存在する場合
if (!CHECK_ON.equals(resultList[k]
.getSelectedCheck())
&& CodeKeyValue.BILL_DELAYED.value().equals(
resultList[k].getCodeId())
&& resultList[j].getCoupon().compareTo(
resultList[k].getCoupon()) == 0) {
// WRCV0015
tempWarn
.append(ConfigUtil
.getMessage(
MessageID.WRCV0015,
resultList[j].getContractNo(),
ConfigUtil
.getConstantsValue(MessageParamConst.LEASE_FEE),
ConfigUtil
.getConstantsValue(MessageParamConst.DELAYED)));
tempWarn.append(MESSAGE_LINE);
}
}
}
}
//}
// ワーニングメッセージ(temp)
if (contractNoCheckflg) {
tempList.append(tempWarn);
}
}
// チェックしているチェックボックスが存在しない場合
if (!checkFlg) {
// エラー出力
throw new PromoteMessageException(false, MessageID.ERCV0002);
}
// ワーニングメッセージ--WRCV0005
if (warn05Flg) {
warnMessageList.append(ConfigUtil.getMessage(MessageID.WRCV0005));
warnMessageList.append(MESSAGE_LINE);
}
// ワーニングメッセージリスト設定
dto.setWarnMessageList(warnMessageList.append(tempList));
return dto;
}
/**
* 対象データワークテーブル削除&追加
*
* @param dto
* 引落予定一覧Dto
* @param processFlag
* 処理区分 0:請求書出力 1:催告書出力 2:引落ファイル 3:未回収状況 4:引落依頼取消 5:Tax Invoice/Receipt
* @return 新規件数
*/
public int targetWorkTableFunction(Rcv0001s02Dto dto, int processFlag) {
// 新規件数
int updateNum = 0;
// 删除当前sessionId既成的记录
DataObjectWorktableEntity[] dataObjectWorktableEntityList
= this.dataObjectWorktableDao.selectBySessionId(session.getSessionId());
// dataObjectWorktableDao.deleteBatch(dataObjectWorktableEntityList);
// セッション情報取得
Rcv0001s02Dto condDto = (Rcv0001s02Dto) session.getCondDto(session
.getLinkInfo().getCurrentPageId());
Rcv0001s02Entity[] resultList = (Rcv0001s02Entity[]) condDto
.getRstAllList();
boolean insertFlag = false;
// 登録処理
// 請求書出力の場合
if (processFlag == 0) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
// 回収状況 = 回収済以外 且つ 請求書出力要否 = 要 且つ 回収方法 = GIRO以外
/***********【TFS向け仕様追加・変更対応】 zhou update start 2013/01/07**************/
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
// // 契約状況
// int contractCondition = 0;
// if (!StringUtil.isEmpty(resultList[i].getContractCondition())) {
// contractCondition = Integer.parseInt(resultList[i].getContractCondition());
// }
// // 契約状況区分 034:31.開始済
// int alreadyStarted = Integer.parseInt(CodeKeyValue.ALREADY_STARTED.value());
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
if (
// ((CodeKeyValue.BILL_LEASE.value().equals(
// resultList[i].getWithdrawCasus())
//
// /***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/26**************/
// //&& resultList[i].getCoupon() > 0
// && (resultList[i].getCoupon() == 0 || contractCondition >= alreadyStarted)
// )
// //******* LAMP Step2向け対応 by tangzhiming 2013/04/15 start *********/
//// || CodeKeyValue.BILL_DEPOSIT.value().equals(
//// resultList[i].getWithdrawCasus())
//// /***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/26**************/
//// || CodeKeyValue.BILL_DELAYED.value().equals(
//// resultList[i].getWithdrawCasus())
//// || CodeKeyValue.BILL_EXPIRY_OPTIONS
//// .value().equals(resultList[i].getWithdrawCasus())
// || !CodeKeyValue.BILL_LEASE.value().equals(
// resultList[i].getWithdrawCasus())
// || (CodeKeyValue.BILL_LEASE.value().equals(resultList[i].getWithdrawCasus())
// && resultList[i].getCoupon() > 0)
// //******* LAMP Step2向け対応 by tangzhiming 2013/04/15 end *********/
// )
// &&
!CodeKeyValue.WITHDRAWED.value().equals(
resultList[i].getWithdrawStatus())
// && CodeKeyValue.IS_APPLY_BOOK_CREATE_ON.value().equals(
// resultList[i].getRequestFileOutput())
/*&& !CodeKeyValue.REAL_SDAPPROPRIATE.value().equals(
resultList[i].getScheduleWithdrawMethod())*/) {
/***********【TFS向け仕様追加・変更対応】 zhou update end 2013/01/07****************/
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1007);
}
// 催告書出力の場合
} else if (processFlag == 1) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
// 回収状況 = 回収済以外 且つ 回収方法:GIRO以外
if (!CodeKeyValue.WITHDRAWED.value().equals(
resultList[i].getWithdrawStatus())
/***********【TFS向け仕様追加・変更対応】 caowei add 2012/1/6 start******************/
//&& !CodeKeyValue.COLLECTION_WAY_GIRO.value().equals(
&& !CodeKeyValue.REAL_SDAPPROPRIATE.value().equals(
/***********【TFS向け仕様追加・変更対応】 caowei add 2012/1/6 end********************/
resultList[i].getScheduleWithdrawMethod())) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1008);
}
// 引落ファイル
} else if (processFlag == 2) {
for (int i = 0; i < resultList.length; i++) {
// 銀行区分
String bankDiv = AccountUtil.getBankKbn(resultList[i]
.getScheduleWithdrawAccountNo());
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
// 契約状況
int contractCondition = 0;
if (!StringUtil.isEmpty(resultList[i].getContractCondition())) {
contractCondition = Integer.parseInt(resultList[i].getContractCondition());
}
// 契約状況区分 034:31.開始済
int alreadyStarted = Integer.parseInt(CodeKeyValue.ALREADY_STARTED.value());
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
if (((CodeKeyValue.BILL_LEASE.value().equals(
resultList[i].getWithdrawCasus())
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
//&& resultList[i].getCoupon() > 0
&& (resultList[i].getCoupon() == 0 || contractCondition >= alreadyStarted)
)
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
|| CodeKeyValue.BILL_DELAYED.value().equals(
resultList[i].getWithdrawCasus())
|| CodeKeyValue.BILL_EXPIRY_OPTIONS
.value().equals(resultList[i].getWithdrawCasus()))
&& !CodeKeyValue.WITHDRAWED.value().equals(
resultList[i].getWithdrawStatus())
&& CodeKeyValue.REAL_WITHDRAWAL.value().equals(
resultList[i].getScheduleWithdrawMethod())
&& (CodeKeyValue.BANK_DIV_NONGYE.value().equals(bankDiv)
|| CodeKeyValue.BANK_DIV_KOUSYOU.value().equals(bankDiv))) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1009);
}
// 未回収状況
} else if (processFlag == 3) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
if (CodeKeyValue.BILL_LEASE.value().equals(
resultList[i].getWithdrawCasus())
&& !CodeKeyValue.WITHDRAWED.value().equals(
resultList[i].getWithdrawStatus())
&& !StringUtil.isEmpty(resultList[i].getDelayedNo())) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1010);
}
// 依頼取消
} else if (processFlag == 4) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
// 契約状況
int contractCondition = 0;
if (!StringUtil.isEmpty(resultList[i].getContractCondition())) {
contractCondition = Integer.parseInt(resultList[i].getContractCondition());
}
// 契約状況区分 034:31.開始済
int alreadyStarted = Integer.parseInt(CodeKeyValue.ALREADY_STARTED.value());
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
if (((CodeKeyValue.BILL_LEASE.value().equals(resultList[i].getWithdrawCasus())
/***********【TFS2.0向け仕様追加・変更対応】 caowei update start 2013/03/27**************/
// && resultList[i].getCoupon() > 0
&& (resultList[i].getCoupon() == 0 || contractCondition >= alreadyStarted)
)
/***********【TFS2.0向け仕様追加・変更対応】 caowei update end 2013/03/27**************/
|| CodeKeyValue.BILL_DELAYED.value().equals(
resultList[i].getWithdrawCasus())
|| CodeKeyValue.BILL_EXPIRY_OPTIONS.value().
equals(resultList[i].getWithdrawCasus()))
&& CodeKeyValue.WITHDRAWING.value().equals(
resultList[i].getWithdrawStatus())) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回収種別
if (resultList[i].getWithdrawCasus() != null) {
dataObjectWorktableEntity.setCouponSeq(Integer
.parseInt(resultList[i].getWithdrawCasus()));
}
// 回数
if (resultList[i].getCoupon() != null) {
dataObjectWorktableEntity.setCoupon(Integer
.valueOf(resultList[i].getCoupon()));
}
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
// 入金小分類
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV1006);
}
// OALT STEP1 20161201 modify by カク start
// Tax Invoice/Receipt
} else if (processFlag == 5) {
for (int i = 0; i < resultList.length; i++) {
// 選択した項目
if (CHECK_ON.equals(resultList[i].getSelectedCheck())) {
insertFlag = true;
// 添加到Worktable中.
DataObjectWorktableEntity dataObjectWorktableEntity
= new DataObjectWorktableEntity();
// 該当セッションID
dataObjectWorktableEntity.setSessionId(session.getSessionId());
// 回収種別
dataObjectWorktableEntity
.setWithdrawCasus(resultList[i].getWithdrawCasus());
// 契約番号
dataObjectWorktableEntity.setContractNo(resultList[i]
.getContractNo());
// 物件番号
dataObjectWorktableEntity.setSuppliesNo(resultList[i].getSuppliesNo());
// 回数
dataObjectWorktableEntity.setCoupon(resultList[i].getCoupon());
// 回数連番
dataObjectWorktableEntity.setCouponSeq(resultList[i].getCouponSeq());
this.dataObjectWorktableDao.insert(dataObjectWorktableEntity);
updateNum++;
}
}
if (!insertFlag) {
throw new PromoteMessageException(false, MessageID.ERCV0068);
}
}
// OALT STEP1 20161201 modify by カク end
return updateNum;
}
/**
* 口座ファイル一括作成管理テーブルにデータを追加処理
*
* @param dto
* 引落予定一覧Dto
* @param fileName
* ZIPファイルのファイル名
* @param realWithdrawScheduleDate
* 実回収予定日
* @param businessDate
* 業務日付
* @param withdrawKbn
* 回収区分
* @return 更新件数
*/
public int doBundleCreateHistoryInsert(Rcv0001s02Dto dto, String fileName,
Date realWithdrawScheduleDate, Date businessDate, String withdrawKbn) {
// 作成ファイルパス
String filePath = ConfigUtil
.commonConfig(CommonConfigKey.RequestOutPutPath);
// 更新対象
BundleCreateHistoryEntity insertEntity = new BundleCreateHistoryEntity();
// 案件番号
insertEntity.setCaseNo(dto.getCaseDivionSearch());
/*** zlw 2013/12/23 add start ***/
// 拠点
insertEntity.setBranchCode(dto.getBranchSearch());
/*** zlw 2013/12/23 add end ***/
// 請求処理区分
insertEntity
.setRequestKbn(CodeKeyValue.REQUEST_KBN_SINGLE_WITHDRAWAL_FILE
.value());
// 一括実施日時
insertEntity.setBundleTime(DatetimeUtil.dateToTimestamp(businessDate));
// 処理ステータス
insertEntity.setBundleStatus(CodeKeyValue.SUM_UP_STATUS_COMPLETE
.value());
// 作成ファイルパス
insertEntity.setFilePath(filePath);
// 作成ファイル名
insertEntity.setFileName(fileName);
// 画面.回収予定日FROM
insertEntity.setWithdrawScheduleDateFrom(DatetimeUtil.dateToSQLDate(dto
.getApplyDateFromSearch()));
// 画面.回収予定日TO
insertEntity.setWithdrawScheduleDateTo(DatetimeUtil.dateToSQLDate(dto
.getApplyDateToSearch()));
return bundleCreateHistoryDao.insert(insertEntity);
}
/**
* 依頼取消処理
*
* @param dto
* 引落予定一覧Dto
* @param updateNum
* updateNum
* @return 引落予定一覧Dto
*/
public Rcv0001s02Dto doRequestCancellation(Rcv0001s02Dto dto, int updateNum) {
// セッション情報取得
Rcv0001s02Dto condDto = (Rcv0001s02Dto) session.getCondDto(session
.getLinkInfo().getCurrentPageId());
// セッションから検索結果を取得
Rcv0001s02Entity[] resultList = (Rcv0001s02Entity[]) condDto
.getRstAllList();
// 操作ログエンティティ リスト
List < LogHistoryEntity > logHistoryList =
new ArrayList < LogHistoryEntity > ();
// 業務日時取得
Date businessDate = DatetimeUtil.currentAppDateTime();
// 選択し対象を操作ログテーブルにデータを追加する
for (int i = 0; i < resultList.length; i++) {
// チェックしているチェックボックス
if (CHECK_ON.equals(resultList[i]
.getSelectedCheck())) {
// ログを新規する
LogHistoryEntity logHistoryEntity = new LogHistoryEntity();
// 操作日付 = 業務日時
logHistoryEntity.setOperationTime(DatetimeUtil
.dateToTimestamp(businessDate));
// ログタイプ = 1:作業ログ
logHistoryEntity.setLogType(CodeKeyValue.LOG_BUSNESS.value());
// ユーザーID = ユーザーID
logHistoryEntity.setUserId(session.getLoginInfo().getUserId());
// 部門ID = システムに登録したユーザーの部門ID
logHistoryEntity.setDeptId(session.getLoginInfo().getDeptId());
// ログのコメント:選択した契約番号+"_"+回数+"_"+回数連番+"_"+備考(備考 = "依頼取消")
logHistoryEntity.setComment(resultList[i].getContractNo() + UNDERLINE
+ String.valueOf(resultList[i].getCoupon()) + UNDERLINE
+ String.valueOf(resultList[i].getCouponSeq()) + UNDERLINE
+ ConfigUtil.getConstantsValue(MessageParamConst.REQUEST_CANCEL
.value()));
// ログロストに追加する
logHistoryList.add(logHistoryEntity);
}
}
// 操作ログテーブルにデータを一括追加する
// ログのコメント:ワークテーブルの契約番号+"_"+回数+"_"+回数連番+"_"+備考
doInsertLogBatch(logHistoryList);
// DB更新を行う
// 当月請求テーブルに対応するレコードを削除する
dao.deleteMonthData();
// 引落予定更新 Dto
Rcv0001s02UpdateDto updateDto = new Rcv0001s02UpdateDto();
// 回収ステータス 0:"未回収"を設定する
updateDto.setWithdrawStatusNo(CodeKeyValue.NOT_WITHDRAWED.value());
// 回収ステータス 2:"一部入金"を設定する
updateDto.setWithdrawStatusPart(CodeKeyValue.PART_WITHDRAWED.value());
// セッションIDを設定する
updateDto.setSessionId(session.getSessionId());
// 回収種別:10:リース料を設定する
updateDto.setWithdrawCasus(CodeKeyValue.BILL_LEASE.value());
// 新規者/更新者を設定する
updateDto.setModifyUser(session.getLoginInfo().getUserId());
// 新規日付/更新日付を設定する
updateDto.setModifyDate(DatetimeUtil.dateToTimestamp(businessDate));
// 排他日時
updateDto.setLastModifyDate(dto.getLastModifyDate());
// 請求書作成フラグを設定する
updateDto.setRequstFileCreatFlgOff(CodeKeyValue.REQUST_FILE_CREAT_FLG_OFF
.value());
// 請求回収情報に対応するレコード更新
int requestNum = dao.updateRequstWithdrawInfo(updateDto);
// 回収種別:20:延滞利息を設定する
updateDto.setWithdrawCasus(CodeKeyValue.BILL_DELAYED.value());
// 延滞情報に対応するレコード更新
int delayNum = dao.updateDelayedInfo(updateDto);
// 回収種別:50:満了時オプション売却金を設定する
updateDto.setWithdrawCasus(CodeKeyValue.BILL_EXPIRY_OPTIONS.value());
// 満了オプション買取金
int buyOptNum = dao.updateBuyOptionWhithdrawInfo(updateDto);
// 請求回収情報に更新した件数 + 延滞情報に更新した件数 <> 対象件数 の場合
if (updateNum != requestNum + delayNum + buyOptNum) {
throw new PromoteMessageException(false, MessageID.ERCV0019);
}
return dto;
}
/**
* 操作ログテーブルにデータを一括追加する
*
* @param logHistoryList
* 操作ログ エンティティ リスト
*/
private void doInsertLogBatch(List < LogHistoryEntity > logHistoryList) {
// アレイを定義する
LogHistoryEntity[] logHistoryEntities = new LogHistoryEntity[logHistoryList
.size()];
// リストをアレイに転換する
logHistoryList.toArray(logHistoryEntities);
// DBに追加する
logHistoryDao.insertBatch(logHistoryEntities);
}
/**
* EXCEL出力処理
*
* @param dto
* 引落予定一覧Dto
* @return 引落予定一覧Dto
*/
public Rcv0001s02Dto doExcel(Rcv0001s02Dto dto) {
// EXCELファイル
String fileName = "";
// SheetData
SheetData sheetData = null;
// List作成
List < SheetData > dataList = new ArrayList < SheetData > ();
// EXCEL対応内容
Workbook workBook = null;
// HashMap作成
Map < StringParam, String > paramMap = new HashMap < StringParam, String > ();
// ログインユーザID
String userId = null;
// 業務日時
String date = null;
// SheetData作成
sheetData = createTransferSheet(dto);
// Listにデータセット
dataList.add(sheetData);
// EXCELファイル内容作成
workBook = ExcelSheetUtil
.fillData(TemplateConfigKey.rcv0001r16, dataList);
// 支払種別に従って、該当種別の一括支払申請書を作成する。
// ログインユーザID
userId = session.getLoginInfo().getUserId();
// 業務日時
date = StringUtil.formatDate(DatetimeUtil.currentAppDateTime(),
StringFormatType.DATE_FORMAT_YYYYMMDDHHMMSS);
// HashMapセット
paramMap.put(StringParam.TEMPLATE_FILE_USER, userId);
paramMap.put(StringParam.TEMPLATE_FILE_DATETIME, date);
// EXCELファイル名取得
fileName = ConfigUtil.generateXLSFileName(TemplateConfigKey.rcv0001r16,
paramMap);
// EXCEL内容セット
dto.setWorkBook(workBook);
// EXCELファイル名セット
dto.setFileName(fileName);
// 返回DTO
return dto;
}
/**
* 請求回収一覧sheet
*
* @param dto
* 請求回収一覧Dto
* @return 請求回収一覧SheetData
*/
private SheetData createTransferSheet(Rcv0001s02Dto dto) {
// 通貨情報を全取得する
CurrencyMstEntity[] currencyInfo = currencyMstDao.selectAll();
// 通貨マップを定義する
Map < String, String > currencyMap = new HashMap < String, String > ();
// 通貨情報を繰り返す
for (CurrencyMstEntity cur : currencyInfo) {
// マップを設定
currencyMap.put(cur.getCurrencyId(), cur.getCurrencySign());
}
// SheetData
SheetData sheetData = new SheetData(ConfigUtil
.getConstantsValue(MessageParamConst.TRANSFER_SCHEDULE_SHEET_NAME),
EXECL_CONFIG_NAME);
// セッション情報取得
Rcv0001s02Dto condDto = (Rcv0001s02Dto) session.getCondDto(session
.getLinkInfo().getCurrentPageId());
// セッションから検索結果を取得
Rcv0001s02Entity[] resultList = (Rcv0001s02Entity[]) condDto
.getRstAllList();
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/02/18 start******************/
/**** Lease产品化-课题及改善内容 redmine#3553 kuangweijun modify 2015/08/28 start ****/
// 英国のカントリーIDを取得
Integer countryBritainId = ConfigUtil.getCountryId(Locale.ENGLISH);
// // 中国のカントリーIDを取得
// Integer countryBritainId = ConfigUtil.getCountryId(Locale.CHINA);
/**** Lease产品化-课题及改善内容 redmine#3553 kuangweijun modify 2015/08/28 end ****/
// LAMP製品化対応 zlw add start
// OALT STEP1 redmine #322 「Branch」にたいして「空白」検索可能とする modify by hao 20170203 start
if (StringUtil.isEmpty(dto.getBranchSearch())) {
sheetData.addData(EXECL_BRANCHNAME, null);
} else {
// 国ID
String countryId = ConfigUtil.getCountryId(session.getLoginInfo().getLocale()).toString();
BranchMstEntity branchMstEntity = branchMstDao.getSiteName(dto.getBranchSearch(), countryId);
sheetData.addData(EXECL_BRANCHNAME, branchMstEntity.getBranchName());
}
// OALT STEP1 redmine #322 「Branch」にたいして「空白」検索可能とする modify by hao 20170203 end
// LAMP製品化対応 zlw add end
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/02/18 end******************/
// LAMP製品化対応 redmine#48 hxh add start
// 契約状況From
String contractConditionFromSearch = DropdownListUtil.getCodeNameByCode(CodeMstKbn.CONTACT_STATUS_KBN, dto.getContractConditionFromSearch());
// 契約状況To
String contractConditionToSearch = DropdownListUtil.getCodeNameByCode(CodeMstKbn.CONTACT_STATUS_KBN, dto.getContractConditionToSearch());
// 契約状況
String contractConditionSearch = "";
// 契約状況From != null || 契約状況To != nullの場合、契約状況の中で「~」を追加すること。
if(!(contractConditionFromSearch.equals("") && contractConditionToSearch.equals(""))){
contractConditionSearch = contractConditionFromSearch + TILDE + contractConditionToSearch;
}
sheetData.addData(EXECL_CONTRACTSTATUS, contractConditionSearch);
// LAMP製品化対応 redmine#48 hxh add end
// 案件名称
sheetData.addData(EXECL_CASENO, DropdownListUtil.getCodeNameByCode(
CodeMstKbn.CASE_ATTR, condDto.getCaseDivionSearch(),
countryBritainId));
// 売主
sheetData.addData(AGENCYNAME, condDto.getAgencyNameSearch());
// 出力日時
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
/*sheetData.addData(SYSDATETIME, DatetimeUtil.dateToTimestamp(DatetimeUtil
.currentAppDate()));*/
sheetData.addData(SYSDATETIME, StringUtil.formatDate(DatetimeUtil
.currentAppDateTime(),
StringFormatType.DATE_FORMAT_YYYY_M_D));
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
// 契約番号
sheetData.addData(CONTRACTNO, condDto.getContractNoForSearch());
// 顧客
sheetData.addData(CUSTOMERNAME, condDto.getCustNameSearch());
// 回収方法モード
sheetData.addData(METHODMODE, DropdownListUtil.getCodeNameByCode(
CodeMstKbn.SEARCH_MODE, dto.getSchedulRealModelWay(),
countryBritainId));
// 回収方法
sheetData.addData(SCHEDULEWITHDRAWMETHODNAME, DropdownListUtil
.getCodeNameByCode(CodeMstKbn.REAL_COLLECTION_WAY, dto
.getRealCollectionWay(), countryBritainId));
// 回収日
if (condDto.getApplyDateToSearch() != null
&& condDto.getApplyDateFromSearch() != null) {
sheetData.addData(RECYCLEDATE, StringUtil.formatDate(condDto
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
// .getApplyDateFromSearch(), StringFormatType.DATE_FORMAT_DDMMMYYYY)
.getApplyDateFromSearch(), StringFormatType.DATE_FORMAT_YYYY_M_D)
+ TILDE + StringUtil.formatDate(condDto.getApplyDateToSearch(),
// StringFormatType.DATE_FORMAT_DDMMMYYYY));
StringFormatType.DATE_FORMAT_YYYY_M_D));
} else if (condDto.getApplyDateFromSearch() != null) {
sheetData.addData(RECYCLEDATE, StringUtil.formatDate(condDto
.getApplyDateFromSearch(),
// StringFormatType.DATE_FORMAT_DDMMMYYYY));
StringFormatType.DATE_FORMAT_YYYY_M_D));
} else if (condDto.getApplyDateToSearch() != null) {
sheetData.addData(RECYCLEDATE, TILDE
+ StringUtil.formatDate(condDto.getApplyDateToSearch(),
// StringFormatType.DATE_FORMAT_DDMMMYYYY));
StringFormatType.DATE_FORMAT_YYYY_M_D));
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
}
// 回収日モード
sheetData.addData(DATEMODE, DropdownListUtil.getCodeNameByCode(
CodeMstKbn.SEARCH_MODE, dto.getSchedulRealModelDay(),
countryBritainId));
// 遅延
sheetData.addData(DELAYEDDATE, condDto.getDelayedDateSearch());
// 回収銀行
sheetData.addData(BANK, condDto.getBankBranchNameCon());
// 回収銀行モード
sheetData.addData(BANKMODE, DropdownListUtil.getCodeNameByCode(
CodeMstKbn.SEARCH_MODE, dto.getSchedulRealModelBank(),
countryBritainId));
// 回収種別
String collectionType = "";
// リース料
if (CHECK_ON.equals(condDto.getKbnLeaseAmountSearch())) {
collectionType = DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_LEASE.value(), countryBritainId);
}
// 延滞利息
if (CHECK_ON.equals(condDto.getKbnDelayAmountSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_DELAYED.value(), countryBritainId);
}
// 解約損害金
if (CHECK_ON.equals(condDto.getKbnContractCancellationSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_END_AGREEMENT.value(), countryBritainId);
}
// 物件処分金
if (CHECK_ON.equals(condDto.getKbnThingMoneySearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_SUPPLIES_DISPOSAL.value(), countryBritainId);
}
// 満了買取金
if (CHECK_ON.equals(condDto.getKbnAcceptanceDateSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_EXPIRY_OPTIONS.value(), countryBritainId);
}
// 保証金
if (CHECK_ON.equals(condDto.getKbnDepositSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_DEPOSIT.value(), countryBritainId);
}
// 管理費
if (CHECK_ON.equals(condDto.getKbnAdministrationFeeSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_ADMINISTRATION_FEE.value(), countryBritainId);
}
// 前渡金利息
if (CHECK_ON.equals(condDto.getKbnAdvancedPaymentInterestSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_ADVANCED_PAYMENT_INTEREST.value(),
countryBritainId);
}
// 据置利息
if (CHECK_ON.equals(condDto.getKbnGracePeriodInterestSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_GRACE_PERIOD_INTEREST.value(),
countryBritainId);
}
// その他
if (CHECK_ON.equals(condDto.getKbnOtherSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_OTHER.value(), countryBritainId);
}
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun add 2013/05/16 start********************/
// 保証金(元本)
if (CHECK_ON.equals(condDto.getKbnGuaranteeDepositSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_GUARANTEE_DEPOSIT.value(), countryBritainId);
}
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun add 2013/05/16 end ********************/
// 前受利息
if (CHECK_ON.equals(condDto.getKbnPrepaidInterestSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_PREPAID_INTEREST.value(), countryBritainId);
}
// 繰上返済金
if (CHECK_ON.equals(condDto.getKbnPrepaymentSearch())) {
if (!collectionType.equals("")) {
collectionType = collectionType + STR_MARK;
}
collectionType += DropdownListUtil.getCodeNameByCode(CodeMstKbn.BILL_FLG,
CodeKeyValue.BILL_PREPAYMENT.value(), countryBritainId);
}
sheetData.addData(COLLCTIONTYPE, collectionType);
// 回収状況
String collctionStatus = "";
// 未回収
if (CHECK_ON.equals(condDto.getKbnPaidStatusNotRequestSearch())) {
collctionStatus = DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, CodeKeyValue.NOT_WITHDRAWED
.value(), countryBritainId);
}
// 依頼中
if (CHECK_ON.equals(condDto.getKbnPaidStatusRequest())) {
if (!collctionStatus.equals("")) {
collctionStatus = collctionStatus + STR_MARK;
}
collctionStatus += DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, CodeKeyValue.WITHDRAWING.value(),
countryBritainId);
}
// 一部入金
if (CHECK_ON.equals(condDto.getKbnPartWithdrawedSearch())) {
if (!collctionStatus.equals("")) {
collctionStatus = collctionStatus + STR_MARK;
}
collctionStatus += DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, CodeKeyValue.PART_WITHDRAWED
.value(), countryBritainId);
}
// 回収済
if (CHECK_ON.equals(condDto.getKbnWithdrawStatusSearch())) {
if (!collctionStatus.equals("")) {
collctionStatus = collctionStatus + STR_MARK;
}
collctionStatus += DropdownListUtil.getCodeNameByCode(
CodeMstKbn.COLLECTION_STATUS, CodeKeyValue.WITHDRAWED.value(),
countryBritainId);
}
sheetData.addData(COLLCTIONSTATUS, collctionStatus);
// 通貨
sheetData.addData(CURRENCY, CurrencyUtil.getCurrencyName(condDto
.getKeyCurrency()));
// 強制解約予定
if (condDto.getEnforceEndAgreeScheduldSearch()) {
sheetData.addData(ENFORCEFLAG, 1);
} else {
sheetData.addData(ENFORCEFLAG, 0);
}
sheetData.addData(COLLCTIONSTATUS, collctionStatus);
// dropdownLists
DropdownListDto[] currencyNameItems = CurrencyUtil.getCurrencyList(
false, CodeKeyValue.CURRENCY_LIST_KBN_CONTRACT.value());
if (!ListUtil.isEmpty(currencyNameItems)) {
for (int i = 0; i < currencyNameItems.length && i < 3; i++) {
list[i] = "***合计(" + currencyNameItems[i].getLabel()
+ ")***";
}
}
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun del 2013/05/02 start********************/
// sheetData.addData(SUM, list[0]);
/***********【LAMP_STEP2 製品化追加開発】 wangxuejun del 2013/05/02 end**********************/
// ローデータ保存用
List < Object > rowDataList = new ArrayList < Object > ();
// ファイルレコード項目保存用
List < List < Object > > transferScheduleList = new ArrayList < List < Object > > ();
// 番号
int listNum = 1;
for (int i = 0; i < resultList.length; i++) {
// ローデータ保存用
rowDataList = new ArrayList < Object > ();
// 番号
rowDataList.add(listNum);
// 売主番号
rowDataList.add(resultList[i].getAgencyCustCode());
// 売主名
rowDataList.add(resultList[i].getAgencyName());
// 顧客番号
rowDataList.add(resultList[i].getCustomerCode());
// 顧客名
rowDataList.add(resultList[i].getCustomerName());
// 契約番号
rowDataList.add(resultList[i].getContractNo());
// LAMP製品化対応 zlw add start
// 拠点名
rowDataList.add(resultList[i].getBranchNm());
// LAMP製品化対応 zlw add end
// 回収種別
rowDataList.add(resultList[i].getWithdrawCasusName());
// 物件番号
rowDataList.add(resultList[i].getSuppliesNo());
// 物件名
rowDataList.add(resultList[i].getSuppliesName());
//wanghuan mult1.5 2016.1.12 start
// 契約状況
rowDataList.add(resultList[i].getContractConditionNow());
//wanghuan mult1.5 2016.1.12 end
// 回数
if (resultList[i].getCouponSeq() != null) {
rowDataList.add(resultList[i].getCoupon().toString()
+ STR_LINE + resultList[i].getCouponSeq());
} else {
rowDataList.add(resultList[i].getCoupon());
}
// 回収状況
rowDataList.add(resultList[i].getWithdrawStatusName());
// 回収予定日
String scheduleDate = "";
scheduleDate = StringUtil.formatDate(resultList[i].getWithdrawScheduleDate(),
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
// StringFormatType.DATE_FORMAT_DDMMMYYYY);
StringFormatType.DATE_FORMAT_YYYY_M_D);
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
// 【 延滞開始日~延滞終了日(延滞日数)】
if (resultList[i].getDelayedStartDate() != null) {
scheduleDate = scheduleDate + "\t\n" + StringUtil.formatDate(
resultList[i].getDelayedStartDate(),
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
//StringFormatType.DATE_FORMAT_DDMMMYYYY)
StringFormatType.DATE_FORMAT_YYYY_M_D)
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
+ TILDE
+ StringUtil.formatDate(resultList[i]
.getDelayedAccountDate(),
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 start******************/
// StringFormatType.DATE_FORMAT_DDMMMYYYY);
StringFormatType.DATE_FORMAT_YYYY_M_D);
/***********【TFS向け仕様追加・変更対応】 chenlifeng add 2013/1/11 end******************/
// (延滞日数)
scheduleDate += BRACKET_LEFT
+ resultList[i].getDelayedDays().toString()
+ BRACKET_RIGHT;
}
rowDataList.add(scheduleDate);
// 回収予定日の営業日
rowDataList.add(DatetimeUtil.getWorkDate(resultList[i]
.getWithdrawScheduleDate(), resultList[i]
.getWithdrawWorkdayFlg(), CodeKeyValue.WORKDAY_FLG_BEFORE
.value(), resultList[i].getKeyCurrencyId()));
// 回収先コード
rowDataList.add(resultList[i].getWithdrawScheduleCustomerCode());
// 回収先名
rowDataList.add(resultList[i].getWithdrawScheduleCustomerName());
// 予定回収方法
rowDataList.add(resultList[i].getScheduleWithdrawMethodName());
// 予定回収先区分
rowDataList.add(resultList[i].getScheduleWithdrawKbnName());
// 予定回収銀行
if (resultList[i].getScheduleBankBranchName() != null) {
rowDataList.add(resultList[i].getScheduleBankBranchName() + NEW_LINE
+ resultList[i].getScheduleWithdrawAccountNo());
} else {
rowDataList.add(null);
}
// 取引通貨Name
rowDataList.add(StringUtil.trim(resultList[i].getKeyCurrencyIdName()));
// 取引通貨ID(非表示)
rowDataList.add(resultList[i].getKeyCurrencyId());
// 回収予定金額
rowDataList.add(resultList[i].getWithdrawScheduleAmount());
// 未回収金額
if (resultList[i].getNotWithdrawAmount() != null) {
rowDataList.add(resultList[i].getNotWithdrawAmount());
} else {
rowDataList.add(BigDecimal.ZERO);
}
// 回収済金額
if (resultList[i].getWithdrawResultAmount() != null) {
rowDataList.add(resultList[i].getWithdrawResultAmount());
} else {
rowDataList.add(BigDecimal.ZERO);
}
// 回収実績日
rowDataList.add(StringUtil.formatDate(resultList[i].getWithdrawResultDate(),
StringFormatType.DATE_FORMAT_YYYY_M_D));
// 実回収方法
rowDataList.add(resultList[i].getRealWithdrawMethodName());
// 実回収先区分
rowDataList.add(resultList[i].getRealWithdrawKbnName());
// 実回収銀行
if (resultList[i].getRealBankBranchName() != null) {
rowDataList.add(resultList[i].getRealBankBranchName() + NEW_LINE
+ resultList[i].getRealWithdrawAccountNo());
} else {
rowDataList.add(null);
}
rowDataList.add(resultList[i].getDebitNoteOutputDate());
// 請求書番号
rowDataList.add(resultList[i].getInvoiceNo());
/*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add start ***/
// 発票分類
rowDataList.add(resultList[i].getInvType());
// 発票発行金額
rowDataList.add(resultList[i].getInvIssueAmount());
// 領収書番号
rowDataList.add(resultList[i].getReceiptNo());
// 領収書発行日
rowDataList.add(resultList[i].getReceiptSsueDate());
// 領収書発行金額
rowDataList.add(resultList[i].getReceiptIssueAmount());
/*** liuheng 2014-11-25 LAMP製品化 Step3(発票管理) add end ***/
transferScheduleList.add(rowDataList);
// 番号
listNum++;
}
// Listにデータをセット
sheetData.addData(EXECL_DATA_LIST, transferScheduleList);
return sheetData;
}
/**
* 設置 請求回収一覧dao
*
* @param dao
* 請求回収一覧dao
*/
public void setDao(Rcv0001s02Dao dao) {
this.dao = dao;
}
/**
* 設置 案件番号Dao
*
* @param caseNodao
* 案件番号Dao
*/
public void setCaseNodao(CaseMstDao caseNodao) {
this.caseNodao = caseNodao;
}
/**
* 设置ファイル一括消込ワークDao
*
* @param dataObjectWorktableDao ファイル一括消込ワークDao
*/
public void setDataObjectWorktableDao(
DataObjectWorktableDao dataObjectWorktableDao) {
this.dataObjectWorktableDao = dataObjectWorktableDao;
}
/**
* 设置 消込履歴ワークDao
*
* @param bundleCreateHistoryDao
* 消込履歴ワークDao
*/
public void setBundleCreateHistoryDao(
BundleCreateHistoryDao bundleCreateHistoryDao) {
this.bundleCreateHistoryDao = bundleCreateHistoryDao;
}
/**
* ログDAOを設定する
*
* @param logHistoryDao
* ログDAO
*/
public void setLogHistoryDao(LogHistoryDao logHistoryDao) {
this.logHistoryDao = logHistoryDao;
}
/**
* 貨マスタDaoを設定する
*
* @param currencyMstDao
* 貨マスタDao
*/
public void setCurrencyMstDao(CurrencyMstDao currencyMstDao) {
this.currencyMstDao = currencyMstDao;
}
/**
* 设置branchMstDao
*
* @param branchMstDao branchMstDao
*/
public void setBranchMstDao(BranchMstDao branchMstDao) {
this.branchMstDao = branchMstDao;
}
}
| 88,979 | 0.526349 | 0.511951 | 1,913 | 41.40617 | 28.462955 | 160 | false | false | 39 | 0.000481 | 0 | 0 | 81 | 0.000998 | 0.383691 | false | false |
15
|
215958acf1aaa9aeda0c01ff70adfeb88d120c58
| 9,474,697,900,259 |
9ea61352f076df3402de379ffc0718d468ffb2f3
|
/src/main/java/com/schizhande/usermanagementsystem/config/UserServiceBeanFactory.java
|
b8e6279d43923e0ad2ac2e5fade9fa8d37d43161
|
[] |
no_license
|
Schizhande/user-management-system
|
https://github.com/Schizhande/user-management-system
|
5a902217d698461851a97422caad8039b4dd9834
|
e531e985e9d74304a316cd193c63b273e6fc9ed8
|
refs/heads/master
| 2022-12-04T23:13:30.504000 | 2020-08-27T06:37:31 | 2020-08-27T06:37:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.schizhande.usermanagementsystem.config;
import com.schizhande.usermanagementsystem.dao.*;
import com.schizhande.usermanagementsystem.events.CreateUserListener;
import com.schizhande.usermanagementsystem.notifications.service.EmailService;
import com.schizhande.usermanagementsystem.service.*;
import com.schizhande.usermanagementsystem.service.impl.*;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class UserServiceBeanFactory {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ApplicationEventPublisher applicationEventPublisher;
private final TokenRepository tokenRepository;
public UserServiceBeanFactory(UserRepository userRepository,
PasswordEncoder passwordEncoder,
ApplicationEventPublisher applicationEventPublisher, TokenRepository tokenRepository) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.applicationEventPublisher = applicationEventPublisher;
this.tokenRepository = tokenRepository;
}
@Bean
public UserService userService(RoleRepository roleRepository) {
return new UserServiceImpl(userRepository, passwordEncoder, roleRepository, tokenRepository, applicationEventPublisher);
}
@Bean
public RoleService roleService(RoleRepository roleRepository,
UserPermissionRepository userPermissionRepository) {
return new RoleServiceImpl(roleRepository, userPermissionRepository);
}
@Bean
public ApplicationListener createUserListener(EmailService emailService) {
return new CreateUserListener(emailService, tokenRepository);
}
@Bean
public UserInformationService userInformationService(UserInformationRepository userInformationRepository) {
return new UserInformationServiceImpl(userRepository, userInformationRepository);
}
@Bean
public UserPasswordService userPasswordService() {
return new UserPasswordServiceImpl(tokenRepository, userRepository, passwordEncoder, applicationEventPublisher);
}
@Bean
public UserPermissionService userPermissionService(UserPermissionRepository userPermissionRepository,
RoleService roleService) {
return new UserPermissionServiceImpl(userPermissionRepository, roleService);
}
}
|
UTF-8
|
Java
| 2,752 |
java
|
UserServiceBeanFactory.java
|
Java
|
[] | null |
[] |
package com.schizhande.usermanagementsystem.config;
import com.schizhande.usermanagementsystem.dao.*;
import com.schizhande.usermanagementsystem.events.CreateUserListener;
import com.schizhande.usermanagementsystem.notifications.service.EmailService;
import com.schizhande.usermanagementsystem.service.*;
import com.schizhande.usermanagementsystem.service.impl.*;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class UserServiceBeanFactory {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ApplicationEventPublisher applicationEventPublisher;
private final TokenRepository tokenRepository;
public UserServiceBeanFactory(UserRepository userRepository,
PasswordEncoder passwordEncoder,
ApplicationEventPublisher applicationEventPublisher, TokenRepository tokenRepository) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.applicationEventPublisher = applicationEventPublisher;
this.tokenRepository = tokenRepository;
}
@Bean
public UserService userService(RoleRepository roleRepository) {
return new UserServiceImpl(userRepository, passwordEncoder, roleRepository, tokenRepository, applicationEventPublisher);
}
@Bean
public RoleService roleService(RoleRepository roleRepository,
UserPermissionRepository userPermissionRepository) {
return new RoleServiceImpl(roleRepository, userPermissionRepository);
}
@Bean
public ApplicationListener createUserListener(EmailService emailService) {
return new CreateUserListener(emailService, tokenRepository);
}
@Bean
public UserInformationService userInformationService(UserInformationRepository userInformationRepository) {
return new UserInformationServiceImpl(userRepository, userInformationRepository);
}
@Bean
public UserPasswordService userPasswordService() {
return new UserPasswordServiceImpl(tokenRepository, userRepository, passwordEncoder, applicationEventPublisher);
}
@Bean
public UserPermissionService userPermissionService(UserPermissionRepository userPermissionRepository,
RoleService roleService) {
return new UserPermissionServiceImpl(userPermissionRepository, roleService);
}
}
| 2,752 | 0.768895 | 0.768895 | 68 | 39.470589 | 37.130322 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.602941 | false | false |
15
|
6fd9b034fea8a11d5232ace937cf4296239efb35
| 15,290,083,634,937 |
10604042af4f4597dc68833b3c90adb75c0c69a4
|
/Java/wg-project-dashboard-monitoringPenjualan-file-mapper/src/main/java/id/co/wikagedung/system/projectDashboard/service/MonitoringPenjualanFileMapperService.java
|
82fa0286f04e14aa80cb8ce87485bc401fb585e3
|
[] |
no_license
|
myyusuf/wgdashboard
|
https://github.com/myyusuf/wgdashboard
|
e7d51dee2150250813298216daa6724402403cec
|
30ae9dba742fd3bece283abf1569da40df6217f8
|
refs/heads/master
| 2021-01-10T06:58:12.850000 | 2016-01-03T04:28:31 | 2016-01-03T04:28:31 | 45,313,818 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package id.co.wikagedung.system.projectDashboard.service;
import id.co.wikagedung.system.projectDashboard.model.MonitoringPenjualan;
import java.io.IOException;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
public interface MonitoringPenjualanFileMapperService {
List<MonitoringPenjualan> monitoringPenjualanExcelFileMapping() throws InvalidFormatException, IOException;
}
|
UTF-8
|
Java
| 438 |
java
|
MonitoringPenjualanFileMapperService.java
|
Java
|
[] | null |
[] |
package id.co.wikagedung.system.projectDashboard.service;
import id.co.wikagedung.system.projectDashboard.model.MonitoringPenjualan;
import java.io.IOException;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
public interface MonitoringPenjualanFileMapperService {
List<MonitoringPenjualan> monitoringPenjualanExcelFileMapping() throws InvalidFormatException, IOException;
}
| 438 | 0.83105 | 0.828767 | 14 | 29.285715 | 34.822876 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
15
|
86df2c74fbe597eab1c757d69f6eb953abd507a4
| 36,464,272,372,186 |
8082ecef61cacc611aa4f2f0d5c07f4242db35e7
|
/src/main/java/com/eEducation/ftn/web/dto/ColloquiumResultDTO.java
|
8c07ecf10be7757a367ba3a6f6b58e9ae004ec15
|
[] |
no_license
|
lazars14/eEducation
|
https://github.com/lazars14/eEducation
|
006d4f5ad811bfdd36ee5eae45c35dbbc88d154e
|
adad0fa2d9098adb85eea2df02b8b8e9e88f38d0
|
refs/heads/master
| 2021-09-18T09:03:06.434000 | 2018-07-12T07:07:52 | 2018-07-12T07:07:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.eEducation.ftn.web.dto;
import com.eEducation.ftn.model.ColloquiumResult;
public class ColloquiumResultDTO {
private Long id;
private Float points;
private ColloquiumDTO colloquium;
private StudentDTO student;
private StudentDocumentDTO document;
public ColloquiumResultDTO() {}
public ColloquiumResultDTO(ColloquiumResult cr) {
super();
this.id = cr.getId();
this.points = cr.getPoints();
this.colloquium = new ColloquiumDTO(cr.getColloquium());
this.student = new StudentDTO(cr.getStudent());
if(cr.getDocument() == null) {
// document doesn't exist
this.document = null;
} else {
// document exists
this.document = new StudentDocumentDTO(cr.getDocument());
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Float getPoints() {
return points;
}
public void setPoints(Float points) {
this.points = points;
}
public ColloquiumDTO getColloquium() {
return colloquium;
}
public void setColloquium(ColloquiumDTO colloquium) {
this.colloquium = colloquium;
}
public StudentDTO getStudent() {
return student;
}
public void setStudent(StudentDTO student) {
this.student = student;
}
public StudentDocumentDTO getDocument() {
return document;
}
public void setDocument(StudentDocumentDTO document) {
this.document = document;
}
}
|
UTF-8
|
Java
| 1,399 |
java
|
ColloquiumResultDTO.java
|
Java
|
[] | null |
[] |
package com.eEducation.ftn.web.dto;
import com.eEducation.ftn.model.ColloquiumResult;
public class ColloquiumResultDTO {
private Long id;
private Float points;
private ColloquiumDTO colloquium;
private StudentDTO student;
private StudentDocumentDTO document;
public ColloquiumResultDTO() {}
public ColloquiumResultDTO(ColloquiumResult cr) {
super();
this.id = cr.getId();
this.points = cr.getPoints();
this.colloquium = new ColloquiumDTO(cr.getColloquium());
this.student = new StudentDTO(cr.getStudent());
if(cr.getDocument() == null) {
// document doesn't exist
this.document = null;
} else {
// document exists
this.document = new StudentDocumentDTO(cr.getDocument());
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Float getPoints() {
return points;
}
public void setPoints(Float points) {
this.points = points;
}
public ColloquiumDTO getColloquium() {
return colloquium;
}
public void setColloquium(ColloquiumDTO colloquium) {
this.colloquium = colloquium;
}
public StudentDTO getStudent() {
return student;
}
public void setStudent(StudentDTO student) {
this.student = student;
}
public StudentDocumentDTO getDocument() {
return document;
}
public void setDocument(StudentDocumentDTO document) {
this.document = document;
}
}
| 1,399 | 0.70336 | 0.70336 | 72 | 18.430555 | 17.946547 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.402778 | false | false |
15
|
bd5b4c4f7e7a1c59846f4d27d007e3bbbc81fe8e
| 36,086,315,248,368 |
40dd2c2ba934bcbc611b366cf57762dcb14c48e3
|
/RI_Stack/java/src/base/org/cablelabs/impl/manager/system/html/Parser.java
|
1ba4223cec5e743b02e60984c046e2f5b6e20a75
|
[] |
no_license
|
amirna2/OCAP-RI
|
https://github.com/amirna2/OCAP-RI
|
afe0d924dcf057020111406b1d29aa2b3a796e10
|
254f0a8ebaf5b4f09f4a7c8f4961e9596c49ccb7
|
refs/heads/master
| 2020-03-10T03:22:34.355000 | 2018-04-11T23:08:49 | 2018-04-11T23:08:49 | 129,163,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// COPYRIGHT_BEGIN
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
//
// Copyright (C) 2008-2013, Cable Television Laboratories, Inc.
//
// This software is available under multiple licenses:
//
// (1) BSD 2-clause
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
// ·Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// ·Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the
// distribution.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// (2) GPL Version 2
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2. This program is distributed
// in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program.If not, see<http:www.gnu.org/licenses/>.
//
// (3)CableLabs License
// If you or the company you represent has a separate agreement with CableLabs
// concerning the use of this code, your rights and obligations with respect
// to this code shall be as set forth therein. No license is granted hereunder
// for any other purpose.
//
// Please contact CableLabs if you need additional information or
// have any questions.
//
// CableLabs
// 858 Coal Creek Cir
// Louisville, CO 80027-9750
// 303 661-9100
// COPYRIGHT_END
package org.cablelabs.impl.manager.system.html;
import java.text.CharacterIterator;
import java.util.HashMap;
import java.util.Map;
/**
* Parses an input string into a series of start tags, end tags, and blocks of
* text, according to a subset of the HTML5 tokenization rules.
*
* @author Spencer Schumann
*
*/
public class Parser
{
private final String input;
private final int length;
private final TagHandler handler;
private int pos = 0;
private StringBuffer text = new StringBuffer();
private static final char EOF = CharacterIterator.DONE;
private static final HashMap charEntities = new HashMap();
/**
* Parses an html string, returning a Document object.
*
* @param html
* input string
* @return document
*/
public static Document parse(String html)
{
Document.Builder document = Document.builder();
parse(html, document);
return document.build();
}
/**
* Parse an html string, handling the tags and text with the specified
* handler.
*
* @param html
* string to parse
* @param handler
* handler for tags and text
*/
public static void parse(String html, TagHandler handler)
{
Parser parser = new Parser(html, handler);
parser.read();
}
/**
* Tests whether a given character is whitespace according to the HTML5
* whitespace rules. In contrast to Character.isWhitespace, this method is
* not dependent upon the current locale.
*
* @param c
* character to test
* @return true if it is whitespace, false otherwise
*/
public static boolean isWhitespace(char c)
{
switch (c)
{
case '\t':
case '\n':
case '\f':
case '\r':
case ' ':
return true;
default:
return false;
}
}
/**
* Private constructor to prevent direct instantiation and sub-classing.
*
* @param input
* string to parse
* @param handler
* handler for tags and text
*/
private Parser(String input, TagHandler handler)
{
this.input = input;
this.length = input.length();
this.handler = handler;
}
/**
* Read all of the characters in the input string.
*
*/
private void read()
{
while (!atEnd())
{
if (current() == '<')
{
consume();
readTag();
}
else
{
readText();
}
}
emitText();
}
/**
* Remove '\r' characters, converting them to newlines as specified by the
* HTML5 preprocessing rules.
*
* @param str
* string to convert
* @return string with '\r' characters removed
*/
private String convertCarriageReturns(String str)
{
int index = str.indexOf('\r');
if (index < 0)
{
// No CR to convert
return str;
}
StringBuffer buffer = new StringBuffer(str);
while ((index = buffer.indexOf("\r", index)) >= 0)
{
int length = buffer.length();
// Convert '\r' to '\n'
buffer.setCharAt(index, '\n');
if (index < (length - 1))
{
if (buffer.charAt(index + 1) == '\n')
{
// "\r\n" - drop the '\n'
buffer.replace(index + 1, index + 2, "");
}
}
}
return buffer.toString();
}
/**
* Send the current block of text to the handler's text callback method
*
*/
private void emitText()
{
if (text.length() > 0)
{
String str = text.toString();
str = convertCarriageReturns(str);
handler.text(str);
text = new StringBuffer();
}
}
/**
* Read a block of text, which extends up to the next '<' character.
* Translate any character entities that are encountered.
*
*/
private void readText()
{
while (!atEnd())
{
char c = current();
if (c == '&')
{
readCharacterEntity(text);
}
else if (c == '<')
{
break;
}
else
{
if (isValidCharacter(c))
{
text.append(c);
}
consume();
}
}
}
/**
* Read a character entity from the input string and add the translated
* character to the given string buffer.
*
* @param buffer
* string buffer to receive translated character
*/
private void readCharacterEntity(StringBuffer buffer)
{
int semiIndex = input.indexOf(';', pos);
if (semiIndex > (pos + 1))
{
String entity = input.substring(pos + 1, semiIndex);
// There's a possibly valid character entity reference here.
if (entity.charAt(0) == '#')
{
// Numeric entity reference
try
{
char c = (char) Integer.parseInt(entity.substring(1));
if (isValidCharacter(c) && c != '\r')
{
buffer.append(c);
pos = semiIndex + 1;
return;
}
}
catch (NumberFormatException e)
{
}
}
else
{
// Check for named character entity
Character c = (Character) charEntities.get(entity);
if (null != c)
{
buffer.append(c.charValue());
pos = semiIndex + 1;
return;
}
}
}
buffer.append('&');
consume();
}
/**
* Test for valid characters as defined in Table A-2 of
* OC-SP-CCIF2.0-I20-091211.
*
* @param c
* character to test
* @return true if valid, false otherwise
*/
private static boolean isValidCharacter(char c)
{
return (32 <= c && c <= 126) || (160 <= c && c <= 255)
|| "\t\r\n\f".indexOf(c) >= 0;
}
/**
* Test whether a given character is a letter. In contrast to
* Character.isLetter, this method only allows upper case and lower case
* letters A through Z.
*
* @param c
* character to test
* @return true if it is a letter, false otherwise
*/
private static boolean isLetter(char c)
{
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
}
/**
* Convert a string to lower-case. In contrast with String.toLowerCase, this
* method uses the HTML5 rules for converting case and is not locale
* dependent.
*
* @param str
* string to convert
* @return string with upper case letters converted to lower case
*/
public static String toLowerCase(String str)
{
// Only create the StringBuffer if necessary.
// If there are no upper case characters, return the same string.
int i;
int length = str.length();
StringBuffer buffer = null;
for (i = 0; i < length; i++)
{
char c = str.charAt(i);
if ('A' <= c && c <= 'Z')
{
buffer = new StringBuffer(length);
buffer.append(str.substring(0, i));
break;
}
}
if (buffer != null)
{
for (; i < length; i++)
{
char c = str.charAt(i);
if ('A' <= c && c <= 'Z')
{
c += 0x20;
}
buffer.append(c);
}
return buffer.toString();
}
else
{
return str;
}
}
/**
* Reads a single tag from the input stream.
*
* @return tag
*/
private void readTag()
{
char c = current();
switch (c)
{
case '/':
consume();
readEndTag();
break;
case '!':
consume();
readMarkupDeclaration();
break;
case '?':
consume();
readBogusComment();
break;
case EOF:
text.append('<');
break;
default:
if (isLetter(c))
{
readStartTag();
}
else
{
text.append('<');
}
break;
}
}
/**
* Reads a markup declaration, which is a tag that starts with "<!".
*
*/
private void readMarkupDeclaration()
{
if (remainder().startsWith("--"))
{
consume(2);
readComment();
}
else
{
// Note: <!DOCTYPE...> can be treated as a bogus comment.
readBogusComment();
}
}
/**
* Read a comment tag as defined by the HTML5 processing rules.
*
*/
private void readComment()
{
String rest = remainder();
if (rest.startsWith(">"))
{
consume();
return;
}
if (rest.startsWith("->"))
{
consume(2);
return;
}
int index;
while ((index = input.indexOf("--", pos)) >= 0)
{
// In case the comment doesn't end here, go back to second '-' of
// the "--" that was found
// (to handle the case of "---")
int resumePos = index + 1;
// Skip "--"
pos = index + 2;
if (current() == '!')
{
consume();
}
else
{
consumeWhitespace();
}
if (current() == '>')
{
// End of comment.
consume();
return;
}
else if (atEnd())
{
break;
}
else
{
pos = resumePos;
}
}
// Unterminated comment.
pos = length;
}
/**
* Read a bogus comment as defined by the HTML5 processing rules.
*
*/
private void readBogusComment()
{
// Skip to the next '>'.
int index = input.indexOf('>', pos);
if (index < 0)
{
pos = length;
}
else
{
pos = index + 1;
}
}
/**
* Read a start tag.
*
*/
private void readStartTag()
{
String name = readTagName();
Map attributes = readAttributes();
if (current() == '>')
{
consume();
emitText();
handler.startTag(name, attributes);
}
}
/**
* Read an end tag.
*
*/
private void readEndTag()
{
char c = current();
if (isLetter(c))
{
String name = readTagName();
// Strip off any attributes that were erroneously added to the end
// tag
readAttributes();
if (!atEnd() && current() == '>')
{
consume();
emitText();
handler.endTag(name);
}
}
else if ('>' == c)
{
// Parse error: encountered "</>". Nothing is emitted in this case.
consume();
}
else if (c == EOF)
{
text.append("</");
}
else
{
readBogusComment();
}
}
/**
* Read a tag name.
*
* @return the tag's name
*/
private String readTagName()
{
StringBuffer buffer = new StringBuffer();
while (!atEnd())
{
char c = current();
if (isWhitespace(c) || '/' == c || '>' == c)
{
break;
}
else
{
if (isValidCharacter(c))
{
buffer.append(c);
}
consume();
}
}
return toLowerCase(buffer.toString());
}
/**
* Read tag attributes.
*
* @return map of attribute key-value pairs.
*/
private Map readAttributes()
{
// The total number of attributes is expected to be
// much less than the default HashMap size of 16.
// TODO: I'd prefer to use Collections.EMPTY_MAP by default...
Map attributes = new HashMap(4);
while (true)
{
consumeWhitespace();
if (atEnd())
{
return attributes;
}
switch (current())
{
case '/':
// Possible XML-style self-closing tag. This syntax is
// accepted, but does not have any effect.
consume();
if (!atEnd() && current() == '>')
{
return attributes;
}
break;
case '>':
// End of tag.
return attributes;
default:
readAttribute(attributes);
break;
}
}
}
/**
* Read a single attribute and add it to the attribute map. If the attribute
* already exists in the map, the existing value is retained.
*
* @param attributes
* map of attributes being read.
*/
private void readAttribute(Map attributes)
{
String name = readAttributeName();
String value = "";
consumeWhitespace();
if (current() == '=')
{
consume();
consumeWhitespace();
value = readAttributeValue();
}
// The first appearance of a given attribute takes
// precedence.
if (!attributes.containsKey(name))
{
attributes.put(name, value);
}
}
/**
* Read an attribute name.
*
* @return the attribute name
*/
private String readAttributeName()
{
StringBuffer buffer = new StringBuffer();
int startPos = pos;
loop: while (!atEnd())
{
char c = current();
switch (c)
{
case '/':
case '>':
break loop;
default:
// '=' is allowed as the first character of an attribute
// name, but it generates a parse error.
if (c == '=' && pos != startPos)
{
break loop;
}
else if (isWhitespace(c))
{
break loop;
}
else if (isValidCharacter(c))
{
buffer.append(c);
}
consume();
break;
}
}
return toLowerCase(buffer.toString());
}
/**
* Read an attribute value.
*
* @return attribute value
*/
private String readAttributeValue()
{
char c = current();
switch (c)
{
case '>':
return "";
case '\'':
case '\"':
consume();
return readQuotedValue(c);
case EOF:
return "";
default:
return readUnquotedValue();
}
}
/**
* Read a quoted attribute value.
*
* @param quote
* quotation mark that terminates this quotation.
* @return attribute value
*/
private String readQuotedValue(char quote)
{
StringBuffer buffer = new StringBuffer();
while (!atEnd())
{
char c = current();
if (c == quote)
{
consume();
break;
}
else if (c == '&')
{
readCharacterEntity(buffer);
}
else
{
if (isValidCharacter(c))
{
buffer.append(c);
}
consume();
}
}
String str = buffer.toString();
return convertCarriageReturns(str);
}
/**
* Read an unquoted attribute value.
*
* @return attribute value
*/
private String readUnquotedValue()
{
StringBuffer buffer = new StringBuffer();
loop: while (!atEnd())
{
char c = current();
switch (c)
{
case '&':
readCharacterEntity(buffer);
break;
case '>':
break loop;
default:
if (isWhitespace(c))
{
break loop;
}
else
{
if (isValidCharacter(c))
{
buffer.append(c);
}
consume();
}
break;
}
}
return buffer.toString();
}
/**
* Consume a single character. The current input position is advanced by
* one.
*
*/
private void consume()
{
pos++;
}
/**
* Consume count input characters. The current input position is advanced by
* count.
*
* @param count
*/
private void consume(int count)
{
pos += count;
}
/**
* Get the current input character. Returns EOF if no more characters are
* available.
*
* @return current character
*/
private char current()
{
return atEnd() ? EOF : input.charAt(pos);
}
/**
* Return the substring of the input from the current position to the end of
* the string.
*
* @return substring of input
*/
private String remainder()
{
return atEnd() ? "" : input.substring(pos);
}
/**
* Determine whether the entire input string has been read.
*
* @return true if at end, false otherwise
*/
private boolean atEnd()
{
return pos >= length;
}
/**
* Skip past all consecutive whitespace characters starting at the current
* input position.
*
*/
private void consumeWhitespace()
{
while (!atEnd())
{
char r = current();
if (isWhitespace(r))
{
consume();
}
else
{
break;
}
}
}
/**
* Convenience method for setting up the map of named character entities.
*
* @param name
* name of character
* @param charCode
* character code
*/
private static void addCharEntity(String name, int charCode)
{
charEntities.put(name, new Character((char) charCode));
}
static
{
// This list of character entities is from Table A-2 of
// OC-SP-CCIF2.0-I20-091211.
addCharEntity("quot", 34);
addCharEntity("amp", 38);
addCharEntity("lt", 60);
addCharEntity("gt", 62);
addCharEntity("nbsp", 160);
addCharEntity("iexcl", 161);
addCharEntity("cent", 162);
addCharEntity("pound", 163);
addCharEntity("curren", 164);
addCharEntity("yen", 165);
addCharEntity("brvbar", 166);
addCharEntity("sect", 167);
addCharEntity("uml", 168);
addCharEntity("copy", 169);
addCharEntity("ordf", 170);
addCharEntity("laquo", 171);
addCharEntity("not", 172);
addCharEntity("shy", 173);
addCharEntity("reg", 174);
addCharEntity("macr", 175);
addCharEntity("deg", 176);
addCharEntity("plusmn", 177);
addCharEntity("sup2", 178);
addCharEntity("sup3", 179);
addCharEntity("acute", 180);
addCharEntity("micro", 181);
addCharEntity("para", 182);
addCharEntity("middot", 183);
addCharEntity("cedil", 184);
addCharEntity("sup1", 185);
addCharEntity("ordm", 186);
addCharEntity("raquo", 187);
addCharEntity("frac14", 188);
addCharEntity("frac12", 189);
addCharEntity("frac34", 190);
addCharEntity("iquest", 191);
addCharEntity("Agrave", 192);
addCharEntity("Aacute", 193);
addCharEntity("Acirc", 194);
addCharEntity("Atilde", 195);
addCharEntity("Auml", 196);
addCharEntity("Aring", 197);
addCharEntity("AElig", 198);
addCharEntity("Ccedil", 199);
addCharEntity("Egrave", 200);
addCharEntity("Eacute", 201);
addCharEntity("Ecirc", 202);
addCharEntity("Euml", 203);
addCharEntity("Igrave", 204);
addCharEntity("Iacute", 205);
addCharEntity("Icirc", 206);
addCharEntity("Iuml", 207);
addCharEntity("ETH", 208);
addCharEntity("Ntilde", 209);
addCharEntity("Ograve", 210);
addCharEntity("Oacute", 211);
addCharEntity("Ocirc", 212);
addCharEntity("Otilde", 213);
addCharEntity("Ouml", 214);
addCharEntity("times", 215);
addCharEntity("Oslash", 216);
addCharEntity("Ugrave", 217);
addCharEntity("Uacute", 218);
addCharEntity("Ucirc", 219);
addCharEntity("Uuml", 220);
addCharEntity("Yacute", 221);
addCharEntity("THORN", 222);
addCharEntity("szlig", 223);
addCharEntity("agrave", 224);
addCharEntity("aacute", 225);
addCharEntity("acirc", 226);
addCharEntity("atilde", 227);
addCharEntity("auml", 228);
addCharEntity("aring", 229);
addCharEntity("aelig", 230);
addCharEntity("ccedil", 231);
addCharEntity("egrave", 232);
addCharEntity("eacute", 233);
addCharEntity("ecirc", 234);
addCharEntity("euml", 235);
addCharEntity("igrave", 236);
addCharEntity("iacute", 237);
addCharEntity("icirc", 238);
addCharEntity("iuml", 239);
addCharEntity("eth", 240);
addCharEntity("ntilde", 241);
addCharEntity("ograve", 242);
addCharEntity("oacute", 243);
addCharEntity("ocirc", 244);
addCharEntity("otilde", 245);
addCharEntity("ouml", 246);
addCharEntity("divide", 247);
addCharEntity("oslash", 248);
addCharEntity("ugrave", 249);
addCharEntity("uacute", 250);
addCharEntity("ucirc", 251);
addCharEntity("uuml", 252);
addCharEntity("yacute", 253);
addCharEntity("thorn", 254);
addCharEntity("yuml", 255);
}
}
|
UTF-8
|
Java
| 26,600 |
java
|
Parser.java
|
Java
|
[
{
"context": "et of the HTML5 tokenization rules.\n * \n * @author Spencer Schumann\n * \n */\npublic class Parser\n{\n private final S",
"end": 3068,
"score": 0.9998413920402527,
"start": 3052,
"tag": "NAME",
"value": "Spencer Schumann"
}
] | null |
[] |
// COPYRIGHT_BEGIN
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
//
// Copyright (C) 2008-2013, Cable Television Laboratories, Inc.
//
// This software is available under multiple licenses:
//
// (1) BSD 2-clause
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
// ·Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// ·Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the
// distribution.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// (2) GPL Version 2
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2. This program is distributed
// in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program.If not, see<http:www.gnu.org/licenses/>.
//
// (3)CableLabs License
// If you or the company you represent has a separate agreement with CableLabs
// concerning the use of this code, your rights and obligations with respect
// to this code shall be as set forth therein. No license is granted hereunder
// for any other purpose.
//
// Please contact CableLabs if you need additional information or
// have any questions.
//
// CableLabs
// 858 Coal Creek Cir
// Louisville, CO 80027-9750
// 303 661-9100
// COPYRIGHT_END
package org.cablelabs.impl.manager.system.html;
import java.text.CharacterIterator;
import java.util.HashMap;
import java.util.Map;
/**
* Parses an input string into a series of start tags, end tags, and blocks of
* text, according to a subset of the HTML5 tokenization rules.
*
* @author <NAME>
*
*/
public class Parser
{
private final String input;
private final int length;
private final TagHandler handler;
private int pos = 0;
private StringBuffer text = new StringBuffer();
private static final char EOF = CharacterIterator.DONE;
private static final HashMap charEntities = new HashMap();
/**
* Parses an html string, returning a Document object.
*
* @param html
* input string
* @return document
*/
public static Document parse(String html)
{
Document.Builder document = Document.builder();
parse(html, document);
return document.build();
}
/**
* Parse an html string, handling the tags and text with the specified
* handler.
*
* @param html
* string to parse
* @param handler
* handler for tags and text
*/
public static void parse(String html, TagHandler handler)
{
Parser parser = new Parser(html, handler);
parser.read();
}
/**
* Tests whether a given character is whitespace according to the HTML5
* whitespace rules. In contrast to Character.isWhitespace, this method is
* not dependent upon the current locale.
*
* @param c
* character to test
* @return true if it is whitespace, false otherwise
*/
public static boolean isWhitespace(char c)
{
switch (c)
{
case '\t':
case '\n':
case '\f':
case '\r':
case ' ':
return true;
default:
return false;
}
}
/**
* Private constructor to prevent direct instantiation and sub-classing.
*
* @param input
* string to parse
* @param handler
* handler for tags and text
*/
private Parser(String input, TagHandler handler)
{
this.input = input;
this.length = input.length();
this.handler = handler;
}
/**
* Read all of the characters in the input string.
*
*/
private void read()
{
while (!atEnd())
{
if (current() == '<')
{
consume();
readTag();
}
else
{
readText();
}
}
emitText();
}
/**
* Remove '\r' characters, converting them to newlines as specified by the
* HTML5 preprocessing rules.
*
* @param str
* string to convert
* @return string with '\r' characters removed
*/
private String convertCarriageReturns(String str)
{
int index = str.indexOf('\r');
if (index < 0)
{
// No CR to convert
return str;
}
StringBuffer buffer = new StringBuffer(str);
while ((index = buffer.indexOf("\r", index)) >= 0)
{
int length = buffer.length();
// Convert '\r' to '\n'
buffer.setCharAt(index, '\n');
if (index < (length - 1))
{
if (buffer.charAt(index + 1) == '\n')
{
// "\r\n" - drop the '\n'
buffer.replace(index + 1, index + 2, "");
}
}
}
return buffer.toString();
}
/**
* Send the current block of text to the handler's text callback method
*
*/
private void emitText()
{
if (text.length() > 0)
{
String str = text.toString();
str = convertCarriageReturns(str);
handler.text(str);
text = new StringBuffer();
}
}
/**
* Read a block of text, which extends up to the next '<' character.
* Translate any character entities that are encountered.
*
*/
private void readText()
{
while (!atEnd())
{
char c = current();
if (c == '&')
{
readCharacterEntity(text);
}
else if (c == '<')
{
break;
}
else
{
if (isValidCharacter(c))
{
text.append(c);
}
consume();
}
}
}
/**
* Read a character entity from the input string and add the translated
* character to the given string buffer.
*
* @param buffer
* string buffer to receive translated character
*/
private void readCharacterEntity(StringBuffer buffer)
{
int semiIndex = input.indexOf(';', pos);
if (semiIndex > (pos + 1))
{
String entity = input.substring(pos + 1, semiIndex);
// There's a possibly valid character entity reference here.
if (entity.charAt(0) == '#')
{
// Numeric entity reference
try
{
char c = (char) Integer.parseInt(entity.substring(1));
if (isValidCharacter(c) && c != '\r')
{
buffer.append(c);
pos = semiIndex + 1;
return;
}
}
catch (NumberFormatException e)
{
}
}
else
{
// Check for named character entity
Character c = (Character) charEntities.get(entity);
if (null != c)
{
buffer.append(c.charValue());
pos = semiIndex + 1;
return;
}
}
}
buffer.append('&');
consume();
}
/**
* Test for valid characters as defined in Table A-2 of
* OC-SP-CCIF2.0-I20-091211.
*
* @param c
* character to test
* @return true if valid, false otherwise
*/
private static boolean isValidCharacter(char c)
{
return (32 <= c && c <= 126) || (160 <= c && c <= 255)
|| "\t\r\n\f".indexOf(c) >= 0;
}
/**
* Test whether a given character is a letter. In contrast to
* Character.isLetter, this method only allows upper case and lower case
* letters A through Z.
*
* @param c
* character to test
* @return true if it is a letter, false otherwise
*/
private static boolean isLetter(char c)
{
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
}
/**
* Convert a string to lower-case. In contrast with String.toLowerCase, this
* method uses the HTML5 rules for converting case and is not locale
* dependent.
*
* @param str
* string to convert
* @return string with upper case letters converted to lower case
*/
public static String toLowerCase(String str)
{
// Only create the StringBuffer if necessary.
// If there are no upper case characters, return the same string.
int i;
int length = str.length();
StringBuffer buffer = null;
for (i = 0; i < length; i++)
{
char c = str.charAt(i);
if ('A' <= c && c <= 'Z')
{
buffer = new StringBuffer(length);
buffer.append(str.substring(0, i));
break;
}
}
if (buffer != null)
{
for (; i < length; i++)
{
char c = str.charAt(i);
if ('A' <= c && c <= 'Z')
{
c += 0x20;
}
buffer.append(c);
}
return buffer.toString();
}
else
{
return str;
}
}
/**
* Reads a single tag from the input stream.
*
* @return tag
*/
private void readTag()
{
char c = current();
switch (c)
{
case '/':
consume();
readEndTag();
break;
case '!':
consume();
readMarkupDeclaration();
break;
case '?':
consume();
readBogusComment();
break;
case EOF:
text.append('<');
break;
default:
if (isLetter(c))
{
readStartTag();
}
else
{
text.append('<');
}
break;
}
}
/**
* Reads a markup declaration, which is a tag that starts with "<!".
*
*/
private void readMarkupDeclaration()
{
if (remainder().startsWith("--"))
{
consume(2);
readComment();
}
else
{
// Note: <!DOCTYPE...> can be treated as a bogus comment.
readBogusComment();
}
}
/**
* Read a comment tag as defined by the HTML5 processing rules.
*
*/
private void readComment()
{
String rest = remainder();
if (rest.startsWith(">"))
{
consume();
return;
}
if (rest.startsWith("->"))
{
consume(2);
return;
}
int index;
while ((index = input.indexOf("--", pos)) >= 0)
{
// In case the comment doesn't end here, go back to second '-' of
// the "--" that was found
// (to handle the case of "---")
int resumePos = index + 1;
// Skip "--"
pos = index + 2;
if (current() == '!')
{
consume();
}
else
{
consumeWhitespace();
}
if (current() == '>')
{
// End of comment.
consume();
return;
}
else if (atEnd())
{
break;
}
else
{
pos = resumePos;
}
}
// Unterminated comment.
pos = length;
}
/**
* Read a bogus comment as defined by the HTML5 processing rules.
*
*/
private void readBogusComment()
{
// Skip to the next '>'.
int index = input.indexOf('>', pos);
if (index < 0)
{
pos = length;
}
else
{
pos = index + 1;
}
}
/**
* Read a start tag.
*
*/
private void readStartTag()
{
String name = readTagName();
Map attributes = readAttributes();
if (current() == '>')
{
consume();
emitText();
handler.startTag(name, attributes);
}
}
/**
* Read an end tag.
*
*/
private void readEndTag()
{
char c = current();
if (isLetter(c))
{
String name = readTagName();
// Strip off any attributes that were erroneously added to the end
// tag
readAttributes();
if (!atEnd() && current() == '>')
{
consume();
emitText();
handler.endTag(name);
}
}
else if ('>' == c)
{
// Parse error: encountered "</>". Nothing is emitted in this case.
consume();
}
else if (c == EOF)
{
text.append("</");
}
else
{
readBogusComment();
}
}
/**
* Read a tag name.
*
* @return the tag's name
*/
private String readTagName()
{
StringBuffer buffer = new StringBuffer();
while (!atEnd())
{
char c = current();
if (isWhitespace(c) || '/' == c || '>' == c)
{
break;
}
else
{
if (isValidCharacter(c))
{
buffer.append(c);
}
consume();
}
}
return toLowerCase(buffer.toString());
}
/**
* Read tag attributes.
*
* @return map of attribute key-value pairs.
*/
private Map readAttributes()
{
// The total number of attributes is expected to be
// much less than the default HashMap size of 16.
// TODO: I'd prefer to use Collections.EMPTY_MAP by default...
Map attributes = new HashMap(4);
while (true)
{
consumeWhitespace();
if (atEnd())
{
return attributes;
}
switch (current())
{
case '/':
// Possible XML-style self-closing tag. This syntax is
// accepted, but does not have any effect.
consume();
if (!atEnd() && current() == '>')
{
return attributes;
}
break;
case '>':
// End of tag.
return attributes;
default:
readAttribute(attributes);
break;
}
}
}
/**
* Read a single attribute and add it to the attribute map. If the attribute
* already exists in the map, the existing value is retained.
*
* @param attributes
* map of attributes being read.
*/
private void readAttribute(Map attributes)
{
String name = readAttributeName();
String value = "";
consumeWhitespace();
if (current() == '=')
{
consume();
consumeWhitespace();
value = readAttributeValue();
}
// The first appearance of a given attribute takes
// precedence.
if (!attributes.containsKey(name))
{
attributes.put(name, value);
}
}
/**
* Read an attribute name.
*
* @return the attribute name
*/
private String readAttributeName()
{
StringBuffer buffer = new StringBuffer();
int startPos = pos;
loop: while (!atEnd())
{
char c = current();
switch (c)
{
case '/':
case '>':
break loop;
default:
// '=' is allowed as the first character of an attribute
// name, but it generates a parse error.
if (c == '=' && pos != startPos)
{
break loop;
}
else if (isWhitespace(c))
{
break loop;
}
else if (isValidCharacter(c))
{
buffer.append(c);
}
consume();
break;
}
}
return toLowerCase(buffer.toString());
}
/**
* Read an attribute value.
*
* @return attribute value
*/
private String readAttributeValue()
{
char c = current();
switch (c)
{
case '>':
return "";
case '\'':
case '\"':
consume();
return readQuotedValue(c);
case EOF:
return "";
default:
return readUnquotedValue();
}
}
/**
* Read a quoted attribute value.
*
* @param quote
* quotation mark that terminates this quotation.
* @return attribute value
*/
private String readQuotedValue(char quote)
{
StringBuffer buffer = new StringBuffer();
while (!atEnd())
{
char c = current();
if (c == quote)
{
consume();
break;
}
else if (c == '&')
{
readCharacterEntity(buffer);
}
else
{
if (isValidCharacter(c))
{
buffer.append(c);
}
consume();
}
}
String str = buffer.toString();
return convertCarriageReturns(str);
}
/**
* Read an unquoted attribute value.
*
* @return attribute value
*/
private String readUnquotedValue()
{
StringBuffer buffer = new StringBuffer();
loop: while (!atEnd())
{
char c = current();
switch (c)
{
case '&':
readCharacterEntity(buffer);
break;
case '>':
break loop;
default:
if (isWhitespace(c))
{
break loop;
}
else
{
if (isValidCharacter(c))
{
buffer.append(c);
}
consume();
}
break;
}
}
return buffer.toString();
}
/**
* Consume a single character. The current input position is advanced by
* one.
*
*/
private void consume()
{
pos++;
}
/**
* Consume count input characters. The current input position is advanced by
* count.
*
* @param count
*/
private void consume(int count)
{
pos += count;
}
/**
* Get the current input character. Returns EOF if no more characters are
* available.
*
* @return current character
*/
private char current()
{
return atEnd() ? EOF : input.charAt(pos);
}
/**
* Return the substring of the input from the current position to the end of
* the string.
*
* @return substring of input
*/
private String remainder()
{
return atEnd() ? "" : input.substring(pos);
}
/**
* Determine whether the entire input string has been read.
*
* @return true if at end, false otherwise
*/
private boolean atEnd()
{
return pos >= length;
}
/**
* Skip past all consecutive whitespace characters starting at the current
* input position.
*
*/
private void consumeWhitespace()
{
while (!atEnd())
{
char r = current();
if (isWhitespace(r))
{
consume();
}
else
{
break;
}
}
}
/**
* Convenience method for setting up the map of named character entities.
*
* @param name
* name of character
* @param charCode
* character code
*/
private static void addCharEntity(String name, int charCode)
{
charEntities.put(name, new Character((char) charCode));
}
static
{
// This list of character entities is from Table A-2 of
// OC-SP-CCIF2.0-I20-091211.
addCharEntity("quot", 34);
addCharEntity("amp", 38);
addCharEntity("lt", 60);
addCharEntity("gt", 62);
addCharEntity("nbsp", 160);
addCharEntity("iexcl", 161);
addCharEntity("cent", 162);
addCharEntity("pound", 163);
addCharEntity("curren", 164);
addCharEntity("yen", 165);
addCharEntity("brvbar", 166);
addCharEntity("sect", 167);
addCharEntity("uml", 168);
addCharEntity("copy", 169);
addCharEntity("ordf", 170);
addCharEntity("laquo", 171);
addCharEntity("not", 172);
addCharEntity("shy", 173);
addCharEntity("reg", 174);
addCharEntity("macr", 175);
addCharEntity("deg", 176);
addCharEntity("plusmn", 177);
addCharEntity("sup2", 178);
addCharEntity("sup3", 179);
addCharEntity("acute", 180);
addCharEntity("micro", 181);
addCharEntity("para", 182);
addCharEntity("middot", 183);
addCharEntity("cedil", 184);
addCharEntity("sup1", 185);
addCharEntity("ordm", 186);
addCharEntity("raquo", 187);
addCharEntity("frac14", 188);
addCharEntity("frac12", 189);
addCharEntity("frac34", 190);
addCharEntity("iquest", 191);
addCharEntity("Agrave", 192);
addCharEntity("Aacute", 193);
addCharEntity("Acirc", 194);
addCharEntity("Atilde", 195);
addCharEntity("Auml", 196);
addCharEntity("Aring", 197);
addCharEntity("AElig", 198);
addCharEntity("Ccedil", 199);
addCharEntity("Egrave", 200);
addCharEntity("Eacute", 201);
addCharEntity("Ecirc", 202);
addCharEntity("Euml", 203);
addCharEntity("Igrave", 204);
addCharEntity("Iacute", 205);
addCharEntity("Icirc", 206);
addCharEntity("Iuml", 207);
addCharEntity("ETH", 208);
addCharEntity("Ntilde", 209);
addCharEntity("Ograve", 210);
addCharEntity("Oacute", 211);
addCharEntity("Ocirc", 212);
addCharEntity("Otilde", 213);
addCharEntity("Ouml", 214);
addCharEntity("times", 215);
addCharEntity("Oslash", 216);
addCharEntity("Ugrave", 217);
addCharEntity("Uacute", 218);
addCharEntity("Ucirc", 219);
addCharEntity("Uuml", 220);
addCharEntity("Yacute", 221);
addCharEntity("THORN", 222);
addCharEntity("szlig", 223);
addCharEntity("agrave", 224);
addCharEntity("aacute", 225);
addCharEntity("acirc", 226);
addCharEntity("atilde", 227);
addCharEntity("auml", 228);
addCharEntity("aring", 229);
addCharEntity("aelig", 230);
addCharEntity("ccedil", 231);
addCharEntity("egrave", 232);
addCharEntity("eacute", 233);
addCharEntity("ecirc", 234);
addCharEntity("euml", 235);
addCharEntity("igrave", 236);
addCharEntity("iacute", 237);
addCharEntity("icirc", 238);
addCharEntity("iuml", 239);
addCharEntity("eth", 240);
addCharEntity("ntilde", 241);
addCharEntity("ograve", 242);
addCharEntity("oacute", 243);
addCharEntity("ocirc", 244);
addCharEntity("otilde", 245);
addCharEntity("ouml", 246);
addCharEntity("divide", 247);
addCharEntity("oslash", 248);
addCharEntity("ugrave", 249);
addCharEntity("uacute", 250);
addCharEntity("ucirc", 251);
addCharEntity("uuml", 252);
addCharEntity("yacute", 253);
addCharEntity("thorn", 254);
addCharEntity("yuml", 255);
}
}
| 26,590 | 0.475073 | 0.459659 | 1,004 | 25.492031 | 20.242723 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464143 | false | false |
15
|
d2fd9a0b34ed23b9e2dd3646748fa30b23688f61
| 35,708,358,139,126 |
8ab9b4653882b67eda89877545c1b2d83af40828
|
/customer-site/cs-webapp/src/main/java/com/pentalog/us/service/ProductFeatureService.java
|
963f03c3be5674cb814cba7ec29a45940602556f
|
[] |
no_license
|
pentastagiu/modul_4
|
https://github.com/pentastagiu/modul_4
|
610474a557af95037dff275bfb7386089f233f8f
|
0ceda9d6489e7e272d098494898147d8abb6016c
|
refs/heads/master
| 2021-01-23T07:03:46.325000 | 2015-07-27T07:35:13 | 2015-07-27T07:35:13 | 37,610,750 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pentalog.us.service;
import java.util.List;
import java.util.Map;
import com.pentalog.us.model.Product;
import com.pentalog.us.model.ProductFeature;
/**
* The product feature service
* @authors acozma and bpopovici
*
*/
public interface ProductFeatureService {
/**
* Method that get product feature by id
* @param id
* @return
*/
ProductFeature getProductFeatureById(int id);
/**
* Method that get product features
* @return
*/
List<ProductFeature> getProductFeatures();
/**
* Method that put product feature
* @param productFeature
*/
void putProductFeature(ProductFeature productFeature);
/**
* Method that post product feature
* @param productFeature
*/
void postProductFeature(ProductFeature productFeature);
/**
* Method that delete product feature
* @param productFeature
*/
void deleteProductFeature(ProductFeature productFeature);
public Map<String, List<ProductFeature>> getProductFeatureByProductId(Product product);
}
|
UTF-8
|
Java
| 1,003 |
java
|
ProductFeatureService.java
|
Java
|
[
{
"context": "e;\n\n/**\n * The product feature service\n * @authors acozma and bpopovici\n *\n */\npublic interface ProductFeat",
"end": 217,
"score": 0.9993611574172974,
"start": 211,
"tag": "USERNAME",
"value": "acozma"
},
{
"context": "The product feature service\n * @authors acozma and bpopovici\n *\n */\npublic interface ProductFeatureService {\t\n",
"end": 231,
"score": 0.9992048740386963,
"start": 222,
"tag": "USERNAME",
"value": "bpopovici"
}
] | null |
[] |
package com.pentalog.us.service;
import java.util.List;
import java.util.Map;
import com.pentalog.us.model.Product;
import com.pentalog.us.model.ProductFeature;
/**
* The product feature service
* @authors acozma and bpopovici
*
*/
public interface ProductFeatureService {
/**
* Method that get product feature by id
* @param id
* @return
*/
ProductFeature getProductFeatureById(int id);
/**
* Method that get product features
* @return
*/
List<ProductFeature> getProductFeatures();
/**
* Method that put product feature
* @param productFeature
*/
void putProductFeature(ProductFeature productFeature);
/**
* Method that post product feature
* @param productFeature
*/
void postProductFeature(ProductFeature productFeature);
/**
* Method that delete product feature
* @param productFeature
*/
void deleteProductFeature(ProductFeature productFeature);
public Map<String, List<ProductFeature>> getProductFeatureByProductId(Product product);
}
| 1,003 | 0.735793 | 0.735793 | 48 | 19.916666 | 20.6507 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.958333 | false | false |
15
|
807c2ce734a7188dfd27d3a73554d116d4e2ccd1
| 35,605,278,920,251 |
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/9/9_3b3adae15d48b49fcf388182e96577918acc2e32/GenericGraphImplTest/9_3b3adae15d48b49fcf388182e96577918acc2e32_GenericGraphImplTest_t.java
|
a6eef8eb97083d51e4578b2b82ae713ce991f84c
|
[] |
no_license
|
zhongxingyu/Seer
|
https://github.com/zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false |
package de.uni_koblenz.jgralabtest.genericimpltest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.Test;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.GraphException;
import de.uni_koblenz.jgralab.GraphIO;
import de.uni_koblenz.jgralab.GraphIOException;
import de.uni_koblenz.jgralab.ImplementationType;
import de.uni_koblenz.jgralab.JGraLab;
import de.uni_koblenz.jgralab.NoSuchAttributeException;
import de.uni_koblenz.jgralab.Record;
import de.uni_koblenz.jgralab.TraversalContext;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.impl.RecordImpl;
import de.uni_koblenz.jgralab.impl.generic.GenericEdgeImpl;
import de.uni_koblenz.jgralab.impl.generic.GenericGraphImpl;
import de.uni_koblenz.jgralab.impl.generic.GenericVertexImpl;
import de.uni_koblenz.jgralab.schema.Attribute;
import de.uni_koblenz.jgralab.schema.AttributedElementClass;
import de.uni_koblenz.jgralab.schema.EdgeClass;
import de.uni_koblenz.jgralab.schema.EnumDomain;
import de.uni_koblenz.jgralab.schema.RecordDomain;
import de.uni_koblenz.jgralab.schema.Schema;
import de.uni_koblenz.jgralab.schema.VertexClass;
public class GenericGraphImplTest {
public static final String SCHEMAFOLDER = "testit" + File.separator
+ "testschemas" + File.separator;
public static final String GRAPHFOLDER = "testit" + File.separator
+ "testgraphs" + File.separator;
public static final String DATAFOLDER = "testit" + File.separator
+ "testdata" + File.separator;
/**
* Tests, if an graph/vertex/edge of a generic <code>Graph</code> contains
* all its attributes, as defined by the corresponding
* {@link AttributedElementClass} in the <code>Graph</code>'s
* <code>Schema</code>.
*
* @param testObject
* A {@link GenericGraphImpl}, {@link GenericVertexImpl} or
* {@link GenericEdgeImpl} <code>Object</code>.
* @param aec
* The element of the <code>Schema</code>, representing the
* tested.
*/
private void testElementAttributes(Object testObject,
AttributedElementClass<?, ?> aec) {
try {
Field f = testObject.getClass().getDeclaredField("attributes");
f.setAccessible(true);
Map<?, ?> attributes = (Map<?, ?>) f.get(testObject);
if (attributes != null) {
assertEquals(aec.getAttributeCount(), attributes.size());
for (Attribute a : aec.getAttributeList()) {
assertTrue(attributes.containsKey(a.getName()));
}
} else {
assertEquals(0, aec.getAttributeCount());
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
fail();
} catch (SecurityException e) {
e.printStackTrace();
fail();
} catch (IllegalArgumentException e) {
e.printStackTrace();
fail();
} catch (IllegalAccessException e) {
e.printStackTrace();
fail();
}
}
/**
* Tests, if the value of an attribute in the generic TGraph implementation
* has the default value defined in its definition in the schema. If no
* explicit default value was defined, it tests, if the attribute's value
* corresponds to the general default value of its Domain.
*
* @param value
* @param attribute
*/
private void testDefaultValue(Object value, Attribute attribute) {
try {
if (attribute.getDefaultValueAsString() != null) {
Object expected = attribute.getDomain().parseGenericAttribute(
GraphIO.createStringReader(attribute
.getDefaultValueAsString(), attribute
.getAttributedElementClass().getSchema()));
assertEquals(expected, value);
} else {
assertEquals(
GenericGraphImpl.genericAttributeDefaultValue(attribute
.getDomain()), value);
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test creating a small graph without attributes (MinimalSchema.tg).
@Test
public void testCreateGraph1() {
try {
Schema schema;
schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
assertTrue(g instanceof GenericGraphImpl);
assertEquals(schema.getGraphClass(), g.getAttributedElementClass());
testElementAttributes(g, schema.getGraphClass());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test creating a graph with attributes that have explicitly defined
// default values in the schema (DefaultValueSchema.tg)
@Test
public void testCreateGraph2() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
assertTrue(g instanceof GenericGraphImpl);
assertEquals(schema.getGraphClass(), g.getAttributedElementClass());
testElementAttributes(g, schema.getGraphClass());
// Test if default values were set correctly
assertEquals(true, g.getAttribute("boolGraph"));
assertEquals(
JGraLab.vector().plus(JGraLab.vector().plus(true))
.plus(JGraLab.vector().plus(false))
.plus(JGraLab.vector().plus(true)),
g.getAttribute("complexListGraph"));
assertEquals(
JGraLab.map()
.plus(JGraLab.vector().plus(true),
JGraLab.set().plus(true))
.plus(JGraLab.vector().plus(false),
JGraLab.set().plus(false)),
g.getAttribute("complexMapGraph"));
assertEquals(
JGraLab.set().plus(JGraLab.set().plus(true))
.plus(JGraLab.set().plus(false)),
g.getAttribute("complexSetGraph"));
assertEquals(new Double(1.1), g.getAttribute("doubleGraph"));
assertEquals("FIRST", g.getAttribute("enumGraph"));
assertEquals(new Integer(1), g.getAttribute("intGraph"));
assertEquals(JGraLab.vector().plus(true).plus(false).plus(true),
g.getAttribute("listGraph"));
assertEquals(new Long(1), g.getAttribute("longGraph"));
assertEquals(
JGraLab.map().plus(1, true).plus(2, false).plus(3, true),
g.getAttribute("mapGraph"));
assertEquals(JGraLab.set().plus(true).plus(false),
g.getAttribute("setGraph"));
assertEquals("test", g.getAttribute("stringGraph"));
assertEquals(
de.uni_koblenz.jgralab.impl.RecordImpl
.empty()
.plus("boolRecord", true)
.plus("doubleRecord", new Double(1.1))
.plus("enumRecord", "FIRST")
.plus("intRecord", new Integer(1))
.plus("listRecord",
JGraLab.vector().plus(true).plus(false)
.plus(true))
.plus("longRecord", new Long(1))
.plus("mapRecord",
JGraLab.map().plus(1, true).plus(2, false)
.plus(3, true))
.plus("setRecord",
JGraLab.set().plus(true).plus(false))
.plus("stringRecord", "test"),
g.getAttribute("recordGraph"));
// Dynamic test to see if default values were set correctly
for (Attribute a : schema.getGraphClass().getAttributeList()) {
testDefaultValue(g.getAttribute(a.getName()), a);
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Creating generic vertices without attributes (MinimalSchema.tg - Node)
@Test
public void testCreateVertex1() {
try {
Schema schema;
schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
assertTrue(v1 instanceof GenericVertexImpl);
testElementAttributes(v1,
schema.getGraphClass().getVertexClass("Node"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
assertTrue(v2 instanceof GenericVertexImpl);
testElementAttributes(v2,
schema.getGraphClass().getVertexClass("Node"));
assertTrue(g.containsVertex(v1));
assertTrue(g.containsVertex(v2));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Create generic vertices with attributes (inherited ones and own ones)
// (DefaultValueTestSchema.tg)
@Test
public void testCreateVertex2() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"TestVertex"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"TestSubVertex")); // Vertex with inherited attributes
assertEquals(schema.getGraphClass().getVertexClass("TestVertex"),
v1.getAttributedElementClass());
assertEquals(
schema.getGraphClass().getVertexClass("TestSubVertex"),
v2.getAttributedElementClass());
testElementAttributes(v1, v1.getAttributedElementClass());
testElementAttributes(v2, v2.getAttributedElementClass());
for (Attribute a : schema.getGraphClass()
.getVertexClass("TestVertex").getAttributeList()) {
testDefaultValue(v1.getAttribute(a.getName()), a);
}
for (Attribute a : schema.getGraphClass()
.getVertexClass("TestSubVertex").getAttributeList()) {
testDefaultValue(v2.getAttribute(a.getName()), a);
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Create generic edges (1 attribute) (MinialSchema.tg)
@Test
public void testCreateEdge1() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
Edge e1 = g.createEdge(schema.getGraphClass().getEdgeClass("Link"),
v1, v2);
Edge e2 = g.createEdge(schema.getGraphClass().getEdgeClass("Link"),
v2, v1);
assertEquals(g.getSchema().getGraphClass().getEdgeClass("Link"),
e1.getAttributedElementClass());
assertEquals(g.getSchema().getGraphClass().getEdgeClass("Link"),
e2.getAttributedElementClass());
assertTrue(g.containsEdge(e1));
assertTrue(g.containsEdge(e2));
testElementAttributes(e1,
schema.getGraphClass().getEdgeClass("Link"));
testElementAttributes(e2,
schema.getGraphClass().getEdgeClass("Link"));
for (Attribute a : e1.getAttributedElementClass()
.getAttributeList()) {
testDefaultValue(e1.getAttribute(a.getName()), a);
}
for (Attribute a : e2.getAttributedElementClass()
.getAttributeList()) {
testDefaultValue(e1.getAttribute(a.getName()), a);
}
assertEquals(e1, v1.getFirstIncidence());
assertEquals(e2, e1.getNextEdge());
assertEquals(e2.getReversedEdge(), e1.getNextIncidence());
assertEquals(e1.getReversedEdge(), v2.getFirstIncidence());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Create generic edges with inherited attributes (VertexTestSchema.tg)
@Test
public void testCreateEdge2() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"SubNode"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"SuperNode"));
Vertex v3 = g.createVertex(schema.getGraphClass().getVertexClass(
"DoubleSubNode"));
Edge e1 = g.createEdge(schema.getGraphClass().getEdgeClass("Link"),
v1, v2);
assertEquals(schema.getGraphClass().getEdgeClass("Link"),
e1.getAttributedElementClass());
testElementAttributes(e1, e1.getAttributedElementClass());
testDefaultValue(e1.getAttribute("aString"), e1
.getAttributedElementClass().getAttribute("aString"));
// Edge with inherited attributes
Edge e2 = g.createEdge(
schema.getGraphClass().getEdgeClass("SubLink"), v3, v2);
assertEquals(schema.getGraphClass().getEdgeClass("SubLink"),
e2.getAttributedElementClass());
testElementAttributes(e2, e2.getAttributedElementClass());
testDefaultValue(e2.getAttribute("anInt"), e2
.getAttributedElementClass().getAttribute("anInt"));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test if deletion works with the generic implementation
@Test
public void testDeleteEdge() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"DoubleSubNode"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"SuperNode"));
Edge e1 = g.createEdge(
schema.getGraphClass().getEdgeClass("SubLink"), v1, v2);
Edge e2 = g.createEdge(
schema.getGraphClass().getEdgeClass("LinkBack"), v2, v1);
g.deleteEdge(e1);
assertFalse(g.containsEdge(e1));
assertTrue(g.containsVertex(v2));
assertTrue(g.containsEdge(e2));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test if deletion works with the generic implementation
@Test
public void testDeleteVertex() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"DoubleSubNode"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"SuperNode"));
Edge e1 = g.createEdge(
schema.getGraphClass().getEdgeClass("SubLink"), v1, v2);
Edge e2 = g.createEdge(
schema.getGraphClass().getEdgeClass("LinkBack"), v2, v1);
g.deleteVertex(v1);
assertFalse(g.containsEdge(e1));
assertFalse(g.containsVertex(v2));
assertFalse(g.containsEdge(e2));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// EdgeClass is from a different schema
@Test(expected = GraphException.class)
public void testCreateEdgeFailure1() {
Graph g1 = null;
try {
// both schemas contain an EdgeClass named "Link"
Schema schema1 = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Schema schema2 = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "jnitestschema.tg");
g1 = schema1.createGraph(ImplementationType.GENERIC);
Vertex v1 = g1.createVertex(schema1.getGraphClass().getVertexClass(
"Node"));
Vertex v2 = g1.createVertex(schema1.getGraphClass().getVertexClass(
"Node"));
// Error: EdgeClass is from schema2
g1.createEdge(schema2.getGraphClass().getEdgeClass("Link"), v1, v2);
} catch (GraphIOException e) {
e.printStackTrace();
fail();
} catch (GraphException e) {
// Test if there has no edge been added to the graph
if (0 == g1.getECount()) {
throw e;
}
}
}
// EdgeClass is not defined between the connected nodes' VertexClasses
@Test(expected = GraphException.class)
public void testCreateEdgeFailure2() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "greqltestschema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"localities.Village"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"localities.Village"));
g.createEdge(
schema.getGraphClass().getEdgeClass("connections.Street"),
v1, v2);
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// The IncidenceClass is redefined and therefore not allowed
// (VertexTestSChema.tg)
@Test(expected = GraphException.class)
public void testCreateEdgeFailure3() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"C2"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"D2"));
// this Edge should not be allowed => GraphException
g.createEdge(schema.getGraphClass().getEdgeClass("E"), v1, v2);
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// VertexClass is from a different Schema
@Test(expected = GraphException.class)
public void testCreateVertexFailure1() {
Graph g1 = null;
try {
Schema citimapschema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "citymapschema.tg");
Schema greqltestschema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "greqltestschema.tg");
g1 = citimapschema.createGraph(ImplementationType.GENERIC);
g1.createVertex(greqltestschema.getGraphClass().getVertexClass(
"junctions.Crossroad"));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
} catch (GraphException e) {
if (0 == g1.getVCount()) {
throw e;
}
}
}
// Test setting a TraversalContext (greqltestgraph.tg)
public void testSetTraversalContext() {
try {
final Graph g = GraphIO.loadGraphFromFile(GRAPHFOLDER
+ "greqltestgraph.tg", ImplementationType.GENERIC, null);
g.setTraversalContext(new TraversalContext() {
@Override
public boolean containsVertex(Vertex v) {
return v.getAttributedElementClass().equals(
g.getGraphClass().getVertexClass("Crossroad"));
}
@Override
public boolean containsEdge(Edge e) {
return e.getAttributedElementClass().equals(
g.getGraphClass().getEdgeClass("Street"));
}
});
for (Vertex v : g.vertices()) {
assertEquals(g.getGraphClass().getVertexClass("Crossroad"),
v.getAttributedElementClass());
}
for (Edge e : g.edges()) {
assertEquals(g.getGraphClass().getEdgeClass("Street"),
e.getAttributedElementClass());
}
g.setTraversalContext(new TraversalContext() {
@Override
public boolean containsVertex(Vertex v) {
return g.getGraphClass().getVertexClass("Plaza")
.equals(v.getAttributedElementClass());
}
@Override
public boolean containsEdge(Edge e) {
return false;
}
});
for (Vertex v : g.vertices()) {
assertEquals(g.getGraphClass().getVertexClass("Plaza"),
v.getAttributedElementClass());
}
assertNull(g.getFirstEdge());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test setting and accessing a graph's attributes
@Test
public void testAccessAttributes1() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
testDefaultValue(g.getAttribute("boolGraph"), g.getGraphClass()
.getAttribute("boolGraph"));
g.setAttribute("boolGraph", false);
assertEquals(false, g.getAttribute("boolGraph"));
testDefaultValue(g.getAttribute("listGraph"), g.getGraphClass()
.getAttribute("listGraph"));
g.setAttribute("listGraph", JGraLab.vector().plus(true).plus(true)
.plus(false));
assertEquals(JGraLab.vector().plus(true).plus(true).plus(false),
g.getAttribute("listGraph"));
g.setAttribute("listGraph", null);
assertEquals(null, g.getAttribute("listGraph"));
g.setAttribute(
"complexListGraph",
JGraLab.vector().plus(JGraLab.vector().plus(true))
.plus(JGraLab.vector().plus(false))
.plus(JGraLab.vector().plus(false)));
assertEquals(
JGraLab.vector().plus(JGraLab.vector().plus(true))
.plus(JGraLab.vector().plus(false))
.plus(JGraLab.vector().plus(false)),
g.getAttribute("complexListGraph"));
RecordImpl r = (RecordImpl) g.getAttribute("recordGraph");
r = r.plus("stringRecord", null);
r = r.plus("listRecord", null);
r = r.plus("setRecord", null);
r = r.plus("mapRecord", null);
g.setAttribute("recordGraph", r);
assertNull(r.getComponent("stringRecord"));
assertNull(r.getComponent("listRecord"));
assertNull(r.getComponent("setRecord"));
assertNull(r.getComponent("mapRecord"));
}
// Test setting attributes that don't exist. NoSuchAttributeException is
// expected.
@Test(expected = NoSuchAttributeException.class)
public void testAccessAttributesFailure1() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
g.setAttribute("doesNotExist", true);
}
@Test(expected = NoSuchAttributeException.class)
public void testAccessAttributesFailure2() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
g.setAttribute("boolgraph", true); // the actual attribute's name is
// written in CamelCase
}
// Test setting attribute values of a wrong domain. A ClassCastException is
// expected.
@Test(expected = ClassCastException.class)
public void testAccessAttributesFailure3() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
g.setAttribute("boolGraph", JGraLab.set().plus(1));
}
// Test setting attribute values of a wrong domain. A ClassCastException is
// expected.
@Test(expected = ClassCastException.class)
public void testAccessAttributesFailure4() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
g.setAttribute("boolGraph", null);
}
// Test type-specific iteration over vertices (VertexTestSchema.tg)
// This test requires the type-specific getNextVertex()/getNextEdge()
// methods of the GenericVertexImpl/EdgeImpl classes, as the iterators
// use them.
@Test
public void testVertexIteration() {
try {
Schema s = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = s.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(s.getGraphClass().getVertexClass("A"));
Vertex v2 = g.createVertex(s.getGraphClass().getVertexClass("A"));
Vertex v3 = g.createVertex(s.getGraphClass().getVertexClass("B"));
Vertex v4 = g.createVertex(s.getGraphClass().getVertexClass("B"));
Vertex v5 = g.createVertex(s.getGraphClass().getVertexClass("C"));
Vertex v6 = g.createVertex(s.getGraphClass().getVertexClass("C"));
Vertex v7 = g.createVertex(s.getGraphClass().getVertexClass("D"));
Vertex v8 = g.createVertex(s.getGraphClass().getVertexClass("D"));
Vertex v9 = g.createVertex(s.getGraphClass().getVertexClass("C2"));
Vertex v10 = g.createVertex(s.getGraphClass().getVertexClass("C2"));
assertNull(g.getFirstVertex(s.getGraphClass().getVertexClass("D2")));
assertEquals(v1,
g.getFirstVertex(s.getGraphClass().getVertexClass("A")));
assertEquals(v3,
g.getFirstVertex(s.getGraphClass().getVertexClass("B")));
assertEquals(v5,
g.getFirstVertex(s.getGraphClass().getVertexClass("C")));
assertEquals(v7,
g.getFirstVertex(s.getGraphClass().getVertexClass("D")));
assertEquals(v9,
g.getFirstVertex(s.getGraphClass().getVertexClass("C2")));
Vertex v11 = g.createVertex(s.getGraphClass().getVertexClass("D2"));
Vertex v12 = g.createVertex(s.getGraphClass().getVertexClass("D2"));
Vertex[] aTest = new Vertex[] { v1, v2, v5, v6, v9, v10 };
Vertex[] bTest = new Vertex[] { v3, v4, v7, v8, v11, v12 };
Vertex[] cTest = new Vertex[] { v5, v6, v9, v10 };
Vertex[] dTest = new Vertex[] { v7, v8, v11, v12 };
Vertex[] c2Test = new Vertex[] { v9, v10 };
Vertex[] d2Test = new Vertex[] { v11, v12 };
int i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("A"))) {
assertEquals(aTest[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("B"))) {
assertEquals(bTest[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("C"))) {
assertEquals(cTest[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("D"))) {
assertEquals(dTest[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("C2"))) {
assertEquals(c2Test[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("D2"))) {
assertEquals(d2Test[i], v);
i++;
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test type-specific iteration over edges (VertexTestSchema.tg)
@Test
public void testEdgeIteration() {
try {
Schema s = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = s.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(s.getGraphClass().getVertexClass("A"));
Vertex v2 = g.createVertex(s.getGraphClass().getVertexClass("A"));
Vertex v3 = g.createVertex(s.getGraphClass().getVertexClass("B"));
Vertex v4 = g.createVertex(s.getGraphClass().getVertexClass("B"));
Vertex v5 = g.createVertex(s.getGraphClass().getVertexClass("C"));
Vertex v6 = g.createVertex(s.getGraphClass().getVertexClass("C"));
Vertex v7 = g.createVertex(s.getGraphClass().getVertexClass("D"));
Vertex v8 = g.createVertex(s.getGraphClass().getVertexClass("D"));
Edge e1 = g.createEdge(s.getGraphClass().getEdgeClass("E"), v1, v3);
Edge e2 = g.createEdge(s.getGraphClass().getEdgeClass("E"), v2, v4);
Edge e3 = g.createEdge(s.getGraphClass().getEdgeClass("F"), v5, v7);
Edge e4 = g.createEdge(s.getGraphClass().getEdgeClass("F"), v6, v8);
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("G")));
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("H")));
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("I")));
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("J")));
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("K")));
Edge e5 = g.createEdge(s.getGraphClass().getEdgeClass("G"), v5, v8);
Edge e6 = g.createEdge(s.getGraphClass().getEdgeClass("G"), v6, v7);
Edge e7 = g.createEdge(s.getGraphClass().getEdgeClass("H"), v1, v7);
Edge e8 = g.createEdge(s.getGraphClass().getEdgeClass("H"), v2, v8);
Edge[] eTest = new Edge[] { e1, e2, e3, e4, e5, e6, e7, e8 };
Edge[] fTest = new Edge[] { e3, e4 };
Edge[] gTest = new Edge[] { e5, e6 };
Edge[] hTest = new Edge[] { e7, e8 };
int i = 0;
for (Edge e : g.edges(s.getGraphClass().getEdgeClass("E"))) {
assertEquals(eTest[i], e);
i++;
}
i = 0;
for (Edge e : g.edges(s.getGraphClass().getEdgeClass("F"))) {
assertEquals(fTest[i], e);
i++;
}
i = 0;
for (Edge e : g.edges(s.getGraphClass().getEdgeClass("G"))) {
assertEquals(gTest[i], e);
i++;
}
i = 0;
for (Edge e : g.edges(s.getGraphClass().getEdgeClass("H"))) {
assertEquals(hTest[i], e);
i++;
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testSave() {
try {
Schema schema;
schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
g.createEdge(schema.getGraphClass().getEdgeClass("Link"), v1, v2);
g.createEdge(schema.getGraphClass().getEdgeClass("Link"), v2, v1);
g.save(DATAFOLDER + "GenericTestGraph1.tg");
Graph g2 = GraphIO.loadGraphFromFile(DATAFOLDER
+ "GenericTestGraph1.tg", schema,
ImplementationType.GENERIC, null);
Iterator<Vertex> vertexIterator1 = g.vertices().iterator();
Iterator<Vertex> vertexIterator2 = g2.vertices().iterator();
Iterator<Edge> edgeIterator1 = g.edges().iterator();
Iterator<Edge> edgeIterator2 = g2.edges().iterator();
while (vertexIterator1.hasNext()) {
Vertex vg1 = vertexIterator1.next();
Vertex vg2 = vertexIterator2.next();
assertEquals(vg1.getId(), vg2.getId());
assertEquals(vg1.getAttributedElementClass(),
vg2.getAttributedElementClass());
}
assertFalse(vertexIterator2.hasNext());
while (edgeIterator1.hasNext()) {
Edge eg1 = edgeIterator1.next();
Edge eg2 = edgeIterator2.next();
assertEquals(eg1.getId(), eg2.getId());
assertEquals(eg2.getAttributedElementClass(),
eg2.getAttributedElementClass());
}
assertFalse(edgeIterator2.hasNext());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test loading a graph (tested statically against a saved graph)
@Test
public void testLoadGraph1() {
// Static test relies on an unchanged graph in the file!
try {
Schema s = GraphIO.loadSchemaFromFile(GRAPHFOLDER
+ "citymapgraph.tg");
Graph g = GraphIO.loadGraphFromFile(
GRAPHFOLDER + "citymapgraph.tg", s,
ImplementationType.GENERIC, null);
assertEquals(8, g.getVCount());
assertEquals(11, g.getECount());
// Check types
VertexClass intersection = g.getSchema().getGraphClass()
.getVertexClass("Intersection");
VertexClass carPark = g.getSchema().getGraphClass()
.getVertexClass("CarPark");
EdgeClass street = g.getSchema().getGraphClass()
.getEdgeClass("Street");
EdgeClass bridge = g.getSchema().getGraphClass()
.getEdgeClass("Bridge");
Vertex[] vertices = new Vertex[8];
for (int i = 0; i < 8; i++) {
vertices[i] = g.getVertex(i + 1);
}
Edge[] edges = new Edge[11];
for (int i = 0; i < 11; i++) {
edges[i] = g.getEdge(i + 1);
}
assertEquals(vertices[0].getAttributedElementClass(), intersection);
assertEquals(vertices[1].getAttributedElementClass(), intersection);
assertEquals(vertices[2].getAttributedElementClass(), carPark);
assertEquals(vertices[3].getAttributedElementClass(), intersection);
assertEquals(vertices[4].getAttributedElementClass(), intersection);
assertEquals(vertices[5].getAttributedElementClass(), intersection);
assertEquals(vertices[6].getAttributedElementClass(), carPark);
assertEquals(vertices[7].getAttributedElementClass(), carPark);
assertEquals(edges[0].getAttributedElementClass(), street);
assertEquals(edges[1].getAttributedElementClass(), street);
assertEquals(edges[2].getAttributedElementClass(), street);
assertEquals(edges[3].getAttributedElementClass(), street);
assertEquals(edges[4].getAttributedElementClass(), bridge);
assertEquals(edges[5].getAttributedElementClass(), street);
assertEquals(edges[6].getAttributedElementClass(), street);
assertEquals(edges[7].getAttributedElementClass(), street);
assertEquals(edges[8].getAttributedElementClass(), bridge);
assertEquals(edges[9].getAttributedElementClass(), bridge);
assertEquals(edges[10].getAttributedElementClass(), street);
// Check attribute values
assertFalse((Boolean) vertices[0].getAttribute("roundabout"));
assertFalse((Boolean) vertices[1].getAttribute("roundabout"));
assertFalse((Boolean) vertices[3].getAttribute("roundabout"));
assertFalse((Boolean) vertices[4].getAttribute("roundabout"));
assertFalse((Boolean) vertices[5].getAttribute("roundabout"));
for (Vertex v : vertices) {
assertEquals(null, v.getAttribute("name"));
}
assertEquals(new Integer(2500),
vertices[2].getAttribute("capacity"));
assertEquals(new Integer(500), vertices[6].getAttribute("capacity"));
assertEquals(new Integer(500), vertices[7].getAttribute("capacity"));
for (int i = 0; i < edges.length; i++) {
assertFalse((Boolean) edges[i].getAttribute("oneway"));
assertEquals("e" + (i + 1), edges[i].getAttribute("name"));
assertEquals(0, edges[i].getAttribute("length"));
}
assertEquals(0, edges[4].getAttribute("height"));
assertEquals(0, edges[8].getAttribute("height"));
assertEquals(0, edges[9].getAttribute("height"));
// Check incidences
assertEquals(2, vertices[0].getDegree());
assertEquals(edges[0], vertices[0].getFirstIncidence());
assertEquals(edges[2], vertices[0].getLastIncidence());
assertEquals(3, vertices[1].getDegree());
assertEquals(edges[0].getReversedEdge(),
vertices[1].getFirstIncidence());
assertEquals(edges[1], vertices[1].getFirstIncidence()
.getNextIncidence());
assertEquals(edges[3].getReversedEdge(),
vertices[1].getLastIncidence());
assertEquals(2, vertices[2].getDegree());
assertEquals(edges[1].getReversedEdge(),
vertices[2].getFirstIncidence());
assertEquals(edges[4], vertices[2].getLastIncidence());
assertEquals(3, vertices[3].getDegree());
assertEquals(edges[2].getReversedEdge(),
vertices[3].getFirstIncidence());
assertEquals(edges[5], vertices[3].getFirstIncidence()
.getNextIncidence());
assertEquals(edges[7], vertices[3].getLastIncidence());
assertEquals(4, vertices[4].getDegree());
assertEquals(edges[3], vertices[4].getFirstIncidence());
assertEquals(edges[5].getReversedEdge(), vertices[4]
.getFirstIncidence().getNextIncidence());
assertEquals(edges[6], vertices[4].getLastIncidence()
.getPrevIncidence());
assertEquals(edges[8], vertices[4].getLastIncidence());
assertEquals(3, vertices[5].getDegree());
assertEquals(edges[4].getReversedEdge(),
vertices[5].getFirstIncidence());
assertEquals(edges[6].getReversedEdge(), vertices[5]
.getFirstIncidence().getNextIncidence());
assertEquals(edges[9], vertices[5].getLastIncidence());
assertEquals(2, vertices[6].getDegree());
assertEquals(edges[7].getReversedEdge(),
vertices[6].getFirstIncidence());
assertEquals(edges[10], vertices[6].getLastIncidence());
assertEquals(3, vertices[7].getDegree());
assertEquals(edges[8].getReversedEdge(),
vertices[7].getFirstIncidence());
assertEquals(edges[9].getReversedEdge(), vertices[7]
.getFirstIncidence().getNextIncidence());
assertEquals(edges[10].getReversedEdge(),
vertices[7].getLastIncidence());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test loading the greqltestgraph.tg-file
@Test
public void testLoadGraph2() {
try {
Schema s = GraphIO.loadSchemaFromFile(GRAPHFOLDER
+ "greqltestgraph.tg");
Graph g1 = GraphIO.loadGraphFromFile(GRAPHFOLDER
+ "greqltestgraph.tg", s, ImplementationType.GENERIC, null);
assertEquals(s.getGraphClass(), g1.getAttributedElementClass());
assertEquals(157, g1.getVCount());
assertEquals(357, g1.getECount());
// compare against the same Graph loaded with the standard
// implementation
Graph g2 = GraphIO
.loadGraphFromFile(GRAPHFOLDER + "greqltestgraph.tg", s,
ImplementationType.STANDARD, null);
for (Vertex v : g2.vertices()) {
assertEquals(v.getAttributedElementClass(),
g1.getVertex(v.getId()).getAttributedElementClass());
// assert equality of attributes
for (Attribute a : v.getAttributedElementClass()
.getAttributeList()) {
try {
assertEquals(
v.writeAttributeValueToString(a.getName()),
g2.getVertex(v.getId())
.writeAttributeValueToString(
a.getName()));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
}
for (Edge edge : g2.edges()) {
assertEquals(edge.getAttributedElementClass(),
g1.getEdge(edge.getId()).getAttributedElementClass());
// assert equality of attributes
for (Attribute a : edge.getAttributedElementClass()
.getAttributeList()) {
try {
assertEquals(edge.writeAttributeValueToString(a
.getName()), g2.getEdge(edge.getId())
.writeAttributeValueToString(a.getName()));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testCreateRecord() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
RecordDomain testRecordDomain = (RecordDomain) schema
.getDomain("TestRecordDomain");
Map<String, Object> values = new HashMap<String, Object>();
Boolean boolRecord = Boolean.FALSE;
Double doubleRecord = Double.valueOf(0.123d);
String enumRecord = "SECOND";
Integer intRecord = Integer.valueOf(42);
List<?> listRecord = JGraLab.vector().plus(true).plus(false);
Long longRecord = Long.valueOf(9876543210l);
Map<?, ?> mapRecord = JGraLab.map().plus(1, true).plus(2, false);
Set<?> setRecord = JGraLab.set().plus(true).plus(false);
String stringRecord = "some string";
values.put("boolRecord", boolRecord);
values.put("doubleRecord", doubleRecord);
values.put("enumRecord", enumRecord);
values.put("intRecord", intRecord);
values.put("listRecord", listRecord);
values.put("longRecord", longRecord);
values.put("mapRecord", mapRecord);
values.put("setRecord", setRecord);
values.put("stringRecord", stringRecord);
Record r = g.createRecord(testRecordDomain, values);
for (String componentName : values.keySet()) {
assertEquals(values.get(componentName),
r.getComponent(componentName));
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testGetEnumConstant() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
EnumDomain testEnumDomain = (EnumDomain) schema
.getDomain("TestEnumDomain");
for (String c : testEnumDomain.getConsts()) {
assertEquals(c, g.getEnumConstant(testEnumDomain, c));
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@Test(expected = GraphException.class)
public void testGetEnumConstantFailure() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
EnumDomain testEnumDomain = (EnumDomain) schema
.getDomain("TestEnumDomain");
g.getEnumConstant(testEnumDomain, "FOURTH");
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@AfterClass
public static void cleanup() {
File f = new File(DATAFOLDER + "GenericTestGraph1.tg");
f.delete();
}
}
|
UTF-8
|
Java
| 39,730 |
java
|
9_3b3adae15d48b49fcf388182e96577918acc2e32_GenericGraphImplTest_t.java
|
Java
|
[] | null |
[] |
package de.uni_koblenz.jgralabtest.genericimpltest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.Test;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.GraphException;
import de.uni_koblenz.jgralab.GraphIO;
import de.uni_koblenz.jgralab.GraphIOException;
import de.uni_koblenz.jgralab.ImplementationType;
import de.uni_koblenz.jgralab.JGraLab;
import de.uni_koblenz.jgralab.NoSuchAttributeException;
import de.uni_koblenz.jgralab.Record;
import de.uni_koblenz.jgralab.TraversalContext;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.impl.RecordImpl;
import de.uni_koblenz.jgralab.impl.generic.GenericEdgeImpl;
import de.uni_koblenz.jgralab.impl.generic.GenericGraphImpl;
import de.uni_koblenz.jgralab.impl.generic.GenericVertexImpl;
import de.uni_koblenz.jgralab.schema.Attribute;
import de.uni_koblenz.jgralab.schema.AttributedElementClass;
import de.uni_koblenz.jgralab.schema.EdgeClass;
import de.uni_koblenz.jgralab.schema.EnumDomain;
import de.uni_koblenz.jgralab.schema.RecordDomain;
import de.uni_koblenz.jgralab.schema.Schema;
import de.uni_koblenz.jgralab.schema.VertexClass;
public class GenericGraphImplTest {
public static final String SCHEMAFOLDER = "testit" + File.separator
+ "testschemas" + File.separator;
public static final String GRAPHFOLDER = "testit" + File.separator
+ "testgraphs" + File.separator;
public static final String DATAFOLDER = "testit" + File.separator
+ "testdata" + File.separator;
/**
* Tests, if an graph/vertex/edge of a generic <code>Graph</code> contains
* all its attributes, as defined by the corresponding
* {@link AttributedElementClass} in the <code>Graph</code>'s
* <code>Schema</code>.
*
* @param testObject
* A {@link GenericGraphImpl}, {@link GenericVertexImpl} or
* {@link GenericEdgeImpl} <code>Object</code>.
* @param aec
* The element of the <code>Schema</code>, representing the
* tested.
*/
private void testElementAttributes(Object testObject,
AttributedElementClass<?, ?> aec) {
try {
Field f = testObject.getClass().getDeclaredField("attributes");
f.setAccessible(true);
Map<?, ?> attributes = (Map<?, ?>) f.get(testObject);
if (attributes != null) {
assertEquals(aec.getAttributeCount(), attributes.size());
for (Attribute a : aec.getAttributeList()) {
assertTrue(attributes.containsKey(a.getName()));
}
} else {
assertEquals(0, aec.getAttributeCount());
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
fail();
} catch (SecurityException e) {
e.printStackTrace();
fail();
} catch (IllegalArgumentException e) {
e.printStackTrace();
fail();
} catch (IllegalAccessException e) {
e.printStackTrace();
fail();
}
}
/**
* Tests, if the value of an attribute in the generic TGraph implementation
* has the default value defined in its definition in the schema. If no
* explicit default value was defined, it tests, if the attribute's value
* corresponds to the general default value of its Domain.
*
* @param value
* @param attribute
*/
private void testDefaultValue(Object value, Attribute attribute) {
try {
if (attribute.getDefaultValueAsString() != null) {
Object expected = attribute.getDomain().parseGenericAttribute(
GraphIO.createStringReader(attribute
.getDefaultValueAsString(), attribute
.getAttributedElementClass().getSchema()));
assertEquals(expected, value);
} else {
assertEquals(
GenericGraphImpl.genericAttributeDefaultValue(attribute
.getDomain()), value);
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test creating a small graph without attributes (MinimalSchema.tg).
@Test
public void testCreateGraph1() {
try {
Schema schema;
schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
assertTrue(g instanceof GenericGraphImpl);
assertEquals(schema.getGraphClass(), g.getAttributedElementClass());
testElementAttributes(g, schema.getGraphClass());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test creating a graph with attributes that have explicitly defined
// default values in the schema (DefaultValueSchema.tg)
@Test
public void testCreateGraph2() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
assertTrue(g instanceof GenericGraphImpl);
assertEquals(schema.getGraphClass(), g.getAttributedElementClass());
testElementAttributes(g, schema.getGraphClass());
// Test if default values were set correctly
assertEquals(true, g.getAttribute("boolGraph"));
assertEquals(
JGraLab.vector().plus(JGraLab.vector().plus(true))
.plus(JGraLab.vector().plus(false))
.plus(JGraLab.vector().plus(true)),
g.getAttribute("complexListGraph"));
assertEquals(
JGraLab.map()
.plus(JGraLab.vector().plus(true),
JGraLab.set().plus(true))
.plus(JGraLab.vector().plus(false),
JGraLab.set().plus(false)),
g.getAttribute("complexMapGraph"));
assertEquals(
JGraLab.set().plus(JGraLab.set().plus(true))
.plus(JGraLab.set().plus(false)),
g.getAttribute("complexSetGraph"));
assertEquals(new Double(1.1), g.getAttribute("doubleGraph"));
assertEquals("FIRST", g.getAttribute("enumGraph"));
assertEquals(new Integer(1), g.getAttribute("intGraph"));
assertEquals(JGraLab.vector().plus(true).plus(false).plus(true),
g.getAttribute("listGraph"));
assertEquals(new Long(1), g.getAttribute("longGraph"));
assertEquals(
JGraLab.map().plus(1, true).plus(2, false).plus(3, true),
g.getAttribute("mapGraph"));
assertEquals(JGraLab.set().plus(true).plus(false),
g.getAttribute("setGraph"));
assertEquals("test", g.getAttribute("stringGraph"));
assertEquals(
de.uni_koblenz.jgralab.impl.RecordImpl
.empty()
.plus("boolRecord", true)
.plus("doubleRecord", new Double(1.1))
.plus("enumRecord", "FIRST")
.plus("intRecord", new Integer(1))
.plus("listRecord",
JGraLab.vector().plus(true).plus(false)
.plus(true))
.plus("longRecord", new Long(1))
.plus("mapRecord",
JGraLab.map().plus(1, true).plus(2, false)
.plus(3, true))
.plus("setRecord",
JGraLab.set().plus(true).plus(false))
.plus("stringRecord", "test"),
g.getAttribute("recordGraph"));
// Dynamic test to see if default values were set correctly
for (Attribute a : schema.getGraphClass().getAttributeList()) {
testDefaultValue(g.getAttribute(a.getName()), a);
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Creating generic vertices without attributes (MinimalSchema.tg - Node)
@Test
public void testCreateVertex1() {
try {
Schema schema;
schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
assertTrue(v1 instanceof GenericVertexImpl);
testElementAttributes(v1,
schema.getGraphClass().getVertexClass("Node"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
assertTrue(v2 instanceof GenericVertexImpl);
testElementAttributes(v2,
schema.getGraphClass().getVertexClass("Node"));
assertTrue(g.containsVertex(v1));
assertTrue(g.containsVertex(v2));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Create generic vertices with attributes (inherited ones and own ones)
// (DefaultValueTestSchema.tg)
@Test
public void testCreateVertex2() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"TestVertex"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"TestSubVertex")); // Vertex with inherited attributes
assertEquals(schema.getGraphClass().getVertexClass("TestVertex"),
v1.getAttributedElementClass());
assertEquals(
schema.getGraphClass().getVertexClass("TestSubVertex"),
v2.getAttributedElementClass());
testElementAttributes(v1, v1.getAttributedElementClass());
testElementAttributes(v2, v2.getAttributedElementClass());
for (Attribute a : schema.getGraphClass()
.getVertexClass("TestVertex").getAttributeList()) {
testDefaultValue(v1.getAttribute(a.getName()), a);
}
for (Attribute a : schema.getGraphClass()
.getVertexClass("TestSubVertex").getAttributeList()) {
testDefaultValue(v2.getAttribute(a.getName()), a);
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Create generic edges (1 attribute) (MinialSchema.tg)
@Test
public void testCreateEdge1() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
Edge e1 = g.createEdge(schema.getGraphClass().getEdgeClass("Link"),
v1, v2);
Edge e2 = g.createEdge(schema.getGraphClass().getEdgeClass("Link"),
v2, v1);
assertEquals(g.getSchema().getGraphClass().getEdgeClass("Link"),
e1.getAttributedElementClass());
assertEquals(g.getSchema().getGraphClass().getEdgeClass("Link"),
e2.getAttributedElementClass());
assertTrue(g.containsEdge(e1));
assertTrue(g.containsEdge(e2));
testElementAttributes(e1,
schema.getGraphClass().getEdgeClass("Link"));
testElementAttributes(e2,
schema.getGraphClass().getEdgeClass("Link"));
for (Attribute a : e1.getAttributedElementClass()
.getAttributeList()) {
testDefaultValue(e1.getAttribute(a.getName()), a);
}
for (Attribute a : e2.getAttributedElementClass()
.getAttributeList()) {
testDefaultValue(e1.getAttribute(a.getName()), a);
}
assertEquals(e1, v1.getFirstIncidence());
assertEquals(e2, e1.getNextEdge());
assertEquals(e2.getReversedEdge(), e1.getNextIncidence());
assertEquals(e1.getReversedEdge(), v2.getFirstIncidence());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Create generic edges with inherited attributes (VertexTestSchema.tg)
@Test
public void testCreateEdge2() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"SubNode"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"SuperNode"));
Vertex v3 = g.createVertex(schema.getGraphClass().getVertexClass(
"DoubleSubNode"));
Edge e1 = g.createEdge(schema.getGraphClass().getEdgeClass("Link"),
v1, v2);
assertEquals(schema.getGraphClass().getEdgeClass("Link"),
e1.getAttributedElementClass());
testElementAttributes(e1, e1.getAttributedElementClass());
testDefaultValue(e1.getAttribute("aString"), e1
.getAttributedElementClass().getAttribute("aString"));
// Edge with inherited attributes
Edge e2 = g.createEdge(
schema.getGraphClass().getEdgeClass("SubLink"), v3, v2);
assertEquals(schema.getGraphClass().getEdgeClass("SubLink"),
e2.getAttributedElementClass());
testElementAttributes(e2, e2.getAttributedElementClass());
testDefaultValue(e2.getAttribute("anInt"), e2
.getAttributedElementClass().getAttribute("anInt"));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test if deletion works with the generic implementation
@Test
public void testDeleteEdge() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"DoubleSubNode"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"SuperNode"));
Edge e1 = g.createEdge(
schema.getGraphClass().getEdgeClass("SubLink"), v1, v2);
Edge e2 = g.createEdge(
schema.getGraphClass().getEdgeClass("LinkBack"), v2, v1);
g.deleteEdge(e1);
assertFalse(g.containsEdge(e1));
assertTrue(g.containsVertex(v2));
assertTrue(g.containsEdge(e2));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test if deletion works with the generic implementation
@Test
public void testDeleteVertex() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"DoubleSubNode"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"SuperNode"));
Edge e1 = g.createEdge(
schema.getGraphClass().getEdgeClass("SubLink"), v1, v2);
Edge e2 = g.createEdge(
schema.getGraphClass().getEdgeClass("LinkBack"), v2, v1);
g.deleteVertex(v1);
assertFalse(g.containsEdge(e1));
assertFalse(g.containsVertex(v2));
assertFalse(g.containsEdge(e2));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// EdgeClass is from a different schema
@Test(expected = GraphException.class)
public void testCreateEdgeFailure1() {
Graph g1 = null;
try {
// both schemas contain an EdgeClass named "Link"
Schema schema1 = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Schema schema2 = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "jnitestschema.tg");
g1 = schema1.createGraph(ImplementationType.GENERIC);
Vertex v1 = g1.createVertex(schema1.getGraphClass().getVertexClass(
"Node"));
Vertex v2 = g1.createVertex(schema1.getGraphClass().getVertexClass(
"Node"));
// Error: EdgeClass is from schema2
g1.createEdge(schema2.getGraphClass().getEdgeClass("Link"), v1, v2);
} catch (GraphIOException e) {
e.printStackTrace();
fail();
} catch (GraphException e) {
// Test if there has no edge been added to the graph
if (0 == g1.getECount()) {
throw e;
}
}
}
// EdgeClass is not defined between the connected nodes' VertexClasses
@Test(expected = GraphException.class)
public void testCreateEdgeFailure2() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "greqltestschema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"localities.Village"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"localities.Village"));
g.createEdge(
schema.getGraphClass().getEdgeClass("connections.Street"),
v1, v2);
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// The IncidenceClass is redefined and therefore not allowed
// (VertexTestSChema.tg)
@Test(expected = GraphException.class)
public void testCreateEdgeFailure3() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"C2"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"D2"));
// this Edge should not be allowed => GraphException
g.createEdge(schema.getGraphClass().getEdgeClass("E"), v1, v2);
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// VertexClass is from a different Schema
@Test(expected = GraphException.class)
public void testCreateVertexFailure1() {
Graph g1 = null;
try {
Schema citimapschema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "citymapschema.tg");
Schema greqltestschema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "greqltestschema.tg");
g1 = citimapschema.createGraph(ImplementationType.GENERIC);
g1.createVertex(greqltestschema.getGraphClass().getVertexClass(
"junctions.Crossroad"));
} catch (GraphIOException e) {
e.printStackTrace();
fail();
} catch (GraphException e) {
if (0 == g1.getVCount()) {
throw e;
}
}
}
// Test setting a TraversalContext (greqltestgraph.tg)
public void testSetTraversalContext() {
try {
final Graph g = GraphIO.loadGraphFromFile(GRAPHFOLDER
+ "greqltestgraph.tg", ImplementationType.GENERIC, null);
g.setTraversalContext(new TraversalContext() {
@Override
public boolean containsVertex(Vertex v) {
return v.getAttributedElementClass().equals(
g.getGraphClass().getVertexClass("Crossroad"));
}
@Override
public boolean containsEdge(Edge e) {
return e.getAttributedElementClass().equals(
g.getGraphClass().getEdgeClass("Street"));
}
});
for (Vertex v : g.vertices()) {
assertEquals(g.getGraphClass().getVertexClass("Crossroad"),
v.getAttributedElementClass());
}
for (Edge e : g.edges()) {
assertEquals(g.getGraphClass().getEdgeClass("Street"),
e.getAttributedElementClass());
}
g.setTraversalContext(new TraversalContext() {
@Override
public boolean containsVertex(Vertex v) {
return g.getGraphClass().getVertexClass("Plaza")
.equals(v.getAttributedElementClass());
}
@Override
public boolean containsEdge(Edge e) {
return false;
}
});
for (Vertex v : g.vertices()) {
assertEquals(g.getGraphClass().getVertexClass("Plaza"),
v.getAttributedElementClass());
}
assertNull(g.getFirstEdge());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test setting and accessing a graph's attributes
@Test
public void testAccessAttributes1() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
testDefaultValue(g.getAttribute("boolGraph"), g.getGraphClass()
.getAttribute("boolGraph"));
g.setAttribute("boolGraph", false);
assertEquals(false, g.getAttribute("boolGraph"));
testDefaultValue(g.getAttribute("listGraph"), g.getGraphClass()
.getAttribute("listGraph"));
g.setAttribute("listGraph", JGraLab.vector().plus(true).plus(true)
.plus(false));
assertEquals(JGraLab.vector().plus(true).plus(true).plus(false),
g.getAttribute("listGraph"));
g.setAttribute("listGraph", null);
assertEquals(null, g.getAttribute("listGraph"));
g.setAttribute(
"complexListGraph",
JGraLab.vector().plus(JGraLab.vector().plus(true))
.plus(JGraLab.vector().plus(false))
.plus(JGraLab.vector().plus(false)));
assertEquals(
JGraLab.vector().plus(JGraLab.vector().plus(true))
.plus(JGraLab.vector().plus(false))
.plus(JGraLab.vector().plus(false)),
g.getAttribute("complexListGraph"));
RecordImpl r = (RecordImpl) g.getAttribute("recordGraph");
r = r.plus("stringRecord", null);
r = r.plus("listRecord", null);
r = r.plus("setRecord", null);
r = r.plus("mapRecord", null);
g.setAttribute("recordGraph", r);
assertNull(r.getComponent("stringRecord"));
assertNull(r.getComponent("listRecord"));
assertNull(r.getComponent("setRecord"));
assertNull(r.getComponent("mapRecord"));
}
// Test setting attributes that don't exist. NoSuchAttributeException is
// expected.
@Test(expected = NoSuchAttributeException.class)
public void testAccessAttributesFailure1() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
g.setAttribute("doesNotExist", true);
}
@Test(expected = NoSuchAttributeException.class)
public void testAccessAttributesFailure2() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
g.setAttribute("boolgraph", true); // the actual attribute's name is
// written in CamelCase
}
// Test setting attribute values of a wrong domain. A ClassCastException is
// expected.
@Test(expected = ClassCastException.class)
public void testAccessAttributesFailure3() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
g.setAttribute("boolGraph", JGraLab.set().plus(1));
}
// Test setting attribute values of a wrong domain. A ClassCastException is
// expected.
@Test(expected = ClassCastException.class)
public void testAccessAttributesFailure4() throws GraphIOException {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
g.setAttribute("boolGraph", null);
}
// Test type-specific iteration over vertices (VertexTestSchema.tg)
// This test requires the type-specific getNextVertex()/getNextEdge()
// methods of the GenericVertexImpl/EdgeImpl classes, as the iterators
// use them.
@Test
public void testVertexIteration() {
try {
Schema s = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = s.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(s.getGraphClass().getVertexClass("A"));
Vertex v2 = g.createVertex(s.getGraphClass().getVertexClass("A"));
Vertex v3 = g.createVertex(s.getGraphClass().getVertexClass("B"));
Vertex v4 = g.createVertex(s.getGraphClass().getVertexClass("B"));
Vertex v5 = g.createVertex(s.getGraphClass().getVertexClass("C"));
Vertex v6 = g.createVertex(s.getGraphClass().getVertexClass("C"));
Vertex v7 = g.createVertex(s.getGraphClass().getVertexClass("D"));
Vertex v8 = g.createVertex(s.getGraphClass().getVertexClass("D"));
Vertex v9 = g.createVertex(s.getGraphClass().getVertexClass("C2"));
Vertex v10 = g.createVertex(s.getGraphClass().getVertexClass("C2"));
assertNull(g.getFirstVertex(s.getGraphClass().getVertexClass("D2")));
assertEquals(v1,
g.getFirstVertex(s.getGraphClass().getVertexClass("A")));
assertEquals(v3,
g.getFirstVertex(s.getGraphClass().getVertexClass("B")));
assertEquals(v5,
g.getFirstVertex(s.getGraphClass().getVertexClass("C")));
assertEquals(v7,
g.getFirstVertex(s.getGraphClass().getVertexClass("D")));
assertEquals(v9,
g.getFirstVertex(s.getGraphClass().getVertexClass("C2")));
Vertex v11 = g.createVertex(s.getGraphClass().getVertexClass("D2"));
Vertex v12 = g.createVertex(s.getGraphClass().getVertexClass("D2"));
Vertex[] aTest = new Vertex[] { v1, v2, v5, v6, v9, v10 };
Vertex[] bTest = new Vertex[] { v3, v4, v7, v8, v11, v12 };
Vertex[] cTest = new Vertex[] { v5, v6, v9, v10 };
Vertex[] dTest = new Vertex[] { v7, v8, v11, v12 };
Vertex[] c2Test = new Vertex[] { v9, v10 };
Vertex[] d2Test = new Vertex[] { v11, v12 };
int i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("A"))) {
assertEquals(aTest[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("B"))) {
assertEquals(bTest[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("C"))) {
assertEquals(cTest[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("D"))) {
assertEquals(dTest[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("C2"))) {
assertEquals(c2Test[i], v);
i++;
}
i = 0;
for (Vertex v : g.vertices(s.getGraphClass().getVertexClass("D2"))) {
assertEquals(d2Test[i], v);
i++;
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test type-specific iteration over edges (VertexTestSchema.tg)
@Test
public void testEdgeIteration() {
try {
Schema s = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "VertexTestSchema.tg");
Graph g = s.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(s.getGraphClass().getVertexClass("A"));
Vertex v2 = g.createVertex(s.getGraphClass().getVertexClass("A"));
Vertex v3 = g.createVertex(s.getGraphClass().getVertexClass("B"));
Vertex v4 = g.createVertex(s.getGraphClass().getVertexClass("B"));
Vertex v5 = g.createVertex(s.getGraphClass().getVertexClass("C"));
Vertex v6 = g.createVertex(s.getGraphClass().getVertexClass("C"));
Vertex v7 = g.createVertex(s.getGraphClass().getVertexClass("D"));
Vertex v8 = g.createVertex(s.getGraphClass().getVertexClass("D"));
Edge e1 = g.createEdge(s.getGraphClass().getEdgeClass("E"), v1, v3);
Edge e2 = g.createEdge(s.getGraphClass().getEdgeClass("E"), v2, v4);
Edge e3 = g.createEdge(s.getGraphClass().getEdgeClass("F"), v5, v7);
Edge e4 = g.createEdge(s.getGraphClass().getEdgeClass("F"), v6, v8);
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("G")));
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("H")));
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("I")));
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("J")));
assertNull(g.getFirstEdge(s.getGraphClass().getEdgeClass("K")));
Edge e5 = g.createEdge(s.getGraphClass().getEdgeClass("G"), v5, v8);
Edge e6 = g.createEdge(s.getGraphClass().getEdgeClass("G"), v6, v7);
Edge e7 = g.createEdge(s.getGraphClass().getEdgeClass("H"), v1, v7);
Edge e8 = g.createEdge(s.getGraphClass().getEdgeClass("H"), v2, v8);
Edge[] eTest = new Edge[] { e1, e2, e3, e4, e5, e6, e7, e8 };
Edge[] fTest = new Edge[] { e3, e4 };
Edge[] gTest = new Edge[] { e5, e6 };
Edge[] hTest = new Edge[] { e7, e8 };
int i = 0;
for (Edge e : g.edges(s.getGraphClass().getEdgeClass("E"))) {
assertEquals(eTest[i], e);
i++;
}
i = 0;
for (Edge e : g.edges(s.getGraphClass().getEdgeClass("F"))) {
assertEquals(fTest[i], e);
i++;
}
i = 0;
for (Edge e : g.edges(s.getGraphClass().getEdgeClass("G"))) {
assertEquals(gTest[i], e);
i++;
}
i = 0;
for (Edge e : g.edges(s.getGraphClass().getEdgeClass("H"))) {
assertEquals(hTest[i], e);
i++;
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testSave() {
try {
Schema schema;
schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "MinimalSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
Vertex v1 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
Vertex v2 = g.createVertex(schema.getGraphClass().getVertexClass(
"Node"));
g.createEdge(schema.getGraphClass().getEdgeClass("Link"), v1, v2);
g.createEdge(schema.getGraphClass().getEdgeClass("Link"), v2, v1);
g.save(DATAFOLDER + "GenericTestGraph1.tg");
Graph g2 = GraphIO.loadGraphFromFile(DATAFOLDER
+ "GenericTestGraph1.tg", schema,
ImplementationType.GENERIC, null);
Iterator<Vertex> vertexIterator1 = g.vertices().iterator();
Iterator<Vertex> vertexIterator2 = g2.vertices().iterator();
Iterator<Edge> edgeIterator1 = g.edges().iterator();
Iterator<Edge> edgeIterator2 = g2.edges().iterator();
while (vertexIterator1.hasNext()) {
Vertex vg1 = vertexIterator1.next();
Vertex vg2 = vertexIterator2.next();
assertEquals(vg1.getId(), vg2.getId());
assertEquals(vg1.getAttributedElementClass(),
vg2.getAttributedElementClass());
}
assertFalse(vertexIterator2.hasNext());
while (edgeIterator1.hasNext()) {
Edge eg1 = edgeIterator1.next();
Edge eg2 = edgeIterator2.next();
assertEquals(eg1.getId(), eg2.getId());
assertEquals(eg2.getAttributedElementClass(),
eg2.getAttributedElementClass());
}
assertFalse(edgeIterator2.hasNext());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test loading a graph (tested statically against a saved graph)
@Test
public void testLoadGraph1() {
// Static test relies on an unchanged graph in the file!
try {
Schema s = GraphIO.loadSchemaFromFile(GRAPHFOLDER
+ "citymapgraph.tg");
Graph g = GraphIO.loadGraphFromFile(
GRAPHFOLDER + "citymapgraph.tg", s,
ImplementationType.GENERIC, null);
assertEquals(8, g.getVCount());
assertEquals(11, g.getECount());
// Check types
VertexClass intersection = g.getSchema().getGraphClass()
.getVertexClass("Intersection");
VertexClass carPark = g.getSchema().getGraphClass()
.getVertexClass("CarPark");
EdgeClass street = g.getSchema().getGraphClass()
.getEdgeClass("Street");
EdgeClass bridge = g.getSchema().getGraphClass()
.getEdgeClass("Bridge");
Vertex[] vertices = new Vertex[8];
for (int i = 0; i < 8; i++) {
vertices[i] = g.getVertex(i + 1);
}
Edge[] edges = new Edge[11];
for (int i = 0; i < 11; i++) {
edges[i] = g.getEdge(i + 1);
}
assertEquals(vertices[0].getAttributedElementClass(), intersection);
assertEquals(vertices[1].getAttributedElementClass(), intersection);
assertEquals(vertices[2].getAttributedElementClass(), carPark);
assertEquals(vertices[3].getAttributedElementClass(), intersection);
assertEquals(vertices[4].getAttributedElementClass(), intersection);
assertEquals(vertices[5].getAttributedElementClass(), intersection);
assertEquals(vertices[6].getAttributedElementClass(), carPark);
assertEquals(vertices[7].getAttributedElementClass(), carPark);
assertEquals(edges[0].getAttributedElementClass(), street);
assertEquals(edges[1].getAttributedElementClass(), street);
assertEquals(edges[2].getAttributedElementClass(), street);
assertEquals(edges[3].getAttributedElementClass(), street);
assertEquals(edges[4].getAttributedElementClass(), bridge);
assertEquals(edges[5].getAttributedElementClass(), street);
assertEquals(edges[6].getAttributedElementClass(), street);
assertEquals(edges[7].getAttributedElementClass(), street);
assertEquals(edges[8].getAttributedElementClass(), bridge);
assertEquals(edges[9].getAttributedElementClass(), bridge);
assertEquals(edges[10].getAttributedElementClass(), street);
// Check attribute values
assertFalse((Boolean) vertices[0].getAttribute("roundabout"));
assertFalse((Boolean) vertices[1].getAttribute("roundabout"));
assertFalse((Boolean) vertices[3].getAttribute("roundabout"));
assertFalse((Boolean) vertices[4].getAttribute("roundabout"));
assertFalse((Boolean) vertices[5].getAttribute("roundabout"));
for (Vertex v : vertices) {
assertEquals(null, v.getAttribute("name"));
}
assertEquals(new Integer(2500),
vertices[2].getAttribute("capacity"));
assertEquals(new Integer(500), vertices[6].getAttribute("capacity"));
assertEquals(new Integer(500), vertices[7].getAttribute("capacity"));
for (int i = 0; i < edges.length; i++) {
assertFalse((Boolean) edges[i].getAttribute("oneway"));
assertEquals("e" + (i + 1), edges[i].getAttribute("name"));
assertEquals(0, edges[i].getAttribute("length"));
}
assertEquals(0, edges[4].getAttribute("height"));
assertEquals(0, edges[8].getAttribute("height"));
assertEquals(0, edges[9].getAttribute("height"));
// Check incidences
assertEquals(2, vertices[0].getDegree());
assertEquals(edges[0], vertices[0].getFirstIncidence());
assertEquals(edges[2], vertices[0].getLastIncidence());
assertEquals(3, vertices[1].getDegree());
assertEquals(edges[0].getReversedEdge(),
vertices[1].getFirstIncidence());
assertEquals(edges[1], vertices[1].getFirstIncidence()
.getNextIncidence());
assertEquals(edges[3].getReversedEdge(),
vertices[1].getLastIncidence());
assertEquals(2, vertices[2].getDegree());
assertEquals(edges[1].getReversedEdge(),
vertices[2].getFirstIncidence());
assertEquals(edges[4], vertices[2].getLastIncidence());
assertEquals(3, vertices[3].getDegree());
assertEquals(edges[2].getReversedEdge(),
vertices[3].getFirstIncidence());
assertEquals(edges[5], vertices[3].getFirstIncidence()
.getNextIncidence());
assertEquals(edges[7], vertices[3].getLastIncidence());
assertEquals(4, vertices[4].getDegree());
assertEquals(edges[3], vertices[4].getFirstIncidence());
assertEquals(edges[5].getReversedEdge(), vertices[4]
.getFirstIncidence().getNextIncidence());
assertEquals(edges[6], vertices[4].getLastIncidence()
.getPrevIncidence());
assertEquals(edges[8], vertices[4].getLastIncidence());
assertEquals(3, vertices[5].getDegree());
assertEquals(edges[4].getReversedEdge(),
vertices[5].getFirstIncidence());
assertEquals(edges[6].getReversedEdge(), vertices[5]
.getFirstIncidence().getNextIncidence());
assertEquals(edges[9], vertices[5].getLastIncidence());
assertEquals(2, vertices[6].getDegree());
assertEquals(edges[7].getReversedEdge(),
vertices[6].getFirstIncidence());
assertEquals(edges[10], vertices[6].getLastIncidence());
assertEquals(3, vertices[7].getDegree());
assertEquals(edges[8].getReversedEdge(),
vertices[7].getFirstIncidence());
assertEquals(edges[9].getReversedEdge(), vertices[7]
.getFirstIncidence().getNextIncidence());
assertEquals(edges[10].getReversedEdge(),
vertices[7].getLastIncidence());
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
// Test loading the greqltestgraph.tg-file
@Test
public void testLoadGraph2() {
try {
Schema s = GraphIO.loadSchemaFromFile(GRAPHFOLDER
+ "greqltestgraph.tg");
Graph g1 = GraphIO.loadGraphFromFile(GRAPHFOLDER
+ "greqltestgraph.tg", s, ImplementationType.GENERIC, null);
assertEquals(s.getGraphClass(), g1.getAttributedElementClass());
assertEquals(157, g1.getVCount());
assertEquals(357, g1.getECount());
// compare against the same Graph loaded with the standard
// implementation
Graph g2 = GraphIO
.loadGraphFromFile(GRAPHFOLDER + "greqltestgraph.tg", s,
ImplementationType.STANDARD, null);
for (Vertex v : g2.vertices()) {
assertEquals(v.getAttributedElementClass(),
g1.getVertex(v.getId()).getAttributedElementClass());
// assert equality of attributes
for (Attribute a : v.getAttributedElementClass()
.getAttributeList()) {
try {
assertEquals(
v.writeAttributeValueToString(a.getName()),
g2.getVertex(v.getId())
.writeAttributeValueToString(
a.getName()));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
}
for (Edge edge : g2.edges()) {
assertEquals(edge.getAttributedElementClass(),
g1.getEdge(edge.getId()).getAttributedElementClass());
// assert equality of attributes
for (Attribute a : edge.getAttributedElementClass()
.getAttributeList()) {
try {
assertEquals(edge.writeAttributeValueToString(a
.getName()), g2.getEdge(edge.getId())
.writeAttributeValueToString(a.getName()));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testCreateRecord() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
RecordDomain testRecordDomain = (RecordDomain) schema
.getDomain("TestRecordDomain");
Map<String, Object> values = new HashMap<String, Object>();
Boolean boolRecord = Boolean.FALSE;
Double doubleRecord = Double.valueOf(0.123d);
String enumRecord = "SECOND";
Integer intRecord = Integer.valueOf(42);
List<?> listRecord = JGraLab.vector().plus(true).plus(false);
Long longRecord = Long.valueOf(9876543210l);
Map<?, ?> mapRecord = JGraLab.map().plus(1, true).plus(2, false);
Set<?> setRecord = JGraLab.set().plus(true).plus(false);
String stringRecord = "some string";
values.put("boolRecord", boolRecord);
values.put("doubleRecord", doubleRecord);
values.put("enumRecord", enumRecord);
values.put("intRecord", intRecord);
values.put("listRecord", listRecord);
values.put("longRecord", longRecord);
values.put("mapRecord", mapRecord);
values.put("setRecord", setRecord);
values.put("stringRecord", stringRecord);
Record r = g.createRecord(testRecordDomain, values);
for (String componentName : values.keySet()) {
assertEquals(values.get(componentName),
r.getComponent(componentName));
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testGetEnumConstant() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
EnumDomain testEnumDomain = (EnumDomain) schema
.getDomain("TestEnumDomain");
for (String c : testEnumDomain.getConsts()) {
assertEquals(c, g.getEnumConstant(testEnumDomain, c));
}
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@Test(expected = GraphException.class)
public void testGetEnumConstantFailure() {
try {
Schema schema = GraphIO.loadSchemaFromFile(SCHEMAFOLDER
+ "DefaultValueTestSchema.tg");
Graph g = schema.createGraph(ImplementationType.GENERIC);
EnumDomain testEnumDomain = (EnumDomain) schema
.getDomain("TestEnumDomain");
g.getEnumConstant(testEnumDomain, "FOURTH");
} catch (GraphIOException e) {
e.printStackTrace();
fail();
}
}
@AfterClass
public static void cleanup() {
File f = new File(DATAFOLDER + "GenericTestGraph1.tg");
f.delete();
}
}
| 39,730 | 0.678606 | 0.666826 | 1,104 | 34.986412 | 23.261875 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.513587 | false | false |
15
|
d89e6c45cf7b6321cd51577d68aeea2ed6ee1df4
| 39,187,281,612,769 |
945d2f8da364b6bdbe94b1b66dfbc73984e85874
|
/news-consumer/src/main/java/consumer/NewsConsumer.java
|
8bdf52625f69e49932029a346ecd3baeba66e3e8
|
[] |
no_license
|
robson021/kafka-news-service-demo
|
https://github.com/robson021/kafka-news-service-demo
|
b4449b4d4af829a344736ed215e5761d4941c53e
|
dc5fbad7146f9fb7e4434ff63d51a19f0a438c67
|
refs/heads/master
| 2020-04-04T03:47:45.801000 | 2018-12-19T22:38:09 | 2018-12-19T22:38:09 | 155,726,259 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package consumer;
import common.config.KafkaProps;
import common.model.News;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@RequiredArgsConstructor
public class NewsConsumer {
private final NewsStorage newsStorage;
@KafkaListener(topics = KafkaProps.DEFAULT_TOPIC)
public void newsListener(News news) {
log.info("Consumed new message: {}", news);
newsStorage.addNews(news);
}
}
|
UTF-8
|
Java
| 568 |
java
|
NewsConsumer.java
|
Java
|
[] | null |
[] |
package consumer;
import common.config.KafkaProps;
import common.model.News;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@RequiredArgsConstructor
public class NewsConsumer {
private final NewsStorage newsStorage;
@KafkaListener(topics = KafkaProps.DEFAULT_TOPIC)
public void newsListener(News news) {
log.info("Consumed new message: {}", news);
newsStorage.addNews(news);
}
}
| 568 | 0.771127 | 0.765845 | 23 | 23.695652 | 19.452137 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false |
15
|
05b04c5ed41eea990820eaf5fb9eb6d7f6f6ef27
| 35,948,876,305,862 |
175b63d891814e99e34b3490cf407de945c79197
|
/src/main/java/br/com/algamoney/controller/CategoriaController.java
|
88617be747543262c67d4c6f8496b06b7491700f
|
[] |
no_license
|
Ailton2/algamoney
|
https://github.com/Ailton2/algamoney
|
d0aa3e0cc438fae3002bfe0ca212c5fb1a33eb5d
|
fa625f2dfc5a836a63cf6778d3b0a4c7d6699c2e
|
refs/heads/master
| 2023-04-29T01:35:44.279000 | 2021-05-19T22:45:33 | 2021-05-19T22:45:33 | 364,414,313 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.algamoney.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import br.com.algamoney.exception.EntidadeEmUsoException;
import br.com.algamoney.exception.EntidadeNaoEncontradaException;
import br.com.algamoney.model.Categoria;
import br.com.algamoney.service.CategoriaService;
@CrossOrigin
@RestController
@RequestMapping("/categorias")
public class CategoriaController {
@Autowired
private CategoriaService categoriaService;
@GetMapping
public ResponseEntity<?> listar(){
List<Categoria> categorias = categoriaService.listarTodos();
return ResponseEntity.ok(categorias);
}
@PostMapping
public ResponseEntity<?> salvar(@RequestBody Categoria categoria) {
categoriaService.save(categoria);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@GetMapping("/{id}")
public ResponseEntity<?> buscarId(@PathVariable Long id) throws Exception {
Categoria categoria= categoriaService.buscarPorId(id);
if (categoria != null) {
return ResponseEntity.ok(categoria);
}
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
@DeleteMapping("/{id}")
public ResponseEntity<?> excluir(@PathVariable Long id) throws Exception{
try {
categoriaService.excluir(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} catch (EntidadeNaoEncontradaException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}catch(EntidadeEmUsoException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
@GetMapping("/por-nome")
public List<Categoria> buscaPorN(@RequestParam String nome){
List<Categoria> categorias= categoriaService.buscaPorN(nome);
return categorias;
}
}
|
UTF-8
|
Java
| 2,499 |
java
|
CategoriaController.java
|
Java
|
[] | null |
[] |
package br.com.algamoney.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import br.com.algamoney.exception.EntidadeEmUsoException;
import br.com.algamoney.exception.EntidadeNaoEncontradaException;
import br.com.algamoney.model.Categoria;
import br.com.algamoney.service.CategoriaService;
@CrossOrigin
@RestController
@RequestMapping("/categorias")
public class CategoriaController {
@Autowired
private CategoriaService categoriaService;
@GetMapping
public ResponseEntity<?> listar(){
List<Categoria> categorias = categoriaService.listarTodos();
return ResponseEntity.ok(categorias);
}
@PostMapping
public ResponseEntity<?> salvar(@RequestBody Categoria categoria) {
categoriaService.save(categoria);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@GetMapping("/{id}")
public ResponseEntity<?> buscarId(@PathVariable Long id) throws Exception {
Categoria categoria= categoriaService.buscarPorId(id);
if (categoria != null) {
return ResponseEntity.ok(categoria);
}
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
@DeleteMapping("/{id}")
public ResponseEntity<?> excluir(@PathVariable Long id) throws Exception{
try {
categoriaService.excluir(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} catch (EntidadeNaoEncontradaException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}catch(EntidadeEmUsoException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
@GetMapping("/por-nome")
public List<Categoria> buscaPorN(@RequestParam String nome){
List<Categoria> categorias= categoriaService.buscaPorN(nome);
return categorias;
}
}
| 2,499 | 0.791116 | 0.791116 | 84 | 28.75 | 25.695042 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.452381 | false | false |
15
|
7a04fa1cedb4db21273e77f75e479adfef513df5
| 35,948,876,307,949 |
ffdb8da5c5e7e73abb74d999aaa4114744867ffa
|
/src/collectionmanager/ui/DeleteItem.java
|
30033125d7b9d34446c34e73b7d33eacbf667622
|
[] |
no_license
|
michalrudzky/CollectionManager
|
https://github.com/michalrudzky/CollectionManager
|
f6dfbd0bdc659388ff327d899b4e9c8fc6ee02a8
|
aee63c58f88f250e1f39c905094f9cc1559efe0f
|
refs/heads/master
| 2021-05-11T02:08:25.762000 | 2018-03-01T20:57:41 | 2018-03-01T20:57:41 | 115,761,861 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* 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 collectionmanager.ui;
import collectionmanager.db.DbOperations;
import collectionmanager.entity.CollectionItem;
import java.util.List;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
/**
* GUI window for deleting items from the collection.
* @author michalrudzki
*/
public class DeleteItem extends javax.swing.JFrame
{
/**
* Creates new window for deleting items.
*/
public DeleteItem()
{
initComponents();
fillList();
}
/**
* Populates the dropdown list with names of all collection items.
*/
private void fillList()
{
List itemsList = DbOperations.readCollection();
List<String> namesList = new ArrayList<>();
for (Object o : itemsList)
{
CollectionItem item = (CollectionItem) o;
namesList.add(item.getName());
}
choiceList.setModel(new DefaultComboBoxModel(namesList.toArray()));
}
/**
* 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()
{
titleLabel = new javax.swing.JLabel();
choiceList = new javax.swing.JComboBox<>();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
titleLabel.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
titleLabel.setText("Delete item");
choiceList.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
okButtonActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cancelButtonActionPerformed(evt);
}
});
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(94, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton)
.addGap(110, 110, 110))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(choiceList, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(76, 76, 76))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(titleLabel)
.addGap(136, 136, 136))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(18, 18, 18)
.addComponent(choiceList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(okButton)
.addComponent(cancelButton))
.addContainerGap(32, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Closes the current window and opens the main window.
*/
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed
{//GEN-HEADEREND:event_cancelButtonActionPerformed
dispose();
new CollectionManager().setVisible(true);
}//GEN-LAST:event_cancelButtonActionPerformed
/**
* Performs the deleting item operation.
*/
private void okButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_okButtonActionPerformed
{//GEN-HEADEREND:event_okButtonActionPerformed
// TODO add your handling code here:
String selectedName = (String) choiceList.getSelectedItem();
List itemsList = DbOperations.readCollection();
for (Object o : itemsList)
{
CollectionItem item = (CollectionItem) o;
String itemName = item.getName();
if (itemName.equals(selectedName))
{
int deleteID = item.getId();
DbOperations.deleteItem(deleteID);
break;
}
}
dispose();
new CollectionManager().setVisible(true);
}//GEN-LAST:event_okButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(DeleteItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(DeleteItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(DeleteItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(DeleteItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new DeleteItem().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JComboBox<String> choiceList;
private javax.swing.JButton okButton;
private javax.swing.JLabel titleLabel;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 8,199 |
java
|
DeleteItem.java
|
Java
|
[
{
"context": "for deleting items from the collection.\n * @author michalrudzki\n */\npublic class DeleteItem extends javax.swin",
"end": 477,
"score": 0.8551797866821289,
"start": 468,
"tag": "USERNAME",
"value": "michalrud"
},
{
"context": "ng items from the collection.\n * @author michalrudzki\n */\npublic class DeleteItem extends javax.swing.J",
"end": 480,
"score": 0.564111590385437,
"start": 477,
"tag": "NAME",
"value": "zki"
}
] | null |
[] |
/*
* 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 collectionmanager.ui;
import collectionmanager.db.DbOperations;
import collectionmanager.entity.CollectionItem;
import java.util.List;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
/**
* GUI window for deleting items from the collection.
* @author michalrudzki
*/
public class DeleteItem extends javax.swing.JFrame
{
/**
* Creates new window for deleting items.
*/
public DeleteItem()
{
initComponents();
fillList();
}
/**
* Populates the dropdown list with names of all collection items.
*/
private void fillList()
{
List itemsList = DbOperations.readCollection();
List<String> namesList = new ArrayList<>();
for (Object o : itemsList)
{
CollectionItem item = (CollectionItem) o;
namesList.add(item.getName());
}
choiceList.setModel(new DefaultComboBoxModel(namesList.toArray()));
}
/**
* 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()
{
titleLabel = new javax.swing.JLabel();
choiceList = new javax.swing.JComboBox<>();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
titleLabel.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
titleLabel.setText("Delete item");
choiceList.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
okButtonActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
cancelButtonActionPerformed(evt);
}
});
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(94, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton)
.addGap(110, 110, 110))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(choiceList, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(76, 76, 76))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(titleLabel)
.addGap(136, 136, 136))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(titleLabel)
.addGap(18, 18, 18)
.addComponent(choiceList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(okButton)
.addComponent(cancelButton))
.addContainerGap(32, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Closes the current window and opens the main window.
*/
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed
{//GEN-HEADEREND:event_cancelButtonActionPerformed
dispose();
new CollectionManager().setVisible(true);
}//GEN-LAST:event_cancelButtonActionPerformed
/**
* Performs the deleting item operation.
*/
private void okButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_okButtonActionPerformed
{//GEN-HEADEREND:event_okButtonActionPerformed
// TODO add your handling code here:
String selectedName = (String) choiceList.getSelectedItem();
List itemsList = DbOperations.readCollection();
for (Object o : itemsList)
{
CollectionItem item = (CollectionItem) o;
String itemName = item.getName();
if (itemName.equals(selectedName))
{
int deleteID = item.getId();
DbOperations.deleteItem(deleteID);
break;
}
}
dispose();
new CollectionManager().setVisible(true);
}//GEN-LAST:event_okButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(DeleteItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(DeleteItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(DeleteItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(DeleteItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new DeleteItem().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JComboBox<String> choiceList;
private javax.swing.JButton okButton;
private javax.swing.JLabel titleLabel;
// End of variables declaration//GEN-END:variables
}
| 8,199 | 0.622759 | 0.616051 | 208 | 38.41827 | 33.801216 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false |
15
|
3cb8ac5cf7bf20068d259e5150890d73b20998a0
| 26,293,789,811,280 |
cd86bcc6f34e03689e1bb14ffc1910fb27f43fb4
|
/src/test/java/org/hong/springhello/ListTestBeanTest.java
|
b5eace0fec5695a1b840866a5436c685622a0b5b
|
[] |
no_license
|
t-hong/first-spring
|
https://github.com/t-hong/first-spring
|
5420ccebfa1761053f80827df753193b77151f7b
|
758f2232a62714a25ee792245543a72497e14ea8
|
refs/heads/master
| 2018-03-13T23:11:42.808000 | 2016-06-08T15:18:08 | 2016-06-08T15:18:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.hong.springhello;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
/**
* Created by hong on 16/6/8.
*/
public class ListTestBeanTest {
@Test
public void testListBean(){
ApplicationContext context=new ClassPathXmlApplicationContext("Beans.xml");
ListTestBean listTestBean =context.getBean("listTestBean",ListTestBean.class);
System.out.println(listTestBean.toString());
Assert.assertEquals(3,listTestBean.getValues().size());
}
}
|
UTF-8
|
Java
| 655 |
java
|
ListTestBeanTest.java
|
Java
|
[
{
"context": "port static org.junit.Assert.*;\n\n/**\n * Created by hong on 16/6/8.\n */\npublic class ListTestBeanTest {\n\n ",
"end": 267,
"score": 0.8349746465682983,
"start": 263,
"tag": "USERNAME",
"value": "hong"
}
] | null |
[] |
package org.hong.springhello;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
/**
* Created by hong on 16/6/8.
*/
public class ListTestBeanTest {
@Test
public void testListBean(){
ApplicationContext context=new ClassPathXmlApplicationContext("Beans.xml");
ListTestBean listTestBean =context.getBean("listTestBean",ListTestBean.class);
System.out.println(listTestBean.toString());
Assert.assertEquals(3,listTestBean.getValues().size());
}
}
| 655 | 0.749618 | 0.741985 | 23 | 27.52174 | 27.954729 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false |
15
|
fb11b66b22ffbf88be9d27c7ae850050ba20c258
| 4,440,996,204,697 |
95506785b19f6be40c543cb8a40f58b539979b08
|
/src/main/java/servlets/FiscalizacionesNew.java
|
6c380ebacb60357e32ba2f59936c7076bd6bcdb0
|
[] |
no_license
|
JoaTorres/PrexTax
|
https://github.com/JoaTorres/PrexTax
|
5aea2bf92077c838ced55fc72c9a31b9e931d7ef
|
9382d2fb219f1892370cc41309feaabf07b84ae1
|
refs/heads/master
| 2020-04-10T02:25:35.474000 | 2019-07-08T21:56:57 | 2019-07-08T21:56:57 | 160,744,058 | 0 | 0 | null | false | 2019-11-13T08:38:35 | 2018-12-06T23:12:02 | 2019-07-24T15:02:45 | 2019-11-13T08:38:33 | 22,262 | 0 | 0 | 1 |
Java
| false | false |
package servlets;
import dao.component.FiscalizacionDAO;
import dao.component.SelectDAO;
import dao.to.FiscalizacionTO;
import dao.to.SelectTO;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.StringUtils;
@WebServlet(name = "FiscalizacionesNew", urlPatterns = {"/FiscalizacionesNew"})
public class FiscalizacionesNew extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
try {
FiscalizacionDAO oDao = new FiscalizacionDAO();
SelectDAO selectDAO = new SelectDAO();
int id = request.getParameter("id").equals("") ? 0 : Integer.parseInt(request.getParameter("id"));
String ruc = request.getParameter("ruc");
int idArea = request.getParameter("idArea").equals("") ? 1 : Integer.parseInt(request.getParameter("idArea"));
int idDocumento = request.getParameter("idDocumento").equals("") ? 1 : Integer.parseInt(request.getParameter("idDocumento"));
int idTipo = request.getParameter("idTipo").equals("") ? 1 : Integer.parseInt(request.getParameter("idTipo"));
int idEstado = request.getParameter("idEstado").equals("") ? 1 : Integer.parseInt(request.getParameter("idEstado"));
int idTributo = request.getParameter("idTributo").equals("") ? 1 : Integer.parseInt(request.getParameter("idTributo"));
String nroReq = request.getParameter("nroReq");
String periodoI = request.getParameter("periodoI");
String periodoF = request.getParameter("periodoF");
String fRecepcion = request.getParameter("fRecepcion");
String fPresentacion = request.getParameter("fPresentacion");
String hora = request.getParameter("hora");
int idLugar = request.getParameter("idLugar").equals("") ? 1 : Integer.parseInt(request.getParameter("idLugar"));
String auditor = request.getParameter("auditor");
int anexos = request.getParameter("anexos").equals("") ? 0 : Integer.parseInt(request.getParameter("anexos"));
int idError = request.getParameter("idError").equals("") ? 1 : Integer.parseInt(request.getParameter("idError"));
String observacion = request.getParameter("observacion");
String anioI = "";
String mesI = "";
String anioF = "";
String mesF = "";
if (!periodoI.equals("")) {
ArrayList<String> periodoArray = StringUtils.splitOnChar(periodoI, "-");
anioI = periodoArray.get(0);
mesI = periodoArray.get(1);
}
if (!periodoF.equals("")) {
ArrayList<String> periodoArray = StringUtils.splitOnChar(periodoF, "-");
anioF = periodoArray.get(0);
mesF = periodoArray.get(1);
}
FiscalizacionTO o = new FiscalizacionTO();
o.setId(id);
o.setIdArea(idArea);
o.setRuc(ruc);
o.setIdDocumento(idDocumento);
o.setIdTipo(idTipo);
o.setIdEstado(idEstado);
o.setIdTributo(idTributo);
o.setNroReq(nroReq);
o.setAnioI(anioI);
o.setMesI(mesI);
o.setAnioF(anioF);
o.setMesF(mesF);
o.setfRecepcion(fRecepcion);
o.setfPresentacion(fPresentacion);
o.setHora(hora);
o.setIdLugar(idLugar);
o.setAuditor(auditor);
o.setAnexos(anexos);
o.setIdError(idError);
o.setObservacion(observacion);
int msg = oDao.insertUpdate(o);
//<editor-fold defaultstate="collapsed" desc="ÁREAS">
String areasHidden = request.getParameter("areasNew");
if (areasHidden == null) {
areasHidden = "1,2";
}
List<SelectTO> areas = selectDAO.list("fiscalizacionesAreas");
String[] areasArray = StringUtils.splitOnCharArray(areasHidden, ",");
for (SelectTO area : areas) {
for (String str : areasArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("areas", areas);
request.setAttribute("areasHidden", areasHidden);
request.setAttribute("areasNew", areasHidden);
request.setAttribute("areasExcel", areasHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ESTADOS">
String estadosHidden = request.getParameter("estadosNew");
if (estadosHidden == null) {
estadosHidden = "1,2";
}
List<SelectTO> estados = selectDAO.list("fiscalizacionesEstados");
String[] estadosArray = StringUtils.splitOnCharArray(estadosHidden, ",");
for (SelectTO area : estados) {
for (String str : estadosArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("estados", estados);
request.setAttribute("estadosHidden", estadosHidden);
request.setAttribute("estadosNew", estadosHidden);
request.setAttribute("estadosExcel", estadosHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="DOCUMENTOS">
String documentosHidden = request.getParameter("documentosNew");
if (documentosHidden == null) {
documentosHidden = "1,2,3,4";
}
List<SelectTO> documentos = selectDAO.list("fiscalizacionesDocumentos");
String[] documentosArray = StringUtils.splitOnCharArray(documentosHidden, ",");
for (SelectTO area : documentos) {
for (String str : documentosArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("documentos", documentos);
request.setAttribute("documentosHidden", documentosHidden);
request.setAttribute("documentosNew", documentosHidden);
request.setAttribute("documentosExcel", documentosHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="TIPOS">
String tiposHidden = request.getParameter("tiposHidden");
if (tiposHidden == null) {
tiposHidden = "1,2,3,4";
}
List<SelectTO> tipos = selectDAO.list("fiscalizacionesTipos");
String[] tiposArray = StringUtils.splitOnCharArray(tiposHidden, ",");
for (SelectTO area : tipos) {
for (String str : tiposArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("tipos", tipos);
request.setAttribute("tiposHidden", tiposHidden);
request.setAttribute("tiposNew", tiposHidden);
request.setAttribute("tiposExcel", tiposHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="TRIBUTOS">
String tributosHidden = request.getParameter("tributosHidden");
if (tributosHidden == null) {
tributosHidden = "1,2,3,4";
}
List<SelectTO> tributos = selectDAO.list("fiscalizacionesTributos");
String[] tributosArray = StringUtils.splitOnCharArray(tributosHidden, ",");
for (SelectTO area : tributos) {
for (String str : tributosArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("tributos", tributos);
request.setAttribute("tributosHidden", tributosHidden);
request.setAttribute("tributosNew", tributosHidden);
request.setAttribute("tributosExcel", tributosHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="LUGARES">
String lugaresHidden = request.getParameter("lugaresHidden");
if (lugaresHidden == null) {
lugaresHidden = "1,2,3,4";
}
List<SelectTO> lugares = selectDAO.list("fiscalizacionesLugares");
String[] lugaresArray = StringUtils.splitOnCharArray(lugaresHidden, ",");
for (SelectTO area : lugares) {
for (String str : lugaresArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("lugares", lugares);
request.setAttribute("lugaresHidden", lugaresHidden);
request.setAttribute("lugaresNew", lugaresHidden);
request.setAttribute("lugaresExcel", lugaresHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ERRORES">
String erroresHidden = request.getParameter("erroresHidden");
if (erroresHidden == null) {
erroresHidden = "1,2,3,4";
}
List<SelectTO> errores = selectDAO.list("fiscalizacionesErrores");
String[] erroresArray = StringUtils.splitOnCharArray(erroresHidden, ",");
for (SelectTO area : errores) {
for (String str : erroresArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("errores", errores);
request.setAttribute("erroresHidden", erroresHidden);
request.setAttribute("erroresNew", erroresHidden);
request.setAttribute("erroresExcel", erroresHidden);
//</editor-fold>
//LISTAR
List<FiscalizacionTO> list = oDao.list();
request.setAttribute("list", list);
request.setAttribute("msg", msg);
getServletConfig().getServletContext().getRequestDispatcher("/fiscalizacionesList.jsp").forward(request, response);
} catch (Exception e) {
System.out.println("ERROR @FiscalizacionesNew: " + e);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
UTF-8
|
Java
| 12,631 |
java
|
FiscalizacionesNew.java
|
Java
|
[] | null |
[] |
package servlets;
import dao.component.FiscalizacionDAO;
import dao.component.SelectDAO;
import dao.to.FiscalizacionTO;
import dao.to.SelectTO;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.StringUtils;
@WebServlet(name = "FiscalizacionesNew", urlPatterns = {"/FiscalizacionesNew"})
public class FiscalizacionesNew extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
try {
FiscalizacionDAO oDao = new FiscalizacionDAO();
SelectDAO selectDAO = new SelectDAO();
int id = request.getParameter("id").equals("") ? 0 : Integer.parseInt(request.getParameter("id"));
String ruc = request.getParameter("ruc");
int idArea = request.getParameter("idArea").equals("") ? 1 : Integer.parseInt(request.getParameter("idArea"));
int idDocumento = request.getParameter("idDocumento").equals("") ? 1 : Integer.parseInt(request.getParameter("idDocumento"));
int idTipo = request.getParameter("idTipo").equals("") ? 1 : Integer.parseInt(request.getParameter("idTipo"));
int idEstado = request.getParameter("idEstado").equals("") ? 1 : Integer.parseInt(request.getParameter("idEstado"));
int idTributo = request.getParameter("idTributo").equals("") ? 1 : Integer.parseInt(request.getParameter("idTributo"));
String nroReq = request.getParameter("nroReq");
String periodoI = request.getParameter("periodoI");
String periodoF = request.getParameter("periodoF");
String fRecepcion = request.getParameter("fRecepcion");
String fPresentacion = request.getParameter("fPresentacion");
String hora = request.getParameter("hora");
int idLugar = request.getParameter("idLugar").equals("") ? 1 : Integer.parseInt(request.getParameter("idLugar"));
String auditor = request.getParameter("auditor");
int anexos = request.getParameter("anexos").equals("") ? 0 : Integer.parseInt(request.getParameter("anexos"));
int idError = request.getParameter("idError").equals("") ? 1 : Integer.parseInt(request.getParameter("idError"));
String observacion = request.getParameter("observacion");
String anioI = "";
String mesI = "";
String anioF = "";
String mesF = "";
if (!periodoI.equals("")) {
ArrayList<String> periodoArray = StringUtils.splitOnChar(periodoI, "-");
anioI = periodoArray.get(0);
mesI = periodoArray.get(1);
}
if (!periodoF.equals("")) {
ArrayList<String> periodoArray = StringUtils.splitOnChar(periodoF, "-");
anioF = periodoArray.get(0);
mesF = periodoArray.get(1);
}
FiscalizacionTO o = new FiscalizacionTO();
o.setId(id);
o.setIdArea(idArea);
o.setRuc(ruc);
o.setIdDocumento(idDocumento);
o.setIdTipo(idTipo);
o.setIdEstado(idEstado);
o.setIdTributo(idTributo);
o.setNroReq(nroReq);
o.setAnioI(anioI);
o.setMesI(mesI);
o.setAnioF(anioF);
o.setMesF(mesF);
o.setfRecepcion(fRecepcion);
o.setfPresentacion(fPresentacion);
o.setHora(hora);
o.setIdLugar(idLugar);
o.setAuditor(auditor);
o.setAnexos(anexos);
o.setIdError(idError);
o.setObservacion(observacion);
int msg = oDao.insertUpdate(o);
//<editor-fold defaultstate="collapsed" desc="ÁREAS">
String areasHidden = request.getParameter("areasNew");
if (areasHidden == null) {
areasHidden = "1,2";
}
List<SelectTO> areas = selectDAO.list("fiscalizacionesAreas");
String[] areasArray = StringUtils.splitOnCharArray(areasHidden, ",");
for (SelectTO area : areas) {
for (String str : areasArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("areas", areas);
request.setAttribute("areasHidden", areasHidden);
request.setAttribute("areasNew", areasHidden);
request.setAttribute("areasExcel", areasHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ESTADOS">
String estadosHidden = request.getParameter("estadosNew");
if (estadosHidden == null) {
estadosHidden = "1,2";
}
List<SelectTO> estados = selectDAO.list("fiscalizacionesEstados");
String[] estadosArray = StringUtils.splitOnCharArray(estadosHidden, ",");
for (SelectTO area : estados) {
for (String str : estadosArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("estados", estados);
request.setAttribute("estadosHidden", estadosHidden);
request.setAttribute("estadosNew", estadosHidden);
request.setAttribute("estadosExcel", estadosHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="DOCUMENTOS">
String documentosHidden = request.getParameter("documentosNew");
if (documentosHidden == null) {
documentosHidden = "1,2,3,4";
}
List<SelectTO> documentos = selectDAO.list("fiscalizacionesDocumentos");
String[] documentosArray = StringUtils.splitOnCharArray(documentosHidden, ",");
for (SelectTO area : documentos) {
for (String str : documentosArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("documentos", documentos);
request.setAttribute("documentosHidden", documentosHidden);
request.setAttribute("documentosNew", documentosHidden);
request.setAttribute("documentosExcel", documentosHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="TIPOS">
String tiposHidden = request.getParameter("tiposHidden");
if (tiposHidden == null) {
tiposHidden = "1,2,3,4";
}
List<SelectTO> tipos = selectDAO.list("fiscalizacionesTipos");
String[] tiposArray = StringUtils.splitOnCharArray(tiposHidden, ",");
for (SelectTO area : tipos) {
for (String str : tiposArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("tipos", tipos);
request.setAttribute("tiposHidden", tiposHidden);
request.setAttribute("tiposNew", tiposHidden);
request.setAttribute("tiposExcel", tiposHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="TRIBUTOS">
String tributosHidden = request.getParameter("tributosHidden");
if (tributosHidden == null) {
tributosHidden = "1,2,3,4";
}
List<SelectTO> tributos = selectDAO.list("fiscalizacionesTributos");
String[] tributosArray = StringUtils.splitOnCharArray(tributosHidden, ",");
for (SelectTO area : tributos) {
for (String str : tributosArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("tributos", tributos);
request.setAttribute("tributosHidden", tributosHidden);
request.setAttribute("tributosNew", tributosHidden);
request.setAttribute("tributosExcel", tributosHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="LUGARES">
String lugaresHidden = request.getParameter("lugaresHidden");
if (lugaresHidden == null) {
lugaresHidden = "1,2,3,4";
}
List<SelectTO> lugares = selectDAO.list("fiscalizacionesLugares");
String[] lugaresArray = StringUtils.splitOnCharArray(lugaresHidden, ",");
for (SelectTO area : lugares) {
for (String str : lugaresArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("lugares", lugares);
request.setAttribute("lugaresHidden", lugaresHidden);
request.setAttribute("lugaresNew", lugaresHidden);
request.setAttribute("lugaresExcel", lugaresHidden);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ERRORES">
String erroresHidden = request.getParameter("erroresHidden");
if (erroresHidden == null) {
erroresHidden = "1,2,3,4";
}
List<SelectTO> errores = selectDAO.list("fiscalizacionesErrores");
String[] erroresArray = StringUtils.splitOnCharArray(erroresHidden, ",");
for (SelectTO area : errores) {
for (String str : erroresArray) {
if (area.getId() == Integer.parseInt(str)) {
area.setMarcado(1);
}
}
}
request.setAttribute("errores", errores);
request.setAttribute("erroresHidden", erroresHidden);
request.setAttribute("erroresNew", erroresHidden);
request.setAttribute("erroresExcel", erroresHidden);
//</editor-fold>
//LISTAR
List<FiscalizacionTO> list = oDao.list();
request.setAttribute("list", list);
request.setAttribute("msg", msg);
getServletConfig().getServletContext().getRequestDispatcher("/fiscalizacionesList.jsp").forward(request, response);
} catch (Exception e) {
System.out.println("ERROR @FiscalizacionesNew: " + e);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 12,631 | 0.567458 | 0.563816 | 287 | 42.006969 | 29.343334 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.74216 | false | false |
15
|
ab5ac344f843fcb0123fe7c8a47b397819d55054
| 26,079,041,452,618 |
4a44488c380d18ca86d419d27febb2b2b2d018e9
|
/src/main/java/com/voucher/manage/daoModel/TTT/FileRalateParent.java
|
3a6f9894110d0ee65a001ec8faeb8809eaeaba81
|
[] |
no_license
|
wangjiabc/voucher2
|
https://github.com/wangjiabc/voucher2
|
ce13f7e98b8a9617e7587cdead25b6aa8f469287
|
7cade816ff0262ecff841931b8aa060940db921c
|
refs/heads/master
| 2022-12-24T19:05:38.075000 | 2020-01-28T05:03:08 | 2020-01-28T05:03:08 | 147,205,885 | 0 | 5 | null | false | 2022-12-16T08:43:24 | 2018-09-03T13:02:56 | 2020-01-28T05:03:11 | 2022-12-16T08:43:21 | 93,471 | 0 | 2 | 58 |
HTML
| false | false |
package com.voucher.manage.daoModel.TTT;
import java.util.Date;
import java.io.Serializable;
import com.voucher.manage.daoSQL.annotations.*;
@DBTable(name="[FileRalateParent]")
public class FileRalateParent implements Serializable{
private static final long serialVersionUID = 1L;
@SQLString(name="GUID")
private String GUID;
@SQLString(name="RoomGUID")
private String RoomGUID;
@SQLString(name="FileName")
private String FileName;
@SQLString(name="OptType")
private String OptType;
@SQLDateTime(name="DateTime")
private Date DateTime;
public void setGUID(String GUID){
this.GUID = GUID;
}
public String getGUID(){
return GUID;
}
public void setRoomGUID(String RoomGUID){
this.RoomGUID = RoomGUID;
}
public String getRoomGUID(){
return RoomGUID;
}
public void setFileName(String FileName){
this.FileName = FileName;
}
public String getFileName(){
return FileName;
}
public void setOptType(String OptType){
this.OptType = OptType;
}
public String getOptType(){
return OptType;
}
public void setDateTime(Date DateTime){
this.DateTime = DateTime;
}
public Date getDateTime(){
return DateTime;
}
/*
*数据库查询参数
*/
@QualifiLimit(name="limit")
private Integer limit;
@QualifiOffset(name="offset")
private Integer offset;
@QualifiNotIn(name="notIn")
private String notIn;
@QualifiSort(name="sort")
private String sort;
@QualifiOrder(name="order")
private String order;
@QualifiWhere(name="where")
private String[] where;
@QualifiWhereTerm(name="whereTerm")
private String whereTerm;
public void setLimit(Integer limit){
this.limit = limit;
}
public Integer getLimit(){
return limit;
}
public void setOffset(Integer offset){
this.offset = offset;
}
public Integer getOffset(){
return offset;
}
public void setNotIn(String notIn){
this.notIn = notIn;
}
public String getNotIn(){
return notIn;
}
public void setSort(String sort){
this.sort = sort;
}
public String getSort(){
return sort;
}
public void setOrder(String order){
this.order = order;
}
public String getOrder(){
return order;
}
public void setWhere(String[] where){
this.where = where;
}
public String[] getWhere(){
return where;
}
public void setWhereTerm(String whereTerm){
this.whereTerm = whereTerm;
}
public String getWhereTerm(){
return whereTerm;
}
}
|
UTF-8
|
Java
| 2,524 |
java
|
FileRalateParent.java
|
Java
|
[] | null |
[] |
package com.voucher.manage.daoModel.TTT;
import java.util.Date;
import java.io.Serializable;
import com.voucher.manage.daoSQL.annotations.*;
@DBTable(name="[FileRalateParent]")
public class FileRalateParent implements Serializable{
private static final long serialVersionUID = 1L;
@SQLString(name="GUID")
private String GUID;
@SQLString(name="RoomGUID")
private String RoomGUID;
@SQLString(name="FileName")
private String FileName;
@SQLString(name="OptType")
private String OptType;
@SQLDateTime(name="DateTime")
private Date DateTime;
public void setGUID(String GUID){
this.GUID = GUID;
}
public String getGUID(){
return GUID;
}
public void setRoomGUID(String RoomGUID){
this.RoomGUID = RoomGUID;
}
public String getRoomGUID(){
return RoomGUID;
}
public void setFileName(String FileName){
this.FileName = FileName;
}
public String getFileName(){
return FileName;
}
public void setOptType(String OptType){
this.OptType = OptType;
}
public String getOptType(){
return OptType;
}
public void setDateTime(Date DateTime){
this.DateTime = DateTime;
}
public Date getDateTime(){
return DateTime;
}
/*
*数据库查询参数
*/
@QualifiLimit(name="limit")
private Integer limit;
@QualifiOffset(name="offset")
private Integer offset;
@QualifiNotIn(name="notIn")
private String notIn;
@QualifiSort(name="sort")
private String sort;
@QualifiOrder(name="order")
private String order;
@QualifiWhere(name="where")
private String[] where;
@QualifiWhereTerm(name="whereTerm")
private String whereTerm;
public void setLimit(Integer limit){
this.limit = limit;
}
public Integer getLimit(){
return limit;
}
public void setOffset(Integer offset){
this.offset = offset;
}
public Integer getOffset(){
return offset;
}
public void setNotIn(String notIn){
this.notIn = notIn;
}
public String getNotIn(){
return notIn;
}
public void setSort(String sort){
this.sort = sort;
}
public String getSort(){
return sort;
}
public void setOrder(String order){
this.order = order;
}
public String getOrder(){
return order;
}
public void setWhere(String[] where){
this.where = where;
}
public String[] getWhere(){
return where;
}
public void setWhereTerm(String whereTerm){
this.whereTerm = whereTerm;
}
public String getWhereTerm(){
return whereTerm;
}
}
| 2,524 | 0.676096 | 0.675697 | 147 | 15.517007 | 14.974515 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.965986 | false | false |
15
|
5f6d2ceb0cb7f76083758b74e1720c2898cc7978
| 8,693,013,809,606 |
92047f5e124a12da106f8f9c04eb74a1f682a5f0
|
/app/src/main/java/sakhcomestate/com/sakhcomestateparser/Views/SakhImageView.java
|
b6fcdcdeebe447765c92ee537b6c0b8204814d3b
|
[] |
no_license
|
whizzzkey/SakhComEstateParser
|
https://github.com/whizzzkey/SakhComEstateParser
|
03ca883de06246b131ed5c2ddbeecee41a01d2ee
|
2900d02c6b54eb05149ccdb94249ad82f4826cc7
|
refs/heads/master
| 2016-06-03T09:14:27.581000 | 2016-05-31T20:45:12 | 2016-05-31T20:45:12 | 47,080,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sakhcomestate.com.sakhcomestateparser.Views;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import sakhcomestate.com.sakhcomestateparser.Activity.FullScreenImageActivity;
import sakhcomestate.com.sakhcomestateparser.R;
import sakhcomestate.com.sakhcomestateparser.Util.OnLoadImageFinishListener;
/**
* Created by Eugene on 06.01.2016.
*/
public class SakhImageView extends LinearLayout implements OnLoadImageFinishListener {
private Handler mHandler = new Handler();
private ViewFlipper mFlipper = null;
private ImageView mImageView = null;
private LayoutInflater mInflater = null;
private Bitmap mImage = null;
private boolean mOnClickFlag = false;
public SakhImageView(Context context){
super(context);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initView(mInflater.inflate(R.layout.layout_sakh_image, this, true));
}
public SakhImageView(Context context, AttributeSet attrs){
super(context,attrs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initView(mInflater.inflate(R.layout.layout_sakh_image, this, true));
}
public SakhImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initView(mInflater.inflate(R.layout.layout_sakh_image, this, true));
}
private void initView(View view) {
mFlipper = (ViewFlipper) view.findViewById(R.id.flipper);
mImageView = (ImageView) view.findViewById(R.id.image);
}
public Bitmap getImage(){
return mImage;
}
public void setImage(Bitmap image) {
mImageView.setImageBitmap(image);
mFlipper.setDisplayedChild(1);
}
public void setImageUrl(String url){
mFlipper.setDisplayedChild(0);
downloadImage(url,this);
}
public void downloadImage(final String url, final OnLoadImageFinishListener listener) {
if(listener!=null){
new Thread(new Runnable() {
public void run() {
Bitmap mImage = null;
try {
InputStream is;
is = (InputStream) new URL(url).getContent();
mImage= BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
if(mImage!=null){
listener.onImage(mImage);
}
}
}).start();
}
}
public void onImage(final Bitmap image) {
mImage=image;
mHandler.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(image);
if(mOnClickFlag){
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(v.getContext(), FullScreenImageActivity.class);
intent.putExtra("IMAGEBYTEARRAY", byteArray);
v.getContext().startActivity(intent);
stream.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
}
mFlipper.setDisplayedChild(1);
}
});
}
public void setOnClickFlag(boolean flg){
mOnClickFlag = flg;
}
}
|
UTF-8
|
Java
| 4,489 |
java
|
SakhImageView.java
|
Java
|
[
{
"context": "Util.OnLoadImageFinishListener;\n\n/**\n * Created by Eugene on 06.01.2016.\n */\npublic class SakhImageView ext",
"end": 733,
"score": 0.9134542346000671,
"start": 727,
"tag": "NAME",
"value": "Eugene"
}
] | null |
[] |
package sakhcomestate.com.sakhcomestateparser.Views;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import sakhcomestate.com.sakhcomestateparser.Activity.FullScreenImageActivity;
import sakhcomestate.com.sakhcomestateparser.R;
import sakhcomestate.com.sakhcomestateparser.Util.OnLoadImageFinishListener;
/**
* Created by Eugene on 06.01.2016.
*/
public class SakhImageView extends LinearLayout implements OnLoadImageFinishListener {
private Handler mHandler = new Handler();
private ViewFlipper mFlipper = null;
private ImageView mImageView = null;
private LayoutInflater mInflater = null;
private Bitmap mImage = null;
private boolean mOnClickFlag = false;
public SakhImageView(Context context){
super(context);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initView(mInflater.inflate(R.layout.layout_sakh_image, this, true));
}
public SakhImageView(Context context, AttributeSet attrs){
super(context,attrs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initView(mInflater.inflate(R.layout.layout_sakh_image, this, true));
}
public SakhImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initView(mInflater.inflate(R.layout.layout_sakh_image, this, true));
}
private void initView(View view) {
mFlipper = (ViewFlipper) view.findViewById(R.id.flipper);
mImageView = (ImageView) view.findViewById(R.id.image);
}
public Bitmap getImage(){
return mImage;
}
public void setImage(Bitmap image) {
mImageView.setImageBitmap(image);
mFlipper.setDisplayedChild(1);
}
public void setImageUrl(String url){
mFlipper.setDisplayedChild(0);
downloadImage(url,this);
}
public void downloadImage(final String url, final OnLoadImageFinishListener listener) {
if(listener!=null){
new Thread(new Runnable() {
public void run() {
Bitmap mImage = null;
try {
InputStream is;
is = (InputStream) new URL(url).getContent();
mImage= BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
if(mImage!=null){
listener.onImage(mImage);
}
}
}).start();
}
}
public void onImage(final Bitmap image) {
mImage=image;
mHandler.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(image);
if(mOnClickFlag){
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(v.getContext(), FullScreenImageActivity.class);
intent.putExtra("IMAGEBYTEARRAY", byteArray);
v.getContext().startActivity(intent);
stream.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
}
mFlipper.setDisplayedChild(1);
}
});
}
public void setOnClickFlag(boolean flg){
mOnClickFlag = flg;
}
}
| 4,489 | 0.589886 | 0.586768 | 129 | 33.79845 | 26.661932 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.620155 | false | false |
15
|
f126c6c68cf83e16dee44aac1c391edd9eb34bf1
| 14,276,471,295,097 |
5d324a018ea0ed2a5f8eb41fecae8f7cee0e2a0e
|
/src/com/sdz/test2/Main.java
|
334821b9017e7827169dabbe90f8a3879c5dff59
|
[] |
no_license
|
AMRANImohand/Java-OBJ
|
https://github.com/AMRANImohand/Java-OBJ
|
015a665afcdaf7b553b3b5a0b350ad7b9841f417
|
03e282db1008ecc686d0de397bbd5ce79f1626c0
|
refs/heads/master
| 2022-04-06T22:33:06.501000 | 2020-01-29T20:43:12 | 2020-01-29T20:43:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sdz.test2;
import com.sdz.test.A;
import com.sdz.test.B;
public class Main {
public static void main(String[] args){
A a = new A();
B b = new B();
//Aucun problème ici
}
}
|
UTF-8
|
Java
| 208 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package com.sdz.test2;
import com.sdz.test.A;
import com.sdz.test.B;
public class Main {
public static void main(String[] args){
A a = new A();
B b = new B();
//Aucun problème ici
}
}
| 208 | 0.603865 | 0.599034 | 12 | 16.25 | 12.152675 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false |
15
|
392ae16b570861bea746bd3fd29a9b5465b37d40
| 10,531,259,831,142 |
73c1bbe6b21e74d7fa30234136bd8485987fae42
|
/demo01Log/src/main/java/cn/itcast/bigdata/weblog/clickstream/pageview/vist/ClickStreamVistMain.java
|
a0dfacd1f57008ceab37eb9264366e22a2cc8ec0
|
[] |
no_license
|
jundaodao/clear_data
|
https://github.com/jundaodao/clear_data
|
b341802a286f4babbdfe1051302059cf0663627a
|
401e0870707567bce7f0fd657c8d4541a8055e88
|
refs/heads/master
| 2020-04-08T19:23:35.402000 | 2018-11-29T11:17:31 | 2018-11-29T11:17:31 | 159,653,147 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.itcast.bigdata.weblog.clickstream.pageview.vist;
import cn.itcast.bigdata.weblog.mrbean.PageVistBean;
import cn.itcast.bigdata.weblog.mrbean.VistBean;
import cn.itcast.bigdata.weblog.utils.DateUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.net.URI;
public class ClickStreamVistMain extends Configured implements Tool {
@Override
public int run(String[] strings) throws Exception {
//获取job
Job job = Job.getInstance(super.getConf());
//本地模式运行开始--------------------------------------------
//输入文件
//TextInputFormat.addInputPath(job,new Path("file:///D:\\大数据课程\\day08_sqoop\\8、大数据离线第八天\\日志文件数据\\pageview"));
//输入文件类型
//job.setInputFormatClass(TextInputFormat.class);
//输出文件
//TextOutputFormat.setOutputPath(job,new Path("file:///D:\\大数据课程\\day08_sqoop\\8、大数据离线第八天\\日志文件数据\\vist"));
//输出文件格式
//job.setOutputFormatClass(TextOutputFormat.class);
//本地模式运行结束--------------------------------------------
//集群模式运行开始
String inputPath="hdfs://node01:8020/weblog/"+ DateUtil.getYesterday()+"/pageview";
String outputPath="hdfs://node01:8020/weblog/"+DateUtil.getYesterday()+"" +
"/visit";
//获取文件系统
FileSystem fileSystem = FileSystem.get(new URI("hdfs:///node01:8020"), super.getConf());
if(fileSystem.exists(new Path(outputPath))){
fileSystem.delete(new Path(outputPath),true);
}
fileSystem.close();
//定义输入路径
FileInputFormat.setInputPaths(job,new Path(inputPath));
//定义输入文件类型
job.setInputFormatClass(TextInputFormat.class);
//定义输出路径
FileOutputFormat.setOutputPath(job,new Path(outputPath));
job.setOutputFormatClass(TextOutputFormat.class);
//定义打包方式
job.setJarByClass(ClickStreamVistMain.class);
//配置mapper
job.setMapperClass(ClickStreamVistMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(PageVistBean.class);
//配置reduce
job.setReducerClass(ClickStreamVistReduce.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(VistBean.class);
//开启
boolean b = job.waitForCompletion(true);
return b?0:1;
}
public static void main(String[] args) throws Exception {
int run = ToolRunner.run(new Configuration(), new ClickStreamVistMain(), args);
System.exit(run);
}
}
|
UTF-8
|
Java
| 3,391 |
java
|
ClickStreamVistMain.java
|
Java
|
[] | null |
[] |
package cn.itcast.bigdata.weblog.clickstream.pageview.vist;
import cn.itcast.bigdata.weblog.mrbean.PageVistBean;
import cn.itcast.bigdata.weblog.mrbean.VistBean;
import cn.itcast.bigdata.weblog.utils.DateUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.net.URI;
public class ClickStreamVistMain extends Configured implements Tool {
@Override
public int run(String[] strings) throws Exception {
//获取job
Job job = Job.getInstance(super.getConf());
//本地模式运行开始--------------------------------------------
//输入文件
//TextInputFormat.addInputPath(job,new Path("file:///D:\\大数据课程\\day08_sqoop\\8、大数据离线第八天\\日志文件数据\\pageview"));
//输入文件类型
//job.setInputFormatClass(TextInputFormat.class);
//输出文件
//TextOutputFormat.setOutputPath(job,new Path("file:///D:\\大数据课程\\day08_sqoop\\8、大数据离线第八天\\日志文件数据\\vist"));
//输出文件格式
//job.setOutputFormatClass(TextOutputFormat.class);
//本地模式运行结束--------------------------------------------
//集群模式运行开始
String inputPath="hdfs://node01:8020/weblog/"+ DateUtil.getYesterday()+"/pageview";
String outputPath="hdfs://node01:8020/weblog/"+DateUtil.getYesterday()+"" +
"/visit";
//获取文件系统
FileSystem fileSystem = FileSystem.get(new URI("hdfs:///node01:8020"), super.getConf());
if(fileSystem.exists(new Path(outputPath))){
fileSystem.delete(new Path(outputPath),true);
}
fileSystem.close();
//定义输入路径
FileInputFormat.setInputPaths(job,new Path(inputPath));
//定义输入文件类型
job.setInputFormatClass(TextInputFormat.class);
//定义输出路径
FileOutputFormat.setOutputPath(job,new Path(outputPath));
job.setOutputFormatClass(TextOutputFormat.class);
//定义打包方式
job.setJarByClass(ClickStreamVistMain.class);
//配置mapper
job.setMapperClass(ClickStreamVistMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(PageVistBean.class);
//配置reduce
job.setReducerClass(ClickStreamVistReduce.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(VistBean.class);
//开启
boolean b = job.waitForCompletion(true);
return b?0:1;
}
public static void main(String[] args) throws Exception {
int run = ToolRunner.run(new Configuration(), new ClickStreamVistMain(), args);
System.exit(run);
}
}
| 3,391 | 0.660515 | 0.652243 | 73 | 41.054794 | 26.807734 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.69863 | false | false |
15
|
9dfea8174f450aebb470828f940e911f60bd9cbc
| 16,003,048,198,911 |
dd345cd2aa97a691af73b2da548f4fa21a075ad6
|
/Spring/Spring_Rest/RestQ3_AddressInfo/src/main/java/com/priyanka/yadav/AddressController.java
|
559bd65ef54c5efd5ec94cd022592fddaddd6f03
|
[] |
no_license
|
PiyuY/Priyanka_Yadav_JFSReact_Assignment
|
https://github.com/PiyuY/Priyanka_Yadav_JFSReact_Assignment
|
eb842062e1b84954157e799081b1e0cd93653512
|
c7fba36677b4e2f10cffcbb0ea74919e302c1198
|
refs/heads/master
| 2023-09-02T16:27:29.762000 | 2021-11-17T14:29:32 | 2021-11-17T14:29:32 | 419,645,698 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.priyanka.yadav;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AddressController {
@GetMapping("/getAddress/{zip}")
public Address getAddressByZip(@PathVariable("zip") int zipCode) {
Address address = new Address(99501, "AK", "US", "ANCHORAGE");
if(zipCode==99501) {
return address;
}else {
return null;
}
}
}
|
UTF-8
|
Java
| 522 |
java
|
AddressController.java
|
Java
|
[] | null |
[] |
package com.priyanka.yadav;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AddressController {
@GetMapping("/getAddress/{zip}")
public Address getAddressByZip(@PathVariable("zip") int zipCode) {
Address address = new Address(99501, "AK", "US", "ANCHORAGE");
if(zipCode==99501) {
return address;
}else {
return null;
}
}
}
| 522 | 0.733716 | 0.714559 | 21 | 23.857143 | 24.024364 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.904762 | false | false |
15
|
d142fb68758ba922d94a0ed16f6572cd6fd40f90
| 2,765,958,983,641 |
900c9ee707e83d71b3d135a8f0a6d006c4760e62
|
/transportSystem/src/main/java/com/transport/system/controller/UserControllers.java
|
f2caf08c225c115f45c7da442f65a809185ba097
|
[] |
no_license
|
artemonLL/transport_system
|
https://github.com/artemonLL/transport_system
|
8ae462d009db6b986cad5eceac895f0a812cf245
|
513d5613e44e2e6d481d66d8ddf62c200c4b1f27
|
refs/heads/master
| 2021-05-03T15:16:30.384000 | 2018-04-10T06:39:12 | 2018-04-10T06:39:12 | 120,474,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.transport.system.controller;
import com.transport.system.dao.UserDao;
import com.transport.system.model.*;
import com.transport.system.service.*;
import com.transport.system.validator.UserValidator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* The User controller, which allows user to view pages.
*/
@Controller
@RequestMapping
public class UserControllers {
private static final Logger logr = Logger.getLogger(TrainStationScheduleController.class);
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@Autowired
private UserValidator userValidator;
@Autowired
ScheduleService scheduleService;
@Autowired
private TicketService ticketService;
@Autowired
private TrainService trainService;
@Autowired
private StationService stationService;
@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
@RequestMapping(value = "/tickets")
public ModelAndView tickets(@ModelAttribute Ticket ticket) {
logr.info(String.format("-----------/tickets/ USER GET---------------Yes"));
ModelAndView mod = new ModelAndView("tickets");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//GET USER FROM SECURITY
Object obj = auth.getPrincipal();
String username = "";
if (obj instanceof UserDetails) {
username = ((UserDetails) obj).getUsername();
} else {
username = obj.toString();
}
User user1 = userService.getUserByName(username);
logr.info(String.format("-----------/tickets/ USER GET---------------Yes"));
List<Ticket> ticketList = ticketService.getTicketListsByUser(user1);
logr.info(String.format("-----------/tickets/ GET USER TICKETS---------------Yes" + ticketList.size()));
mod.addObject("ticketList", ticketList);
return mod;
}
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.addUser(userForm);
securityService.autoLogin(userForm.getUsername(), userForm.getConfirmPassword());
return "redirect:/home";
}
@RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET)
public ModelAndView home(@ModelAttribute Selectform selectform) {
ModelAndView mod = new ModelAndView("home");
mod.addObject("stationList", stationService.getStationList());
mod.addObject("selectform", new Selectform());
return mod;
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null) {
model.addAttribute("error", "Username or Password is incorrect.");
}
if (logout != null) {
model.addAttribute("massage", "Logget out successfully.");
}
return "login";
}
@RequestMapping(value = "/buybuybuy/{train_number}")
public ModelAndView buybuybuy(@PathVariable String train_number) {
logr.info(String.format("-----------train number " + train_number));
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object obj = auth.getPrincipal();
String username = "";
if (obj instanceof UserDetails) {
username = ((UserDetails) obj).getUsername();
} else {
username = obj.toString();
}
User user1 = userService.getUserByName(username);
logr.info(String.format("-----------User " + user1.getUsername()));
Train train = trainService.getTrainByName(train_number);
logr.info(String.format("-----------train train " + train.getTrain_number()));
if (trainService.getFreePlaces(train.getTrain_id()) != 0) {
}
Ticket ticket = new Ticket();
ModelAndView mod = new ModelAndView("redirect:tickets");
return mod;
}
@RequestMapping("saveuser")
public String saveuser(Model model) {
return "registration";
}
}
|
UTF-8
|
Java
| 5,083 |
java
|
UserControllers.java
|
Java
|
[] | null |
[] |
package com.transport.system.controller;
import com.transport.system.dao.UserDao;
import com.transport.system.model.*;
import com.transport.system.service.*;
import com.transport.system.validator.UserValidator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* The User controller, which allows user to view pages.
*/
@Controller
@RequestMapping
public class UserControllers {
private static final Logger logr = Logger.getLogger(TrainStationScheduleController.class);
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@Autowired
private UserValidator userValidator;
@Autowired
ScheduleService scheduleService;
@Autowired
private TicketService ticketService;
@Autowired
private TrainService trainService;
@Autowired
private StationService stationService;
@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
@RequestMapping(value = "/tickets")
public ModelAndView tickets(@ModelAttribute Ticket ticket) {
logr.info(String.format("-----------/tickets/ USER GET---------------Yes"));
ModelAndView mod = new ModelAndView("tickets");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//GET USER FROM SECURITY
Object obj = auth.getPrincipal();
String username = "";
if (obj instanceof UserDetails) {
username = ((UserDetails) obj).getUsername();
} else {
username = obj.toString();
}
User user1 = userService.getUserByName(username);
logr.info(String.format("-----------/tickets/ USER GET---------------Yes"));
List<Ticket> ticketList = ticketService.getTicketListsByUser(user1);
logr.info(String.format("-----------/tickets/ GET USER TICKETS---------------Yes" + ticketList.size()));
mod.addObject("ticketList", ticketList);
return mod;
}
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.addUser(userForm);
securityService.autoLogin(userForm.getUsername(), userForm.getConfirmPassword());
return "redirect:/home";
}
@RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET)
public ModelAndView home(@ModelAttribute Selectform selectform) {
ModelAndView mod = new ModelAndView("home");
mod.addObject("stationList", stationService.getStationList());
mod.addObject("selectform", new Selectform());
return mod;
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null) {
model.addAttribute("error", "Username or Password is incorrect.");
}
if (logout != null) {
model.addAttribute("massage", "Logget out successfully.");
}
return "login";
}
@RequestMapping(value = "/buybuybuy/{train_number}")
public ModelAndView buybuybuy(@PathVariable String train_number) {
logr.info(String.format("-----------train number " + train_number));
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object obj = auth.getPrincipal();
String username = "";
if (obj instanceof UserDetails) {
username = ((UserDetails) obj).getUsername();
} else {
username = obj.toString();
}
User user1 = userService.getUserByName(username);
logr.info(String.format("-----------User " + user1.getUsername()));
Train train = trainService.getTrainByName(train_number);
logr.info(String.format("-----------train train " + train.getTrain_number()));
if (trainService.getFreePlaces(train.getTrain_id()) != 0) {
}
Ticket ticket = new Ticket();
ModelAndView mod = new ModelAndView("redirect:tickets");
return mod;
}
@RequestMapping("saveuser")
public String saveuser(Model model) {
return "registration";
}
}
| 5,083 | 0.665552 | 0.664371 | 172 | 28.552326 | 28.802105 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.494186 | false | false |
15
|
7c193239fd5225c2d61cd050584c790d92ad837c
| 2,765,958,982,068 |
555c90b51f3214acc462f2599b8e80796ffa8360
|
/lims/src/cn/nchu/lims/controller/MDStudentController.java
|
bbf5a07777ccae7e63eb6b9498596f895661debf
|
[] |
no_license
|
XIAAMAN/BackstageManageProject
|
https://github.com/XIAAMAN/BackstageManageProject
|
7ae9002135d94e85ed55273544c8ab183d0b679c
|
5c27675fb54b60c8b76a8669fd40d74431afdbd8
|
refs/heads/master
| 2021-08-23T07:20:05.954000 | 2017-12-04T03:12:35 | 2017-12-04T03:12:35 | 112,989,515 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.nchu.lims.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 cn.nchu.lims.dao.MDStudentDao;
import cn.nchu.lims.domain.MDStudent;
import cn.nchu.lims.util.Constant;
import cn.nchu.lims.util.ajax.AjaxJsonRequestDynaPageParam;
import cn.nchu.lims.util.ajax.AjaxJsonReturnDynaPageParam;
import cn.nchu.lims.util.ajax.AjaxJsonReturnParam;
import cn.nchu.lims.util.lang.EnclosureUtil;
import cn.nchu.lims.util.lang.StringUtil;
import cn.nchu.lims.validator.MDStudentValidator;
@Controller
@RequestMapping(value="/mdstudent")
public class MDStudentController {
/**
* 自动注入MDStudentDao,用于Notice的数据库访问
*/
@Autowired
private MDStudentDao mdStudentDao;
/**
* 动态插入MDStudent信息
* @param mdStudent : MDStudetn
* @return AjaxJsonReturnParam
*/
@ResponseBody
@RequestMapping(value="/add", method=RequestMethod.POST)
public AjaxJsonReturnParam add(@RequestBody MDStudent mdStudent) {
try {
// 调用mdStudentValidator.validator检验字段是否符合规范
String message = MDStudentValidator.validator(mdStudent);
if (StringUtil.isNullOrEmpty(message)) { // 如果没有错误信息,返回状态值 0 (成功)
// 调用mdStudentDao.save插入mdStudent信息
mdStudentDao.save(mdStudent);
// 插入成功 0,将查询到的teacher传进回调对象information属性中
return new AjaxJsonReturnParam(0);
}
return new AjaxJsonReturnParam(1, message); //返回失败状态1,错误信息
} catch(Exception e) {
e.printStackTrace();
return new AjaxJsonReturnParam(1, "请求异常,请与管理员联系 "); //返回失败状态1,错误信息
}
}
/**
* 通过id删除MDStudent信息
* @param mdStudent : MDStudent
* @return AjaxJsonReturnParam
*/
@ResponseBody
@RequestMapping(value="/delete")
public AjaxJsonReturnParam delete(
@RequestBody MDStudent mdStudent, HttpServletRequest request) {
mdStudent = mdStudentDao.get(mdStudent); // 调用mdStudentDao.get查询mdStudent信息
if(mdStudent != null) {// 存在,返回成功状态0
mdStudentDao.delete(mdStudent); // 调用mdStudentDao.delete删除mdStudent信息
EnclosureUtil.clearFileOnDisk( // 清楚物理路径下的头像文件
mdStudent.getPhoto(), request, Constant.UPLOAD_MDSTUDENTENCLOSURE_URL);
return new AjaxJsonReturnParam(0);
}
return new AjaxJsonReturnParam(1, "学生编号错误:编号不存在"); // 不存在,返回失败状态0,错误信息
}
/**
* 动态更新teacher信息
* @param mdStudent : MDStudent
* @param AjaxJsonReturnParam
*/
@RequestMapping(value="/update", method=RequestMethod.POST)
@ResponseBody
public AjaxJsonReturnParam update(
@RequestBody MDStudent mdStudent, HttpServletRequest request) {
MDStudent student = mdStudentDao.get(mdStudent); // 调用mdStudentDao.get查询mdStudent信息
if(student != null) { // mdStudent存在,情况
// 调用mdStudentValidator.validator检验字段是否符合规范
String message = MDStudentValidator.updateValidator(mdStudent);
if (StringUtil.isNullOrEmpty(message)) { // 如果没有错误信息,返回状态值 0 (成功)
/*
* 如果被修改记录photo字段是为不为空或者photo被修改
* 删除原物理路径下的头像文件,替换成现在的文件
* 修改photo字段信息
*/
if (!StringUtil.isNullOrEmpty(student.getPhoto())
&& !student.getPhoto().equals(mdStudent.getPhoto())) {
EnclosureUtil.clearFileOnDisk(
student.getPhoto(), request, Constant.UPLOAD_MDSTUDENTENCLOSURE_URL);
}
mdStudentDao.updateDyna(mdStudent); // 调用mdStudentDao.update更新mdStudent信息
mdStudent = mdStudentDao.get(mdStudent); // 调用mdStudentDao.get得到修改后的mdStudent信息
return new AjaxJsonReturnParam(0, mdStudent); // 返回成功状态0和mdStudent信息
}
return new AjaxJsonReturnParam(1, message);
}
return new AjaxJsonReturnParam(1, "学生编号错误:编号不存在"); // mdStudent不存在,返回失败状态0,错误信息
}
/**
* 根据Id查询MDStudent信息
* @param mdStudent : MDStudent
* @return AjaxJsonReturnParam
*/
@RequestMapping(value="/get")
@ResponseBody
public AjaxJsonReturnParam get(@RequestBody MDStudent mdStudent) {
mdStudent = mdStudentDao.get(mdStudent);
if(mdStudent != null) {
return new AjaxJsonReturnParam(0, mdStudent);
}
return new AjaxJsonReturnParam(1, "编号错误:此用户不存在;");
}
/**
* 动态查询MDStudent信息
* @param teacher : MDStudent
* @return 符合动态查询的MDStudent 列表
*/
@RequestMapping("/listDynaPage")
@ResponseBody
public AjaxJsonReturnDynaPageParam<MDStudent> listDynaPage(
@RequestBody AjaxJsonRequestDynaPageParam<MDStudent> ajrdpp) {
int recordCount // 根据前台封装的AjaxJsonRequestDynaPageParam.param信息,查询信息的总数
= mdStudentDao.listDyna(ajrdpp.getParam()).size();
ajrdpp.getPageModel().setRecordCount(recordCount); // 传入查询到的所有MDStudent信息总数
List<MDStudent> teachers = mdStudentDao.listDynaPage(ajrdpp); // 动态查询MDStudent信息
return new AjaxJsonReturnDynaPageParam<MDStudent>(recordCount, teachers);
}
}
|
GB18030
|
Java
| 5,679 |
java
|
MDStudentController.java
|
Java
|
[] | null |
[] |
package cn.nchu.lims.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 cn.nchu.lims.dao.MDStudentDao;
import cn.nchu.lims.domain.MDStudent;
import cn.nchu.lims.util.Constant;
import cn.nchu.lims.util.ajax.AjaxJsonRequestDynaPageParam;
import cn.nchu.lims.util.ajax.AjaxJsonReturnDynaPageParam;
import cn.nchu.lims.util.ajax.AjaxJsonReturnParam;
import cn.nchu.lims.util.lang.EnclosureUtil;
import cn.nchu.lims.util.lang.StringUtil;
import cn.nchu.lims.validator.MDStudentValidator;
@Controller
@RequestMapping(value="/mdstudent")
public class MDStudentController {
/**
* 自动注入MDStudentDao,用于Notice的数据库访问
*/
@Autowired
private MDStudentDao mdStudentDao;
/**
* 动态插入MDStudent信息
* @param mdStudent : MDStudetn
* @return AjaxJsonReturnParam
*/
@ResponseBody
@RequestMapping(value="/add", method=RequestMethod.POST)
public AjaxJsonReturnParam add(@RequestBody MDStudent mdStudent) {
try {
// 调用mdStudentValidator.validator检验字段是否符合规范
String message = MDStudentValidator.validator(mdStudent);
if (StringUtil.isNullOrEmpty(message)) { // 如果没有错误信息,返回状态值 0 (成功)
// 调用mdStudentDao.save插入mdStudent信息
mdStudentDao.save(mdStudent);
// 插入成功 0,将查询到的teacher传进回调对象information属性中
return new AjaxJsonReturnParam(0);
}
return new AjaxJsonReturnParam(1, message); //返回失败状态1,错误信息
} catch(Exception e) {
e.printStackTrace();
return new AjaxJsonReturnParam(1, "请求异常,请与管理员联系 "); //返回失败状态1,错误信息
}
}
/**
* 通过id删除MDStudent信息
* @param mdStudent : MDStudent
* @return AjaxJsonReturnParam
*/
@ResponseBody
@RequestMapping(value="/delete")
public AjaxJsonReturnParam delete(
@RequestBody MDStudent mdStudent, HttpServletRequest request) {
mdStudent = mdStudentDao.get(mdStudent); // 调用mdStudentDao.get查询mdStudent信息
if(mdStudent != null) {// 存在,返回成功状态0
mdStudentDao.delete(mdStudent); // 调用mdStudentDao.delete删除mdStudent信息
EnclosureUtil.clearFileOnDisk( // 清楚物理路径下的头像文件
mdStudent.getPhoto(), request, Constant.UPLOAD_MDSTUDENTENCLOSURE_URL);
return new AjaxJsonReturnParam(0);
}
return new AjaxJsonReturnParam(1, "学生编号错误:编号不存在"); // 不存在,返回失败状态0,错误信息
}
/**
* 动态更新teacher信息
* @param mdStudent : MDStudent
* @param AjaxJsonReturnParam
*/
@RequestMapping(value="/update", method=RequestMethod.POST)
@ResponseBody
public AjaxJsonReturnParam update(
@RequestBody MDStudent mdStudent, HttpServletRequest request) {
MDStudent student = mdStudentDao.get(mdStudent); // 调用mdStudentDao.get查询mdStudent信息
if(student != null) { // mdStudent存在,情况
// 调用mdStudentValidator.validator检验字段是否符合规范
String message = MDStudentValidator.updateValidator(mdStudent);
if (StringUtil.isNullOrEmpty(message)) { // 如果没有错误信息,返回状态值 0 (成功)
/*
* 如果被修改记录photo字段是为不为空或者photo被修改
* 删除原物理路径下的头像文件,替换成现在的文件
* 修改photo字段信息
*/
if (!StringUtil.isNullOrEmpty(student.getPhoto())
&& !student.getPhoto().equals(mdStudent.getPhoto())) {
EnclosureUtil.clearFileOnDisk(
student.getPhoto(), request, Constant.UPLOAD_MDSTUDENTENCLOSURE_URL);
}
mdStudentDao.updateDyna(mdStudent); // 调用mdStudentDao.update更新mdStudent信息
mdStudent = mdStudentDao.get(mdStudent); // 调用mdStudentDao.get得到修改后的mdStudent信息
return new AjaxJsonReturnParam(0, mdStudent); // 返回成功状态0和mdStudent信息
}
return new AjaxJsonReturnParam(1, message);
}
return new AjaxJsonReturnParam(1, "学生编号错误:编号不存在"); // mdStudent不存在,返回失败状态0,错误信息
}
/**
* 根据Id查询MDStudent信息
* @param mdStudent : MDStudent
* @return AjaxJsonReturnParam
*/
@RequestMapping(value="/get")
@ResponseBody
public AjaxJsonReturnParam get(@RequestBody MDStudent mdStudent) {
mdStudent = mdStudentDao.get(mdStudent);
if(mdStudent != null) {
return new AjaxJsonReturnParam(0, mdStudent);
}
return new AjaxJsonReturnParam(1, "编号错误:此用户不存在;");
}
/**
* 动态查询MDStudent信息
* @param teacher : MDStudent
* @return 符合动态查询的MDStudent 列表
*/
@RequestMapping("/listDynaPage")
@ResponseBody
public AjaxJsonReturnDynaPageParam<MDStudent> listDynaPage(
@RequestBody AjaxJsonRequestDynaPageParam<MDStudent> ajrdpp) {
int recordCount // 根据前台封装的AjaxJsonRequestDynaPageParam.param信息,查询信息的总数
= mdStudentDao.listDyna(ajrdpp.getParam()).size();
ajrdpp.getPageModel().setRecordCount(recordCount); // 传入查询到的所有MDStudent信息总数
List<MDStudent> teachers = mdStudentDao.listDynaPage(ajrdpp); // 动态查询MDStudent信息
return new AjaxJsonReturnDynaPageParam<MDStudent>(recordCount, teachers);
}
}
| 5,679 | 0.753815 | 0.749949 | 148 | 32.209461 | 25.964699 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.168919 | false | false |
15
|
a8ecb2066e7959b7a3a81d3011a0fc6a693ce368
| 33,440,615,397,007 |
f2f6f931b0faa0b26023330442dc73608ce562c7
|
/src/com/CS151FinalProject/Main/Controls.java
|
4cda918067eba958cbc8a803a743ee6a42f38341
|
[] |
no_license
|
sgajjar97/CS151-Final-Project
|
https://github.com/sgajjar97/CS151-Final-Project
|
bc63a8dbe0c79a61fb92f0318d8ac63cce18559d
|
f8b4d0baabd41ed3c835ef4b15ad1f1fc3b74d9b
|
refs/heads/master
| 2021-08-09T02:57:15.935000 | 2017-11-12T01:21:18 | 2017-11-12T01:21:18 | 110,391,860 | 0 | 0 | null | true | 2017-11-12T00:33:18 | 2017-11-12T00:33:18 | 2017-11-10T23:13:39 | 2017-11-11T19:54:32 | 31 | 0 | 0 | 0 | null | false | null |
package com.CS151FinalProject.Main;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.Box;
//import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
//import javax.swing.JPanel;
import javax.swing.JTextField;
import com.CS151FinalProject.DShapes.*;
public class Controls {
Random rand = new Random();
String[] fonts = { "Arial", "Times New Roman" };
JButton rectangle;
JButton oval;
JButton line;
JButton text;
JButton setColor;
JButton moveToFront;
JButton moveToBack;
JButton removeShape;
JTextField textField;
JLabel selectTextLabel;
JLabel enterTextLabel;
@SuppressWarnings("rawtypes")
JComboBox fontOptions;
@SuppressWarnings({ "rawtypes", "unchecked" })
public Controls() {
rectangle = new JButton("Rect");
rectangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int place = rand.nextInt(100) + 1;
int size = rand.nextInt(100) + 20;
// System.out.println("Place\t" + place);
DRectangle rect = new DRectangle();
rect.getModel().setX(place);
rect.getModel().setY(place);
rect.getModel().setWidth(size);
rect.getModel().setHeight(size);
WhiteBoard.getWhiteBoard().canvas.addShape(rect);
}
});
oval = new JButton("Oval");
oval.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int place = rand.nextInt(100) + 1;
int size = rand.nextInt(100) + 20;
DOval oval = new DOval();
oval.getModel().setX(place);
oval.getModel().setY(place);
oval.getModel().setWidth(size);
oval.getModel().setHeight(size);
WhiteBoard.getWhiteBoard().canvas.addShape(oval);
}
});
line = new JButton("Line");
text = new JButton("Text");
setColor = new JButton("Color");
setColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (WhiteBoard.getWhiteBoard().canvas.selectedShape != null)
WhiteBoard.getWhiteBoard().canvas.selectedShape.getModel().setColor(JColorChooser.showDialog(null,
"Set Color", WhiteBoard.getWhiteBoard().canvas.selectedShape.getModel().getColor()));
}
});
moveToFront = new JButton("Move to Front");
moveToBack = new JButton("Move to Back");
removeShape = new JButton("Remove Shape");
textField = new JTextField();
textField.setPreferredSize(new Dimension(150, 150));
textField.setMaximumSize(new Dimension(250, 350));
fontOptions = new JComboBox(fonts);
fontOptions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
selectTextLabel = new JLabel("Select Font ");
enterTextLabel = new JLabel("Enter Text ");
}
public Box getControls() {
Box verticalBox = Box.createVerticalBox();
Box firstBox = Box.createHorizontalBox();
firstBox.setPreferredSize(new Dimension(75, 75));
firstBox.add(rectangle);
firstBox.add(oval);
firstBox.add(line);
firstBox.add(text);
firstBox.add(setColor);
Box thirdBox = Box.createHorizontalBox();
thirdBox.add(selectTextLabel);
thirdBox.add(fontOptions);
Box fourthBox = Box.createHorizontalBox();
fourthBox.add(moveToFront);
fourthBox.add(moveToBack);
fourthBox.add(removeShape);
Box fifthBox = Box.createHorizontalBox();
fifthBox.add(enterTextLabel);
fifthBox.add(textField);
verticalBox.add(firstBox);
verticalBox.add(fifthBox);
verticalBox.add(thirdBox);
verticalBox.add(fourthBox);
for (Component comp : verticalBox.getComponents()) {
((JComponent) comp).setAlignmentX(Box.LEFT_ALIGNMENT);
}
return verticalBox;
}
}
|
UTF-8
|
Java
| 3,855 |
java
|
Controls.java
|
Java
|
[] | null |
[] |
package com.CS151FinalProject.Main;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.Box;
//import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
//import javax.swing.JPanel;
import javax.swing.JTextField;
import com.CS151FinalProject.DShapes.*;
public class Controls {
Random rand = new Random();
String[] fonts = { "Arial", "Times New Roman" };
JButton rectangle;
JButton oval;
JButton line;
JButton text;
JButton setColor;
JButton moveToFront;
JButton moveToBack;
JButton removeShape;
JTextField textField;
JLabel selectTextLabel;
JLabel enterTextLabel;
@SuppressWarnings("rawtypes")
JComboBox fontOptions;
@SuppressWarnings({ "rawtypes", "unchecked" })
public Controls() {
rectangle = new JButton("Rect");
rectangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int place = rand.nextInt(100) + 1;
int size = rand.nextInt(100) + 20;
// System.out.println("Place\t" + place);
DRectangle rect = new DRectangle();
rect.getModel().setX(place);
rect.getModel().setY(place);
rect.getModel().setWidth(size);
rect.getModel().setHeight(size);
WhiteBoard.getWhiteBoard().canvas.addShape(rect);
}
});
oval = new JButton("Oval");
oval.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int place = rand.nextInt(100) + 1;
int size = rand.nextInt(100) + 20;
DOval oval = new DOval();
oval.getModel().setX(place);
oval.getModel().setY(place);
oval.getModel().setWidth(size);
oval.getModel().setHeight(size);
WhiteBoard.getWhiteBoard().canvas.addShape(oval);
}
});
line = new JButton("Line");
text = new JButton("Text");
setColor = new JButton("Color");
setColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (WhiteBoard.getWhiteBoard().canvas.selectedShape != null)
WhiteBoard.getWhiteBoard().canvas.selectedShape.getModel().setColor(JColorChooser.showDialog(null,
"Set Color", WhiteBoard.getWhiteBoard().canvas.selectedShape.getModel().getColor()));
}
});
moveToFront = new JButton("Move to Front");
moveToBack = new JButton("Move to Back");
removeShape = new JButton("Remove Shape");
textField = new JTextField();
textField.setPreferredSize(new Dimension(150, 150));
textField.setMaximumSize(new Dimension(250, 350));
fontOptions = new JComboBox(fonts);
fontOptions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
selectTextLabel = new JLabel("Select Font ");
enterTextLabel = new JLabel("Enter Text ");
}
public Box getControls() {
Box verticalBox = Box.createVerticalBox();
Box firstBox = Box.createHorizontalBox();
firstBox.setPreferredSize(new Dimension(75, 75));
firstBox.add(rectangle);
firstBox.add(oval);
firstBox.add(line);
firstBox.add(text);
firstBox.add(setColor);
Box thirdBox = Box.createHorizontalBox();
thirdBox.add(selectTextLabel);
thirdBox.add(fontOptions);
Box fourthBox = Box.createHorizontalBox();
fourthBox.add(moveToFront);
fourthBox.add(moveToBack);
fourthBox.add(removeShape);
Box fifthBox = Box.createHorizontalBox();
fifthBox.add(enterTextLabel);
fifthBox.add(textField);
verticalBox.add(firstBox);
verticalBox.add(fifthBox);
verticalBox.add(thirdBox);
verticalBox.add(fourthBox);
for (Component comp : verticalBox.getComponents()) {
((JComponent) comp).setAlignmentX(Box.LEFT_ALIGNMENT);
}
return verticalBox;
}
}
| 3,855 | 0.710246 | 0.69987 | 201 | 18.179104 | 20.139507 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.60199 | false | false |
15
|
f06e6db0c006328e463ea5132257f880985828eb
| 22,436,909,184,078 |
7bc766a329f3c65ec309cd0a543e9f7f1870378a
|
/app/src/main/java/com/tiomamaster/customizableconverter/data/Repositories.java
|
33f4a8008aa9f52e8a9f9395d66ba9185f61038e
|
[
"MIT"
] |
permissive
|
tiomamaster/CustomizableConverter
|
https://github.com/tiomamaster/CustomizableConverter
|
765c18a49cab4ba6fc8de026a6aa05a9a6a83856
|
a6286845fd9601e673b7a2550a0748dfd8d5a96e
|
refs/heads/master
| 2021-11-24T13:39:26.005000 | 2021-10-29T15:40:59 | 2021-10-29T15:40:59 | 85,875,163 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tiomamaster.customizableconverter.data;
import android.content.Context;
import android.support.annotation.NonNull;
public class Repositories {
private static ConvertersRepository convertersRepo = null;
private static SettingsRepository settingsRepo = null;
private Repositories() {}
public synchronized static ConvertersRepository getInMemoryRepoInstance(
@NonNull ConvertersServiceApi convertersServiceApi) {
if (convertersRepo == null) {
convertersRepo = new InMemoryConvertersRepository(convertersServiceApi);
}
return convertersRepo;
}
public synchronized static SettingsRepository getInMemoryRepoInstance(Context c) {
if (settingsRepo == null) {
settingsRepo = new InMemorySettingsRepository(c);
}
return settingsRepo;
}
}
|
UTF-8
|
Java
| 858 |
java
|
Repositories.java
|
Java
|
[] | null |
[] |
package com.tiomamaster.customizableconverter.data;
import android.content.Context;
import android.support.annotation.NonNull;
public class Repositories {
private static ConvertersRepository convertersRepo = null;
private static SettingsRepository settingsRepo = null;
private Repositories() {}
public synchronized static ConvertersRepository getInMemoryRepoInstance(
@NonNull ConvertersServiceApi convertersServiceApi) {
if (convertersRepo == null) {
convertersRepo = new InMemoryConvertersRepository(convertersServiceApi);
}
return convertersRepo;
}
public synchronized static SettingsRepository getInMemoryRepoInstance(Context c) {
if (settingsRepo == null) {
settingsRepo = new InMemorySettingsRepository(c);
}
return settingsRepo;
}
}
| 858 | 0.722611 | 0.722611 | 28 | 29.678572 | 28.09811 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false |
15
|
5b475138474b69a384831a2b4e84c8b510db537d
| 8,632,884,299,998 |
6cfc2fd7f43229c0e5b86018efc879b4fd4398fa
|
/Cart.java
|
5bfc238dfa9c6f89c17ee18fb92e638733381507
|
[] |
no_license
|
AykaSova/examplemod
|
https://github.com/AykaSova/examplemod
|
d773e3e5924bc30fdaf58b3bd4b26e1855265245
|
b42bd3c5e37f5e9c69a6b3f2faa248a8126a9579
|
refs/heads/master
| 2020-03-27T06:00:31.103000 | 2018-08-25T06:31:00 | 2018-08-25T06:31:00 | 146,071,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.Forge.Mod1;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraftforge.event.entity.minecart.MinecartCollisionEvent;
public class Cart {
@SubscribeEvent
public void explode(MinecartCollisionEvent event)
{
EntityMinecart cart = event.minecart;
cart.worldObj.createExplosion(cart, cart.posX, cart.posY, cart.posZ, 2, false);
}
}
|
UTF-8
|
Java
| 442 |
java
|
Cart.java
|
Java
|
[] | null |
[] |
package com.Forge.Mod1;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraftforge.event.entity.minecart.MinecartCollisionEvent;
public class Cart {
@SubscribeEvent
public void explode(MinecartCollisionEvent event)
{
EntityMinecart cart = event.minecart;
cart.worldObj.createExplosion(cart, cart.posX, cart.posY, cart.posZ, 2, false);
}
}
| 442 | 0.764706 | 0.760181 | 16 | 25.625 | 27.048279 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3125 | false | false |
15
|
78a6075bf1a92aa337d50b4404efae8bf4300e83
| 33,182,917,372,041 |
11404f4d4c3cfacbe2a5429421b416d1d1721d67
|
/src/test/java/searching/IndexEquallingValueTest.java
|
db24d54f068c43cfc3d85aec1d1b1934f1bec21e
|
[] |
no_license
|
atiwari0802/ProgrammingInterviews
|
https://github.com/atiwari0802/ProgrammingInterviews
|
3f71106e0e7a119c98efc7aa8bb214cca1ee528b
|
336301d9dba0897b7d9c80302bdd89cb9ee53274
|
refs/heads/master
| 2021-07-04T03:52:48.553000 | 2020-05-18T00:06:42 | 2020-05-18T00:06:42 | 182,350,219 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package searching;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
public class IndexEquallingValueTest {
private IndexEquallingValue indexEquallingValue;
@BeforeEach
public void setup() {
indexEquallingValue = new IndexEquallingValue();
}
@Test
public void testIndexEquallingValue() {
List<Integer> input = Arrays.asList(-1, 0, 1, 3, 5, 77, 90);
int result = indexEquallingValue.findIndexEqualToValue(input);
Assertions.assertEquals(3, result);
}
}
|
UTF-8
|
Java
| 635 |
java
|
IndexEquallingValueTest.java
|
Java
|
[] | null |
[] |
package searching;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
public class IndexEquallingValueTest {
private IndexEquallingValue indexEquallingValue;
@BeforeEach
public void setup() {
indexEquallingValue = new IndexEquallingValue();
}
@Test
public void testIndexEquallingValue() {
List<Integer> input = Arrays.asList(-1, 0, 1, 3, 5, 77, 90);
int result = indexEquallingValue.findIndexEqualToValue(input);
Assertions.assertEquals(3, result);
}
}
| 635 | 0.711811 | 0.696063 | 27 | 22.518518 | 22.391087 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
15
|
f954d380e9fb703d3b624dc93a495eb5730bbc23
| 12,077,448,079,418 |
712a5e8475b6c9276bd4f8f857be95fdf6f30b9f
|
/com/facebook/ads/internal/p027l/C0660b.java
|
f7ac989fdfdba16b462c266d1ba668eca4e6c0a4
|
[] |
no_license
|
swapnilsen/OCR_2
|
https://github.com/swapnilsen/OCR_2
|
b29bd22a51203b4d39c2cc8cb03c50a85a81218f
|
1889d208e17e94a55ddeae91336fe92110e1bd2d
|
refs/heads/master
| 2021-01-20T08:46:03.508000 | 2017-05-03T19:50:52 | 2017-05-03T19:50:52 | 90,187,623 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.facebook.ads.internal.p027l;
import android.content.Context;
import com.facebook.ads.internal.C0455a;
import com.facebook.ads.internal.C0536d;
import com.facebook.ads.internal.C0649j;
import com.facebook.ads.internal.p021m.C0675b;
import com.facebook.ads.internal.p021m.C0676c;
import com.facebook.ads.internal.p021m.C0708r;
import com.facebook.ads.internal.p021m.ak;
import com.facebook.ads.internal.p021m.ak.C0672a;
import com.facebook.ads.internal.p027l.C0664e.C0663a;
import com.facebook.ads.internal.p031g.C0557d;
import com.facebook.ads.internal.p031g.C0561f;
import com.facebook.ads.internal.p031g.C0564i;
import com.facebook.ads.internal.p033j.p034a.C0599a;
import com.facebook.ads.internal.p033j.p034a.C0600b;
import com.facebook.ads.internal.p033j.p034a.C0611m;
import com.facebook.ads.internal.p033j.p034a.C0612n;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import net.nend.android.NendIconError;
import org.json.JSONException;
/* renamed from: com.facebook.ads.internal.l.b */
public class C0660b {
private static final C0676c f1543i;
private static final ThreadPoolExecutor f1544j;
Map<String, String> f1545a;
private final Context f1546b;
private final C0662d f1547c;
private final C0649j f1548d;
private C0520a f1549e;
private C0561f f1550f;
private C0599a f1551g;
private final String f1552h;
/* renamed from: com.facebook.ads.internal.l.b.a */
public interface C0520a {
void m1557a(C0536d c0536d);
void m1558a(C0665f c0665f);
}
/* renamed from: com.facebook.ads.internal.l.b.1 */
class C06571 implements Runnable {
final /* synthetic */ C0561f f1539a;
final /* synthetic */ C0660b f1540b;
C06571(C0660b c0660b, C0561f c0561f) {
this.f1540b = c0660b;
this.f1539a = c0561f;
}
public void run() {
C0564i.m1747b(this.f1540b.f1546b);
this.f1540b.f1545a = this.f1539a.m1742e();
try {
this.f1540b.f1551g = ak.m2168b(this.f1540b.f1546b, this.f1539a.f1286e);
this.f1540b.f1551g.m1885a(this.f1540b.f1552h, this.f1540b.f1551g.m1892b().m1928a(this.f1540b.f1545a), this.f1540b.m2111b());
} catch (Exception e) {
this.f1540b.m2106a(C0455a.AD_REQUEST_FAILED.m1130a(e.getMessage()));
}
}
}
/* renamed from: com.facebook.ads.internal.l.b.2 */
class C06582 extends C0600b {
final /* synthetic */ C0660b f1541a;
C06582(C0660b c0660b) {
this.f1541a = c0660b;
}
public void m2101a(C0611m c0611m) {
C0708r.m2284b(this.f1541a.f1550f);
this.f1541a.f1551g = null;
try {
C0612n a = c0611m.m1920a();
if (a != null) {
String e = a.m1925e();
C0664e a2 = this.f1541a.f1547c.m2126a(e);
if (a2.m2127a() == C0663a.ERROR) {
C0666g c0666g = (C0666g) a2;
String c = c0666g.m2129c();
this.f1541a.m2106a(C0455a.m1128a(c0666g.m2130d(), C0455a.ERROR_MESSAGE).m1130a(c == null ? e : c));
return;
}
}
} catch (JSONException e2) {
}
this.f1541a.m2106a(new C0536d(C0455a.NETWORK_ERROR, c0611m.getMessage()));
}
public void m2102a(C0612n c0612n) {
if (c0612n != null) {
String e = c0612n.m1925e();
C0708r.m2284b(this.f1541a.f1550f);
this.f1541a.f1551g = null;
this.f1541a.m2110a(e);
}
}
public void m2103a(Exception exception) {
if (C0611m.class.equals(exception.getClass())) {
m2101a((C0611m) exception);
} else {
this.f1541a.m2106a(new C0536d(C0455a.NETWORK_ERROR, exception.getMessage()));
}
}
}
/* renamed from: com.facebook.ads.internal.l.b.3 */
static /* synthetic */ class C06593 {
static final /* synthetic */ int[] f1542a;
static {
f1542a = new int[C0663a.values().length];
try {
f1542a[C0663a.ADS.ordinal()] = 1;
} catch (NoSuchFieldError e) {
}
try {
f1542a[C0663a.ERROR.ordinal()] = 2;
} catch (NoSuchFieldError e2) {
}
}
}
static {
f1543i = new C0676c();
f1544j = (ThreadPoolExecutor) Executors.newCachedThreadPool(f1543i);
}
public C0660b(Context context) {
this.f1546b = context.getApplicationContext();
this.f1547c = C0662d.m2122a();
this.f1548d = new C0649j(this.f1546b);
this.f1552h = C0661c.m2120a();
}
private void m2106a(C0536d c0536d) {
if (this.f1549e != null) {
this.f1549e.m1557a(c0536d);
}
m2117a();
}
private void m2109a(C0665f c0665f) {
if (this.f1549e != null) {
this.f1549e.m1558a(c0665f);
}
m2117a();
}
private void m2110a(String str) {
try {
C0664e a = this.f1547c.m2126a(str);
C0557d b = a.m2128b();
if (b != null) {
this.f1548d.m2066a(b.m1720b());
C0708r.m2281a(b.m1718a().m1725c(), this.f1550f);
}
switch (C06593.f1542a[a.m2127a().ordinal()]) {
case NendIconError.ERROR_ICONVIEW /*1*/:
C0665f c0665f = (C0665f) a;
if (b != null && b.m1718a().m1726d()) {
C0708r.m2282a(str, this.f1550f);
}
m2109a(c0665f);
return;
case FirebaseRemoteConfig.VALUE_SOURCE_REMOTE /*2*/:
C0666g c0666g = (C0666g) a;
String c = c0666g.m2129c();
C0455a a2 = C0455a.m1128a(c0666g.m2130d(), C0455a.ERROR_MESSAGE);
if (c != null) {
str = c;
}
m2106a(a2.m1130a(str));
return;
default:
m2106a(C0455a.UNKNOWN_RESPONSE.m1130a(str));
return;
}
} catch (Exception e) {
m2106a(C0455a.PARSER_FAILURE.m1130a(e.getMessage()));
}
m2106a(C0455a.PARSER_FAILURE.m1130a(e.getMessage()));
}
private C0600b m2111b() {
return new C06582(this);
}
public void m2117a() {
if (this.f1551g != null) {
this.f1551g.m1895c(1);
this.f1551g.m1893b(1);
this.f1551g = null;
}
}
public void m2118a(C0561f c0561f) {
m2117a();
if (ak.m2169c(this.f1546b) == C0672a.NONE) {
m2106a(new C0536d(C0455a.NETWORK_ERROR, "No network connection"));
return;
}
this.f1550f = c0561f;
C0675b.m2180a(this.f1546b);
if (C0708r.m2283a(c0561f)) {
String c = C0708r.m2285c(c0561f);
if (c != null) {
m2110a(c);
return;
} else {
m2106a(C0455a.LOAD_TOO_FREQUENTLY.m1130a(null));
return;
}
}
f1544j.submit(new C06571(this, c0561f));
}
public void m2119a(C0520a c0520a) {
this.f1549e = c0520a;
}
}
|
UTF-8
|
Java
| 7,626 |
java
|
C0660b.java
|
Java
|
[] | null |
[] |
package com.facebook.ads.internal.p027l;
import android.content.Context;
import com.facebook.ads.internal.C0455a;
import com.facebook.ads.internal.C0536d;
import com.facebook.ads.internal.C0649j;
import com.facebook.ads.internal.p021m.C0675b;
import com.facebook.ads.internal.p021m.C0676c;
import com.facebook.ads.internal.p021m.C0708r;
import com.facebook.ads.internal.p021m.ak;
import com.facebook.ads.internal.p021m.ak.C0672a;
import com.facebook.ads.internal.p027l.C0664e.C0663a;
import com.facebook.ads.internal.p031g.C0557d;
import com.facebook.ads.internal.p031g.C0561f;
import com.facebook.ads.internal.p031g.C0564i;
import com.facebook.ads.internal.p033j.p034a.C0599a;
import com.facebook.ads.internal.p033j.p034a.C0600b;
import com.facebook.ads.internal.p033j.p034a.C0611m;
import com.facebook.ads.internal.p033j.p034a.C0612n;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import net.nend.android.NendIconError;
import org.json.JSONException;
/* renamed from: com.facebook.ads.internal.l.b */
public class C0660b {
private static final C0676c f1543i;
private static final ThreadPoolExecutor f1544j;
Map<String, String> f1545a;
private final Context f1546b;
private final C0662d f1547c;
private final C0649j f1548d;
private C0520a f1549e;
private C0561f f1550f;
private C0599a f1551g;
private final String f1552h;
/* renamed from: com.facebook.ads.internal.l.b.a */
public interface C0520a {
void m1557a(C0536d c0536d);
void m1558a(C0665f c0665f);
}
/* renamed from: com.facebook.ads.internal.l.b.1 */
class C06571 implements Runnable {
final /* synthetic */ C0561f f1539a;
final /* synthetic */ C0660b f1540b;
C06571(C0660b c0660b, C0561f c0561f) {
this.f1540b = c0660b;
this.f1539a = c0561f;
}
public void run() {
C0564i.m1747b(this.f1540b.f1546b);
this.f1540b.f1545a = this.f1539a.m1742e();
try {
this.f1540b.f1551g = ak.m2168b(this.f1540b.f1546b, this.f1539a.f1286e);
this.f1540b.f1551g.m1885a(this.f1540b.f1552h, this.f1540b.f1551g.m1892b().m1928a(this.f1540b.f1545a), this.f1540b.m2111b());
} catch (Exception e) {
this.f1540b.m2106a(C0455a.AD_REQUEST_FAILED.m1130a(e.getMessage()));
}
}
}
/* renamed from: com.facebook.ads.internal.l.b.2 */
class C06582 extends C0600b {
final /* synthetic */ C0660b f1541a;
C06582(C0660b c0660b) {
this.f1541a = c0660b;
}
public void m2101a(C0611m c0611m) {
C0708r.m2284b(this.f1541a.f1550f);
this.f1541a.f1551g = null;
try {
C0612n a = c0611m.m1920a();
if (a != null) {
String e = a.m1925e();
C0664e a2 = this.f1541a.f1547c.m2126a(e);
if (a2.m2127a() == C0663a.ERROR) {
C0666g c0666g = (C0666g) a2;
String c = c0666g.m2129c();
this.f1541a.m2106a(C0455a.m1128a(c0666g.m2130d(), C0455a.ERROR_MESSAGE).m1130a(c == null ? e : c));
return;
}
}
} catch (JSONException e2) {
}
this.f1541a.m2106a(new C0536d(C0455a.NETWORK_ERROR, c0611m.getMessage()));
}
public void m2102a(C0612n c0612n) {
if (c0612n != null) {
String e = c0612n.m1925e();
C0708r.m2284b(this.f1541a.f1550f);
this.f1541a.f1551g = null;
this.f1541a.m2110a(e);
}
}
public void m2103a(Exception exception) {
if (C0611m.class.equals(exception.getClass())) {
m2101a((C0611m) exception);
} else {
this.f1541a.m2106a(new C0536d(C0455a.NETWORK_ERROR, exception.getMessage()));
}
}
}
/* renamed from: com.facebook.ads.internal.l.b.3 */
static /* synthetic */ class C06593 {
static final /* synthetic */ int[] f1542a;
static {
f1542a = new int[C0663a.values().length];
try {
f1542a[C0663a.ADS.ordinal()] = 1;
} catch (NoSuchFieldError e) {
}
try {
f1542a[C0663a.ERROR.ordinal()] = 2;
} catch (NoSuchFieldError e2) {
}
}
}
static {
f1543i = new C0676c();
f1544j = (ThreadPoolExecutor) Executors.newCachedThreadPool(f1543i);
}
public C0660b(Context context) {
this.f1546b = context.getApplicationContext();
this.f1547c = C0662d.m2122a();
this.f1548d = new C0649j(this.f1546b);
this.f1552h = C0661c.m2120a();
}
private void m2106a(C0536d c0536d) {
if (this.f1549e != null) {
this.f1549e.m1557a(c0536d);
}
m2117a();
}
private void m2109a(C0665f c0665f) {
if (this.f1549e != null) {
this.f1549e.m1558a(c0665f);
}
m2117a();
}
private void m2110a(String str) {
try {
C0664e a = this.f1547c.m2126a(str);
C0557d b = a.m2128b();
if (b != null) {
this.f1548d.m2066a(b.m1720b());
C0708r.m2281a(b.m1718a().m1725c(), this.f1550f);
}
switch (C06593.f1542a[a.m2127a().ordinal()]) {
case NendIconError.ERROR_ICONVIEW /*1*/:
C0665f c0665f = (C0665f) a;
if (b != null && b.m1718a().m1726d()) {
C0708r.m2282a(str, this.f1550f);
}
m2109a(c0665f);
return;
case FirebaseRemoteConfig.VALUE_SOURCE_REMOTE /*2*/:
C0666g c0666g = (C0666g) a;
String c = c0666g.m2129c();
C0455a a2 = C0455a.m1128a(c0666g.m2130d(), C0455a.ERROR_MESSAGE);
if (c != null) {
str = c;
}
m2106a(a2.m1130a(str));
return;
default:
m2106a(C0455a.UNKNOWN_RESPONSE.m1130a(str));
return;
}
} catch (Exception e) {
m2106a(C0455a.PARSER_FAILURE.m1130a(e.getMessage()));
}
m2106a(C0455a.PARSER_FAILURE.m1130a(e.getMessage()));
}
private C0600b m2111b() {
return new C06582(this);
}
public void m2117a() {
if (this.f1551g != null) {
this.f1551g.m1895c(1);
this.f1551g.m1893b(1);
this.f1551g = null;
}
}
public void m2118a(C0561f c0561f) {
m2117a();
if (ak.m2169c(this.f1546b) == C0672a.NONE) {
m2106a(new C0536d(C0455a.NETWORK_ERROR, "No network connection"));
return;
}
this.f1550f = c0561f;
C0675b.m2180a(this.f1546b);
if (C0708r.m2283a(c0561f)) {
String c = C0708r.m2285c(c0561f);
if (c != null) {
m2110a(c);
return;
} else {
m2106a(C0455a.LOAD_TOO_FREQUENTLY.m1130a(null));
return;
}
}
f1544j.submit(new C06571(this, c0561f));
}
public void m2119a(C0520a c0520a) {
this.f1549e = c0520a;
}
}
| 7,626 | 0.549567 | 0.38985 | 229 | 32.301311 | 22.446463 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541485 | false | false |
15
|
b890e4bb646fde54c777484db290f0d181a697ca
| 28,930,899,767,871 |
ab49c5b50ff85988b687ac8873792da03e05d758
|
/BOJ/1774_우주신과의 교감.java
|
9c4e68dd538951443ce3d3709b715dc9f3155a16
|
[] |
no_license
|
sys09270883/Algorithms
|
https://github.com/sys09270883/Algorithms
|
e105e3d6120e3b9d46d5aed810260cf2c93f6065
|
f9e4f8c2a716eebe8e71b7912785deecd34dcc7e
|
refs/heads/master
| 2020-06-21T17:08:04.293000 | 2020-06-21T04:33:38 | 2020-06-21T04:33:38 | 197,510,434 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
https://www.acmicpc.net/problem/1774
[문제]
황선자씨는 우주신과 교감을 할수 있는 채널러 이다.
하지만 우주신은 하나만 있는 것이 아니기때문에 황선자 씨는 매번 여럿의 우주신과 교감하느라 힘이 든다.
이러던 와중에 새로운 우주신들이 황선자씨를 이용하게 되었다.
하지만 위대한 우주신들은 바로 황선자씨와 연결될 필요가 없다.
이미 황선자씨와 혹은 이미 우주신끼리 교감할 수 있는 우주신들이 있기 때문에 새로운 우주신들은 그 우주신들을 거쳐서 황선자 씨와 교감을 할 수 있다.
우주신들과의 교감은 우주신들과 황선자씨 혹은 우주신들 끼리 이어진 정신적인 통로를 통해 이루어 진다.
하지만 우주신들과 교감하는 것은 힘든 일이기 때문에 황선자씨는 이런 통로들이 긴 것을 좋아하지 않는다. 왜냐하면 통로들이 길 수록 더 힘이 들기 때문이다.
또한 우리들은 3차원 좌표계로 나타낼 수 있는 세상에 살고 있지만 우주신들과 황선자씨는 2차원 좌표계로 나타낼 수 있는 세상에 살고 있다.
통로들의 길이는 2차원 좌표계상의 거리와 같다.
이미 황선자씨와 연결된, 혹은 우주신들과 연결된 통로들이 존재한다.
우리는 황선자 씨를 도와 아직 연결이 되지 않은 우주신들을 연결해 드려야 한다.
새로 만들어야 할 정신적인 통로의 길이들이 합이 최소가 되게 통로를 만들어 “빵상”을 외칠수 있게 도와주자.
[입력]
첫째 줄에 우주신들의 개수(N<=1,000) 이미 연결된 신들과의 통로의 개수(M<=1,000)가 주어진다.
두 번째 줄부터 N개의 줄에는 황선자를 포함하여 우주신들의 좌표가 (0<= X<=1,000,000), (0<=Y<=1,000,000)가 주어진다.
그 밑으로 M개의 줄에는 이미 연결된 통로가 주어진다. 번호는 위의 입력받은 좌표들의 순서라고 생각하면 된다. 좌표는 정수이다.
[출력]
첫째 줄에 만들어야 할 최소의 통로 길이를 출력하라. 출력은 소수점 둘째짜리까지 출력하여라.
[풀이]
1~N까지의 노드를 입력받고, 간선을 추가한다. 추가적으로 길이가 0이 되는 간선도 추가한다.
간선이 겹치긴 하지만, 오름차순으로 정렬 후 길이가 짧은 간선부터 뽑을 때 노드가 겹치더라도 작은 길이부터 추출하므로 상관없다.
간선을 합쳐주면서 합을 갱신한다.
*/
import java.io.*;
import java.util.*;
public class Main {
static int N, M;
static ArrayList<Node> node;
static ArrayList<Edge> edge;
static int[] parent;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
node = new ArrayList<Node>(N + 1);
edge = new ArrayList<Edge>(N * (N + 1) * 2);
parent = new int[N + 1];
for (int i = 1; i < N + 1; i++) {
parent[i] = i;
}
double res = 0d;
node.add(new Node(0, 0));
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
node.add(new Node(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())));
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
edge.add(new Edge(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), 0));
}
for (int i = 1; i <= N - 1; i++) {
for (int j = i + 1; j <= N; j++) {
edge.add(new Edge(i, j, distance(node.get(i), node.get(j))));
}
}
Collections.sort(edge);
for (Edge e : edge) {
if (find(e.n1) != find(e.n2)) {
union(e.n1, e.n2);
res += e.d;
}
}
bw.write(String.format("%.2f", res));
bw.close();
br.close();
}
private static double distance(Node n1, Node n2) {
return Math.sqrt(Math.pow(n1.x - n2.x, 2) + Math.pow(n1.y - n2.y, 2));
}
private static int find(int x) {
if (x == parent[x])
return x;
return parent[x] = find(parent[x]);
}
private static void union(int x, int y) {
x = find(x);
y = find(y);
parent[x] = y;
}
}
class Node {
int x, y;
public Node(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class Edge implements Comparable<Edge>{
int n1, n2;
double d;
public Edge(int n1, int n2, double d) {
super();
this.n1 = n1;
this.n2 = n2;
this.d = d;
}
@Override
public int compareTo(Edge e) {
// TODO Auto-generated method stub
return Double.compare(this.d, e.d);
}
}
|
UHC
|
Java
| 4,769 |
java
|
1774_우주신과의 교감.java
|
Java
|
[] | null |
[] |
/*
https://www.acmicpc.net/problem/1774
[문제]
황선자씨는 우주신과 교감을 할수 있는 채널러 이다.
하지만 우주신은 하나만 있는 것이 아니기때문에 황선자 씨는 매번 여럿의 우주신과 교감하느라 힘이 든다.
이러던 와중에 새로운 우주신들이 황선자씨를 이용하게 되었다.
하지만 위대한 우주신들은 바로 황선자씨와 연결될 필요가 없다.
이미 황선자씨와 혹은 이미 우주신끼리 교감할 수 있는 우주신들이 있기 때문에 새로운 우주신들은 그 우주신들을 거쳐서 황선자 씨와 교감을 할 수 있다.
우주신들과의 교감은 우주신들과 황선자씨 혹은 우주신들 끼리 이어진 정신적인 통로를 통해 이루어 진다.
하지만 우주신들과 교감하는 것은 힘든 일이기 때문에 황선자씨는 이런 통로들이 긴 것을 좋아하지 않는다. 왜냐하면 통로들이 길 수록 더 힘이 들기 때문이다.
또한 우리들은 3차원 좌표계로 나타낼 수 있는 세상에 살고 있지만 우주신들과 황선자씨는 2차원 좌표계로 나타낼 수 있는 세상에 살고 있다.
통로들의 길이는 2차원 좌표계상의 거리와 같다.
이미 황선자씨와 연결된, 혹은 우주신들과 연결된 통로들이 존재한다.
우리는 황선자 씨를 도와 아직 연결이 되지 않은 우주신들을 연결해 드려야 한다.
새로 만들어야 할 정신적인 통로의 길이들이 합이 최소가 되게 통로를 만들어 “빵상”을 외칠수 있게 도와주자.
[입력]
첫째 줄에 우주신들의 개수(N<=1,000) 이미 연결된 신들과의 통로의 개수(M<=1,000)가 주어진다.
두 번째 줄부터 N개의 줄에는 황선자를 포함하여 우주신들의 좌표가 (0<= X<=1,000,000), (0<=Y<=1,000,000)가 주어진다.
그 밑으로 M개의 줄에는 이미 연결된 통로가 주어진다. 번호는 위의 입력받은 좌표들의 순서라고 생각하면 된다. 좌표는 정수이다.
[출력]
첫째 줄에 만들어야 할 최소의 통로 길이를 출력하라. 출력은 소수점 둘째짜리까지 출력하여라.
[풀이]
1~N까지의 노드를 입력받고, 간선을 추가한다. 추가적으로 길이가 0이 되는 간선도 추가한다.
간선이 겹치긴 하지만, 오름차순으로 정렬 후 길이가 짧은 간선부터 뽑을 때 노드가 겹치더라도 작은 길이부터 추출하므로 상관없다.
간선을 합쳐주면서 합을 갱신한다.
*/
import java.io.*;
import java.util.*;
public class Main {
static int N, M;
static ArrayList<Node> node;
static ArrayList<Edge> edge;
static int[] parent;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
node = new ArrayList<Node>(N + 1);
edge = new ArrayList<Edge>(N * (N + 1) * 2);
parent = new int[N + 1];
for (int i = 1; i < N + 1; i++) {
parent[i] = i;
}
double res = 0d;
node.add(new Node(0, 0));
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
node.add(new Node(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())));
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
edge.add(new Edge(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), 0));
}
for (int i = 1; i <= N - 1; i++) {
for (int j = i + 1; j <= N; j++) {
edge.add(new Edge(i, j, distance(node.get(i), node.get(j))));
}
}
Collections.sort(edge);
for (Edge e : edge) {
if (find(e.n1) != find(e.n2)) {
union(e.n1, e.n2);
res += e.d;
}
}
bw.write(String.format("%.2f", res));
bw.close();
br.close();
}
private static double distance(Node n1, Node n2) {
return Math.sqrt(Math.pow(n1.x - n2.x, 2) + Math.pow(n1.y - n2.y, 2));
}
private static int find(int x) {
if (x == parent[x])
return x;
return parent[x] = find(parent[x]);
}
private static void union(int x, int y) {
x = find(x);
y = find(y);
parent[x] = y;
}
}
class Node {
int x, y;
public Node(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class Edge implements Comparable<Edge>{
int n1, n2;
double d;
public Edge(int n1, int n2, double d) {
super();
this.n1 = n1;
this.n2 = n2;
this.d = d;
}
@Override
public int compareTo(Edge e) {
// TODO Auto-generated method stub
return Double.compare(this.d, e.d);
}
}
| 4,769 | 0.627746 | 0.606982 | 142 | 22.408451 | 24.094051 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.809859 | false | false |
15
|
88e9ba907889e57ca37050c93b09d2c9ec1909f3
| 37,254,546,345,331 |
b613f13d6e8c18e0c572abbeab7ff4e27a361f11
|
/java-runtime/src/utils/AbstractPageServlet.java
|
ba92ca93c7442af316c776e72102cefde63b6a5b
|
[
"Apache-2.0"
] |
permissive
|
webdsl/webdsl
|
https://github.com/webdsl/webdsl
|
5cc4bc14590f8357d6effb58d2cd9a629b0d01f2
|
0499d53abfe18e6d219975627dd344e6fc0dcdee
|
refs/heads/master
| 2023-07-16T07:54:21.902000 | 2023-06-30T07:12:18 | 2023-06-30T07:12:18 | 37,918,550 | 45 | 10 |
Apache-2.0
| false | 2023-04-16T15:18:21 | 2015-06-23T12:46:44 | 2022-11-27T14:33:26 | 2023-04-16T15:18:20 | 1,003,273 | 39 | 7 | 27 |
Java
| false | false |
package utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.webdsl.WebDSLEntity;
import org.webdsl.lang.Environment;
import org.webdsl.logging.Logger;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public abstract class AbstractPageServlet{
protected abstract void renderDebugJsVar(PrintWriter sout);
protected abstract boolean logSqlCheckAccess();
protected abstract void initTemplateClass();
protected abstract boolean isActionSubmit();
protected abstract String[] getUsedSessionEntityJoins();
protected TemplateServlet templateservlet = null;
protected abstract org.webdsl.WebDSLEntity getRequestLogEntry();
protected abstract void addPrincipalToRequestLog(org.webdsl.WebDSLEntity rle);
protected abstract void addLogSqlToSessionMessages();
public Session hibernateSession = null;
protected static Pattern isMarkupLangMimeType= Pattern.compile("html|xml$");
protected static Pattern baseURLPattern= Pattern.compile("(^\\w{0,6})(://[^/]+)");
protected AbstractPageServlet commandingPage = this;
public boolean isReadOnly = false;
public boolean isWebService(){ return false; }
public String placeholderId = "1";
static{
ajax_js_include_name = "ajax.js";
}
public void serve(HttpServletRequest request, HttpServletResponse httpServletResponse, Map<String, String> parammap, Map<String, List<String>> parammapvalues, Map<String,List<utils.File>> fileUploads) throws Exception
{
initTemplateClass();
this.startTime = System.currentTimeMillis();
ThreadLocalPage.set(this);
this.request=request;
this.httpServletResponse = httpServletResponse;
this.response = new ResponseWrapper(httpServletResponse);
this.parammap = parammap;
this.parammapvalues = parammapvalues;
this.fileUploads=fileUploads;
String ajaxParam = parammap.get( "__ajax_runtime_request__" );
if( ajaxParam != null ){
this.setAjaxRuntimeRequest( true );
if( ajaxParam != "1" ){
placeholderId = ajaxParam;
}
}
org.webdsl.WebDSLEntity rle = getRequestLogEntry();
org.apache.logging.log4j.ThreadContext.put("request", rle.getId().toString());
org.apache.logging.log4j.ThreadContext.put("template", "/" + getPageName());
utils.RequestAppender reqAppender = null;
if(parammap.get("disableopt") != null){
this.isOptimizationEnabled = false;
}
if(parammap.get("logsql") != null){
this.isLogSqlEnabled = true;
this.isPageCacheDisabled = true;
reqAppender = utils.RequestAppender.getInstance();
}
if(reqAppender != null){
reqAppender.addRequest(rle.getId().toString());
}
if(parammap.get("nocache") != null){
this.isPageCacheDisabled = true;
}
initRequestVars();
hibernateSession = utils.HibernateUtil.getCurrentSession();
hibernateSession.beginTransaction();
if(isReadOnly){
hibernateSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
}
else{
hibernateSession.setFlushMode(org.hibernate.FlushMode.COMMIT);
}
try
{
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
ThreadLocalServlet.get().loadSessionManager(hibernateSession, getUsedSessionEntityJoins());
ThreadLocalServlet.get().retrieveIncomingMessagesFromHttpSession();
initVarsAndArgs();
enterPlaceholderIdContext();
if(isActionSubmit()) {
if(parammap.get("__action__link__") != null) {
this.setActionLinkUsed(true);
}
templateservlet.storeInputs(null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
//storeinputs also finds which action is executed, since validation might be ignored using [ignore-validation] on the submit
boolean ignoreValidation = actionToBeExecutedHasDisabledValidation;
if (!ignoreValidation){
templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
}
if(validated){
templateservlet.handleActions(null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
}
}
if(isNotValid()){
// mark transaction so it will be aborted at the end
// entered form data can be used to update the form on the client with ajax, taking into account if's and other control flow template elements
// this also means that data in vars/args and hibernate session should not be cleared until form is rendered
abortTransaction();
}
String outstream = s.toString();
if(download != null) { //File.download() excecuted in action
download();
}
else {
boolean isAjaxResponse = true;
// regular render, or failed action render
if( hasNotExecutedAction() || isNotValid() ){
// ajax replace performed during validation, assuming that handles all validation
// all inputajax templates use rollback() to prevent making actual changes -> check for isRollback()
if(isAjaxRuntimeRequest() && outstream.length() > 0 && isRollback()){
response.getWriter().write("[");
response.getWriter().write(outstream);
if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions
if(logSqlCheckAccess()){
response.getWriter().write("{\"action\":\"logsql\",\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}");
}
else{
response.getWriter().write("{\"action\":\"logsql\",\"value\":\"Access to SQL logs was denied.\"}");
}
response.getWriter().write(",");
}
response.getWriter().write("{}]");
}
// action called but no action found
else if( !isWebService() && isValid() && isActionSubmit() ){
org.webdsl.logging.Logger.error("Error: server received POST request but was unable to dispatch to a proper action (" + getRequestURL() + ")" );
httpServletResponse.setStatus( 404 );
response.getWriter().write("404 \n Error: server received POST request but was unable to dispatch to a proper action");
}
// action inside ajax template called and failed
else if( isAjaxTemplateRequest() && isActionSubmit() ){
StringWriter s1 = renderPageOrTemplateContents();
response.getWriter().write("[{\"action\":\"replace\",\"id\":{\"type\":\"enclosing-placeholder\"},\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(s1.toString()) + "\"}]");
}
//actionLink or ajax action used (request came through js runtime), and action failed
else if( isActionLinkUsed() || isAjaxRuntimeRequest() ){
validationFormRerender = true;
renderPageOrTemplateContents();
if(submittedFormId != null){
response.getWriter().write("[{\"action\":\"replace\",\"id\":\"" + submittedFormId + "\",\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]");
}
else{
response.getWriter().write("[{\"action\":\"replace\",\"id\":{submitid:'" + submittedSubmitId + "'},\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]");
}
}
// 1 regular render without any action being executed
// 2 regular action submit, and action failed
// 3 redirect in page init
// 4 download in page init
else{
isAjaxResponse = false;
renderOrInitAction();
}
}
// successful action, always redirect, no render
else {
// actionLink or ajax action used and replace(placeholder) invoked
if( isReRenderPlaceholders() ){
StringBuilder commands = new StringBuilder("[");
templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
renderDynamicFormWithOnlyDirtyData = true;
shouldReInitializeTemplates = true;
renderPageOrTemplateContents(); // content of placeholders is collected in reRenderPlaceholdersContent map
//For now we do not support dynamically loading of resources in case of a rerendered placeholder,
//because this would try to load the js/css resources from the whole page while only a part gets rerendered
// if(this.javascripts.size() > 0) {
// commands.append( requireJSCommand() ).append(",");
// }
// if(this.stylesheets.size() > 0) {
// commands.append( requireCSSCommand() ).append(",");
// }
boolean addComma = false;
for(String ph : reRenderPlaceholders){
if(addComma){ commands.append(","); }
else { addComma = true; }
commands.append("{\"action\":\"replace\",\"id\":\"")
.append(ph)
.append("\",\"value\":\"")
.append(org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(reRenderPlaceholdersContent.get(ph)))
.append("\"}");
}
if( outstream.length() > 0 ){
commands.append( "," + outstream.substring(0, outstream.length() - 1) ); // Other ajax updates, such as clear(ph). Done after ph rerendering to allow customization.
}
commands.append("]");
response.getWriter().write( commands.toString() );
}
//hasExecutedAction() && isValid()
else if( isAjaxRuntimeRequest() ){
PrintWriter responseWriter = response.getWriter();
responseWriter.write("[");
if(this.javascripts.size() > 0) {
responseWriter.write( requireJSCommand() );
responseWriter.write(",");
}
if(this.stylesheets.size() > 0) {
responseWriter.write( requireCSSCommand() );
responseWriter.write(",");
}
responseWriter.write(outstream);
if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions
if(logSqlCheckAccess()){
responseWriter.write("{\"action\":\"logsql\",\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}");
}
else{
responseWriter.write("{\"action\":\"logsql\",\"value\":\"Access to SQL logs was denied.\"}");
}
responseWriter.write(",");
}
if( this.validateFailedBeforeRollback ){
responseWriter.write("{\"action\":\"skip_next_action\"}]");
}
else {
responseWriter.write("{}]");
}
}
else if( isActionLinkUsed() ){
//action link also uses ajax when ajax is not enabled
//, send only redirect location, so the client can simply set
// window.location = req.responseText;
response.getWriter().write("[{\"action\":\"relocate\",\"value\":\""+this.getRedirectUrl() + "\"}]");
} else {
isAjaxResponse = false;
}
if(!isAjaxRuntimeRequest()) {
addLogSqlToSessionMessages();
}
//else: action successful + no validation error + regular submit
// -> always results in a redirect, no further action necessary here
}
if(isAjaxResponse){
response.setContentType("application/json");
}
}
updatePageRequestStatistics();
hibernateSession = utils.HibernateUtil.getCurrentSession();
if( isTransactionAborted() || isRollback() ){
try{
hibernateSession.getTransaction().rollback();
response.sendContent();
}
catch (org.hibernate.SessionException e){
if(!e.getMessage().equals("Session is closed!")){ // closed session is not an issue when rolling back
throw e;
}
}
}
else {
ThreadLocalServlet.get().storeOutgoingMessagesInHttpSession( !isRedirected() || isPostRequest() );
addPrincipalToRequestLog(rle);
if(!this.isAjaxRuntimeRequest()){
ThreadLocalServlet.get().setEndTimeAndStoreRequestLog(utils.HibernateUtil.getCurrentSession());
}
ThreadLocalServlet.get().setCookie(hibernateSession);
if(isReadOnly || !hasWrites){ // either page has read-only modifier, or no writes have been detected
hibernateSession.getTransaction().rollback();
}
else{
hibernateSession.flush();
validateEntities();
hibernateSession.getTransaction().commit();
invalidatePageCacheIfNeeded();
}
if(exceptionInHibernateInterceptor != null){
throw exceptionInHibernateInterceptor;
}
response.sendContent();
}
ThreadLocalOut.popChecked(out);
}
catch(utils.MultipleValidationExceptions mve){
String url = getRequestURL();
org.webdsl.logging.Logger.error("Validation exceptions occurred while handling request URL [ " + url + " ]. Transaction is rolled back.");
for(utils.ValidationException vex : mve.getValidationExceptions()){
org.webdsl.logging.Logger.error( "Validation error: " + vex.getErrorMessage() , vex );
}
hibernateSession.getTransaction().rollback();
setValidated(false);
throw mve;
}
catch(utils.EntityNotFoundException enfe) {
org.webdsl.logging.Logger.error( enfe.getMessage() + ". Transaction is rolled back." );
if(hibernateSession.isOpen()){
hibernateSession.getTransaction().rollback();
}
throw enfe;
}
catch (Exception e) {
String url = getRequestURL();
org.webdsl.logging.Logger.error("exception occurred while handling request URL [ " + url + " ]. Transaction is rolled back.");
org.webdsl.logging.Logger.error("exception message: "+e.getMessage(), e);
if(hibernateSession.isOpen()){
hibernateSession.getTransaction().rollback();
}
throw e;
}
finally{
cleanupThreadLocals();
org.apache.logging.log4j.ThreadContext.remove("request");
org.apache.logging.log4j.ThreadContext.remove("template");
if(reqAppender != null) reqAppender.removeRequest(rle.getId().toString());
}
}
// LoadingCache is thread-safe
public static boolean pageCacheEnabled = utils.BuildProperties.getNumCachedPages() > 0;
public static Cache<String, CacheResult> cacheAnonymousPages =
CacheBuilder.newBuilder()
.maximumSize(utils.BuildProperties.getNumCachedPages()).build();
public boolean invalidateAllPageCache = false;
protected boolean shouldTryCleanPageCaches = false;
public String invalidateAllPageCacheMessage;
public void invalidateAllPageCache(String entityname){
commandingPage.invalidateAllPageCacheInternal(entityname);
}
private void invalidateAllPageCacheInternal(String entityname){
invalidateAllPageCache = true;
invalidateAllPageCacheMessage = entityname;
}
public void shouldTryCleanPageCaches(){
commandingPage.shouldTryCleanPageCachesInternal();
}
private void shouldTryCleanPageCachesInternal(){
shouldTryCleanPageCaches = true;
}
public static void doInvalidateAllPageCache( String triggerReason ) {
Logger.info( "All page caches invalidated, triggered by: " + triggerReason );
cacheAnonymousPages.invalidateAll();
cacheUserSpecificPages.invalidateAll();
}
public static void doInvalidateUserSpecificPageCache( String triggerReason ) {
Logger.info( "User-specific page caches invalidated, triggered by: " + triggerReason );
cacheUserSpecificPages.invalidateAll();
}
public static Cache<String, CacheResult> cacheUserSpecificPages =
CacheBuilder.newBuilder()
.maximumSize(utils.BuildProperties.getNumCachedPages()).build();
public boolean invalidateUserSpecificPageCache = false;
public String invalidateUserSpecificPageCacheMessage;
public void invalidateUserSpecificPageCache(String entityname){
commandingPage.invalidateUserSpecificPageCacheInternal(entityname);
}
private void invalidateUserSpecificPageCacheInternal(String entityname){
invalidateUserSpecificPageCache = true;
String propertySetterTrace = Warning.getStackTraceLineAtIndex(4);
invalidateUserSpecificPageCacheMessage = entityname + " - " + propertySetterTrace;
}
public boolean pageCacheWasUsed = false;
public void invalidatePageCacheIfNeeded(){
if(pageCacheEnabled && shouldTryCleanPageCaches){
if(invalidateAllPageCache){
doInvalidateAllPageCache("change in: "+invalidateAllPageCacheMessage);
}
else if(invalidateUserSpecificPageCache){
doInvalidateUserSpecificPageCache("change in: "+invalidateUserSpecificPageCacheMessage);
}
}
}
public void renderOrInitAction() throws IOException{
String key = getRequestURL();
String s = "";
Cache<String, CacheResult> cache = null;
AbstractDispatchServletHelper servlet = ThreadLocalServlet.get();
if( // not using page cache if:
this.isPageCacheDisabled // ?nocache added to URL
|| this.isPostRequest() // post parameters are not included in cache key
|| isNotValid() // data validation errors need to be rendered
|| !servlet.getIncomingSuccessMessages().isEmpty() // success messages need to be rendered
){
StringWriter renderedContent = renderPageOrTemplateContents();
if(!mimetypeChanged){
s = renderResponse(renderedContent);
}
else{
s = renderedContent.toString();
}
}
else{ // using page cache
if( // use user-specific page cache if:
servlet.sessionHasChanges() // not necessarily login, any session data changes can be included in a rendered page
|| webdsl.generated.functions.loggedIn_.loggedIn_() // user might have old session from before application start, this check is needed to avoid those logged in pages ending up in the anonymous page cache
){
key = key + servlet.getSessionManager().getId();
cache = cacheUserSpecificPages;
}
else{
cache = cacheAnonymousPages;
}
try{
pageCacheWasUsed = true;
CacheResult result = cache.get(key,
new Callable<CacheResult>(){
public CacheResult call(){
// System.out.println("key not found");
pageCacheWasUsed = false;
StringWriter renderedContent = renderPageOrTemplateContents();
CacheResult result = new CacheResult();
if(!mimetypeChanged){
result.body = renderResponse(renderedContent);
}
else{
result.body = renderedContent.toString();
}
result.mimetype = getMimetype();
return result;
}
});
s = result.body;
setMimetype(result.mimetype);
}
catch(java.util.concurrent.ExecutionException e){
e.printStackTrace();
}
}
// redirect in init action can be triggered with GET request, the render call in the line above will execute such inits
if( !isPostRequest() && isRedirected() ){
redirect();
if(cache != null){ cache.invalidate(key); }
}
else if( download != null ){ //File.download() executed in page/template init block
download();
if(cache != null){ cache.invalidate(key); } // don't cache binary file response in this page response cache, can be cached on client with expires header
}
else{
response.setContentType(getMimetype());
PrintWriter sout = response.getWriter(); //reponse.getWriter() must be called after file download checks
sout.write(s);
}
}
public boolean renderDynamicFormWithOnlyDirtyData = false;
public StringWriter renderPageOrTemplateContents(){
if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); }
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
if(getParammap().get("dynamicform") == null){
// regular pages and forms
if(isNotValid()){
clearHibernateCache();
}
ThreadLocalOut.push(out);
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
}
else{
shouldReInitializeTemplates = false;
// dynamicform uses submitted variable data to process form content
// render form with newly entered data, rest with the current persisted data
if(isNotValid() && !renderDynamicFormWithOnlyDirtyData){
StringWriter theform = new StringWriter();
PrintWriter pwform = new PrintWriter(theform);
ThreadLocalOut.push(pwform);
// render, when encountering submitted form save in abstractpage
validationFormRerender = true;
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(pwform);
clearHibernateCache();
}
ThreadLocalOut.push(out);
// render, when isNotValid and encountering submitted form render old
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
}
return s;
}
public StringWriter renderPageOrTemplateContentsSingle(){
if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); }
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
return s;
}
private boolean validationFormRerender = false;
public boolean isValidationFormRerender(){
return validationFormRerender;
}
public String submittedFormContent = null;
public String submittedFormId = null;
public String submittedSubmitId = null;
// helper methods that enable a submit without enclosing form to be ajax-refreshed when validation error occurs
protected StringWriter submitWrapSW;
protected PrintWriter submitWrapOut;
public void submitWrapOpenHelper(String submitId){
if( ! inSubmittedForm && validationFormRerender && request != null && getParammap().get(submitId) != null ){
submittedSubmitId = submitId;
submitWrapSW = new java.io.StringWriter();
submitWrapOut = new java.io.PrintWriter(submitWrapSW);
ThreadLocalOut.push(submitWrapOut);
ThreadLocalOut.peek().print("<span submitid=" + submitId + ">");
}
}
public void submitWrapCloseHelper(){
if( ! inSubmittedForm && validationFormRerender && submitWrapSW != null ){
ThreadLocalOut.peek().print("</span>");
ThreadLocalOut.pop();
submittedFormContent = submitWrapSW.toString();
submitWrapSW = null;
}
}
private static String ajax_js_include_name;
public String renderResponse(StringWriter s) {
StringWriter sw = new StringWriter();
PrintWriter sout = new PrintWriter(sw);
ThreadLocalOut.push(sout);
addJavascriptInclude( utils.IncludePaths.jQueryJS() );
addJavascriptInclude( ajax_js_include_name );
sout.println("<!DOCTYPE html>");
sout.println("<html>");
sout.println("<head>");
if( !customHeadNoDuplicates.containsKey( "viewport" ) ) {
sout.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
}
if( !customHeadNoDuplicates.containsKey( "contenttype" ) ) {
sout.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
}
if( !customHeadNoDuplicates.containsKey( "favicon" ) ) {
sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+ CachedResourceFileNameHelper.fav_ico_link_tag_suffix);
}
if( !customHeadNoDuplicates.containsKey( "defaultcss" ) ) {
sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+ CachedResourceFileNameHelper.common_css_link_tag_suffix);
}
sout.println("<title>"+getPageTitle().replaceAll("<[^>]*>","")+"</title>");
renderDebugJsVar(sout);
sout.println("<script type=\"text/javascript\">var contextpath=\""+ThreadLocalPage.get().getAbsoluteLocation()+"\";</script>");
for(String sheet : this.stylesheets) {
String href = computeResourceSrc("stylesheets", sheet);
sout.print("<link rel=\"stylesheet\" href=\""+ href + "\" type=\"text/css\" />");
}
for(String script : this.javascripts) {
String src = computeResourceSrc("javascript", script);
sout.println("<script type=\"text/javascript\" src=\"" + src + "\"></script>");
}
for(Map.Entry<String,String> headEntry : customHeadNoDuplicates.entrySet()) {
// sout.println("<!-- " + headEntry.getKey() + " -->");
sout.println(headEntry.getValue());
}
sout.println("</head>");
sout.print("<body id=\""+this.getPageName()+"\"");
for(String attribute : this.bodyAttributes) {
sout.print(attribute);
}
sout.print(">");
renderLogSqlMessage();
renderIncomingSuccessMessages();
s.flush();
sout.write(s.toString());
if(this.isLogSqlEnabled()){
if(logSqlCheckAccess()){
sout.print("<hr/><div class=\"logsql\">");
sout.print("<script type=\"text/javascript\">$('a.navigate').on('click', function(event) { event.target.href += '?logsql' })</script>");
utils.HibernateLog.printHibernateLog(sout, this, null);
sout.print("</div>");
}
else{
sout.print("<hr/><div class=\"logsql\">Access to SQL logs was denied.</div>");
}
}
for(String script : this.tailJavascripts) {
String src = computeResourceSrc("javascript", script);
sout.println("<script type=\"text/javascript\" src=\"" + src + "\"></script>");
}
sout.print("</body>");
sout.println("</html>");
ThreadLocalOut.popChecked(sout);
return sw.toString();
}
private String computeResourceSrc(String resourceDirName, String url) {
if(url.startsWith("//") || url.startsWith("http://") || url.startsWith("https://")) {
return url;
} else {
String hashedName = CachedResourceFileNameHelper.getNameWithHash(resourceDirName, url);
return ThreadLocalPage.get().getAbsoluteLocation()+"/"+resourceDirName+"/"+hashedName;
}
}
private String requireJSCommand() {
StringBuilder aStr = new StringBuilder("{ \"action\":\"require_js\", \"value\": [");
boolean addComma = false;
for(String script : this.javascripts) {
if(addComma) {
aStr.append(",");
} else{
addComma = true;
}
String src = computeResourceSrc("javascript", script);
aStr.append( "\"" ).append( org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(src) ).append("\"");
}
aStr.append("] }");
return aStr.toString();
}
private String requireCSSCommand() {
StringBuilder aStr = new StringBuilder("{ \"action\":\"require_css\", \"value\": [");
boolean addComma = false;
for(String sheet : this.stylesheets) {
if(addComma) {
aStr.append(",");
} else{
addComma = true;
}
String href = computeResourceSrc("stylesheets", sheet);
aStr.append( "\"" ).append( org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(href) ).append("\"");
}
aStr.append("] }");
return aStr.toString();
}
//ajax/js runtime request related
protected abstract void initializeBasics(AbstractPageServlet ps, Object[] args);
public boolean isServingAsAjaxResponse = false;
public void serveAsAjaxResponse(Object[] args, TemplateCall templateArg, String placeholderId)
{
AbstractPageServlet ps = ThreadLocalPage.get();
TemplateServlet ts = ThreadLocalTemplate.get();
//inherit commandingPage
commandingPage = ps.commandingPage;
//use passed PageServlet ps here, since this is the context for this type of response
initializeBasics(ps, args);
ThreadLocalPage.set(this);
//outputstream threadlocal is already set, see to-java-servlet/ajax/ajax.str
this.isServingAsAjaxResponse = true;
this.placeholderId = placeholderId;
enterPlaceholderIdContext();
templateservlet.render(null, args, Environment.createNewLocalEnvironment(envGlobalAndSession), null); // new clean environment with only the global templates, and global/session vars
ThreadLocalTemplate.set(ts);
ThreadLocalPage.set(ps);
}
protected boolean isTemplate() { return false; }
public static AbstractPageServlet getRequestedPage(){
return ThreadLocalPage.get();
}
private boolean passedThroughAjaxTemplate = false;
public boolean passedThroughAjaxTemplate(){
return passedThroughAjaxTemplate;
}
public void setPassedThroughAjaxTemplate(boolean b){
passedThroughAjaxTemplate = b;
}
protected boolean isLogSqlEnabled = false;
public boolean isLogSqlEnabled() { return isLogSqlEnabled; }
public boolean isPageCacheDisabled = false;
protected boolean isOptimizationEnabled = true;
public boolean isOptimizationEnabled() { return isOptimizationEnabled; }
public String getExtraQueryArguments(String firstChar) { // firstChar is expected to be ? or &, depending on whether there are more query arguments
HttpServletRequest req = getRequest();
return (req != null && req.getQueryString() != null) ? (firstChar + req.getQueryString()) : "";
}
public abstract String getPageName();
public abstract String getUniqueName();
protected MessageDigest messageDigest = null;
public MessageDigest getMessageDigest(){
if(messageDigest == null){
try{
messageDigest = MessageDigest.getInstance("MD5");
}
catch(NoSuchAlgorithmException ae)
{
org.webdsl.logging.Logger.error("MD5 not available: "+ae.getMessage());
return null;
}
}
return messageDigest;
}
public boolean actionToBeExecutedHasDisabledValidation = false;
public boolean actionHasAjaxPageUpdates = false;
//TODO merge getActionTarget and getPageUrlWithParams
public String getActionTarget() {
if (isServingAsAjaxResponse){
return this.getUniqueName();
}
return getPageName();
}
//TODO merge getActionTarget and getPageUrlWithParams
public String getPageUrlWithParams(){ //used for action field in forms
if(isServingAsAjaxResponse){
return ThreadLocalPage.get().getAbsoluteLocation()+"/"+ThreadLocalPage.get().getActionTarget();
}
else{
//this doesn't work with ajax template render from action, since an ajax template needs to submit to a different page than the original request
return getRequestURL();
}
}
protected abstract void renderIncomingSuccessMessages();
protected abstract void renderLogSqlMessage();
public boolean isPostRequest(){
return ThreadLocalServlet.get().isPostRequest;
}
public boolean isNotPostRequest(){
return !ThreadLocalServlet.get().isPostRequest;
}
public boolean isAjaxTemplateRequest(){
return ThreadLocalServlet.get().getPages().get(ThreadLocalServlet.get().getRequestedPage()).isAjaxTemplate();
}
public abstract String getHiddenParams();
public abstract String getUrlQueryParams();
public abstract String getHiddenPostParamsJson();
//public javax.servlet.http.HttpSession session;
public static void cleanupThreadLocals(){
ThreadLocalEmailContext.set(null);
ThreadLocalPage.set(null);
ThreadLocalTemplate.setNull();
}
//templates scope
public static Environment staticEnv = Environment.createSharedEnvironment();
public Environment envGlobalAndSession = Environment.createLocalEnvironment();
//emails
protected static Map<String, Class<?>> emails = new HashMap<String, Class<?>>();
public static Map<String, Class<?>> getEmails() {
return emails;
}
public boolean sendEmail(String name, Object[] emailargs, Environment emailenv){
EmailServlet temp = renderEmail(name,emailargs,emailenv);
return temp.send();
}
public EmailServlet renderEmail(String name, Object[] emailargs, Environment emailenv){
EmailServlet temp = null;
try
{
temp = ((EmailServlet)getEmails().get(name).newInstance());
}
catch(IllegalAccessException iae)
{
org.webdsl.logging.Logger.error("Problem in email template lookup: " + iae.getMessage());
}
catch(InstantiationException ie)
{
org.webdsl.logging.Logger.error("Problem in email template lookup: " + ie.getMessage());
}
temp.render(emailargs, emailenv);
return temp;
}
//rendertemplate function
public String renderTemplate(String name, Object[] args, Environment env){
return executeTemplatePhase(RENDER_PHASE, name, args, env);
}
//validatetemplate function
public String validateTemplate(String name, Object[] args, Environment env){
return executeTemplatePhase(VALIDATE_PHASE, name, args, env);
}
public static final int DATABIND_PHASE = 1;
public static final int VALIDATE_PHASE = 2;
public static final int ACTION_PHASE = 3;
public static final int RENDER_PHASE = 4;
public String executeTemplatePhase(int phase, String name, Object[] args, Environment env){
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
TemplateServlet enclosingTemplateObject = ThreadLocalTemplate.get();
try{
TemplateServlet temp = ((TemplateServlet)env.getTemplate(name).newInstance());
switch(phase){
case VALIDATE_PHASE: temp.validateInputs(name, args, env, null); break;
case RENDER_PHASE: temp.render(name, args, env, null); break;
}
}
catch(Exception oe){
try {
TemplateCall tcall = env.getWithcall(name); //'elements' or requires arg
TemplateServlet temp = ((TemplateServlet)env.getTemplate(tcall.name).newInstance());
String parent = env.getWithcall(name)==null?null:env.getWithcall(name).parentName;
switch(phase){
case VALIDATE_PHASE: temp.validateInputs(parent, tcall.args, env, null); break;
case RENDER_PHASE: temp.render(parent, tcall.args, env, null); break;
}
}
catch(Exception ie){
org.webdsl.logging.Logger.error("EXCEPTION",oe);
org.webdsl.logging.Logger.error("EXCEPTION",ie);
}
}
ThreadLocalTemplate.set(enclosingTemplateObject);
ThreadLocalOut.popChecked(out);
return s.toString();
}
//ref arg
protected static Map<String, Class<?>> refargclasses = new HashMap<String, Class<?>>();
public static Map<String, Class<?>> getRefArgClasses() {
return refargclasses;
}
public abstract String getAbsoluteLocation();
public String getXForwardedProto() {
if (request == null) {
return null;
} else {
return request.getHeader("x-forwarded-proto");
}
}
protected TemplateContext templateContext = new TemplateContext();
public String getTemplateContextString() {
return templateContext.getTemplateContextString();
}
public void enterPlaceholderIdContext() {
if( ! "1".equals( placeholderId ) ){
templateContext.enterTemplateContext( placeholderId );
}
}
public void enterTemplateContext(String s) {
templateContext.enterTemplateContext(s);
}
public void leaveTemplateContext() {
templateContext.leaveTemplateContext();
}
public void leaveTemplateContextChecked(String s) {
templateContext.leaveTemplateContextChecked(s);
}
public void clearTemplateContext(){
templateContext.clearTemplateContext();
enterPlaceholderIdContext();
}
public void setTemplateContext(TemplateContext tc){
templateContext = tc;
}
public TemplateContext getTemplateContext(){
return templateContext;
}
// objects scheduled to be checked after action completes, filled by hibernate event listener in hibernate util class
ArrayList<WebDSLEntity> entitiesToBeValidated = new ArrayList<WebDSLEntity>();
boolean allowAddingEntitiesForValidation = true;
public void clearEntitiesToBeValidated(){
entitiesToBeValidated = new ArrayList<WebDSLEntity>();
allowAddingEntitiesForValidation = true;
}
public void addEntityToBeValidated(WebDSLEntity w){
if(allowAddingEntitiesForValidation){
entitiesToBeValidated.add(w);
}
}
public void validateEntities(){
allowAddingEntitiesForValidation = false; //adding entities must be disabled when checking is performed, new entities may be loaded for checks, but do not have to be checked themselves
java.util.Set<WebDSLEntity> set = new java.util.HashSet<WebDSLEntity>(entitiesToBeValidated);
java.util.List<utils.ValidationException> exceptions = new java.util.LinkedList<utils.ValidationException>();
for(WebDSLEntity w : set){
if(w.isChanged()){
try {
// System.out.println("validating: "+ w.get_WebDslEntityType() + ":" + w.getName());
w.validateSave();
//System.out.println("done validating");
} catch(utils.ValidationException ve){
exceptions.add(ve);
} catch(utils.MultipleValidationExceptions ve) {
for(utils.ValidationException vex : ve.getValidationExceptions()){
exceptions.add(vex);
}
}
}
}
if(exceptions.size() > 0){
throw new utils.MultipleValidationExceptions(exceptions);
}
clearEntitiesToBeValidated();
}
protected List<utils.ValidationException> validationExceptions = new java.util.LinkedList<utils.ValidationException>();
public List<utils.ValidationException> getValidationExceptions() {
return validationExceptions;
}
public void addValidationException(String name, String message){
validationExceptions.add(new ValidationException(name,message));
}
public List<utils.ValidationException> getValidationExceptionsByName(String name) {
List<utils.ValidationException> list = new java.util.LinkedList<utils.ValidationException>();
for(utils.ValidationException v : validationExceptions){
if(v.getName().equals(name)){
list.add(v);
}
}
return list;
}
public List<String> getValidationErrorsByName(String name) {
List<String> list = new java.util.ArrayList<String>();
for(utils.ValidationException v : validationExceptions){
if(v.getName().equals(name)){
list.add(v.getErrorMessage());
}
}
return list;
}
public boolean hasExecutedAction = false;
public boolean hasExecutedAction(){ return hasExecutedAction; }
public boolean hasNotExecutedAction(){ return !hasExecutedAction; }
protected boolean abortTransaction = false;
public boolean isTransactionAborted(){ return abortTransaction; }
public void abortTransaction(){ abortTransaction = true; }
public java.util.List<String> ignoreset= new java.util.ArrayList<String>();
public boolean hibernateCacheCleared = false;
public boolean shouldReInitializeTemplates = false;
protected java.util.List<String> javascripts = new java.util.ArrayList<String>();
protected java.util.List<String> tailJavascripts = new java.util.ArrayList<String>();
protected java.util.List<String> stylesheets = new java.util.ArrayList<String>();
protected java.util.List<String> bodyAttributes = new java.util.ArrayList<String>();
protected java.util.Map<String,String> customHeadNoDuplicates = new java.util.HashMap<String,String>();
public void addJavascriptInclude(String filename) { commandingPage.addJavascriptIncludeInternal( filename ); }
public void addJavascriptIncludeInternal(String filename) {
if(!javascripts.contains(filename))
javascripts.add(filename);
}
public void addJavascriptTailInclude(String filename) { commandingPage.addJavascriptTailIncludeInternal( filename ); }
public void addJavascriptTailIncludeInternal(String filename) {
if(!tailJavascripts.contains(filename))
tailJavascripts.add(filename);
}
public void addStylesheetInclude(String filename) { commandingPage.addStylesheetIncludeInternal( filename ); }
public void addStylesheetIncludeInternal(String filename) {
if(!stylesheets.contains(filename)){
stylesheets.add(filename);
}
}
public void addStylesheetInclude(String filename, String media) { commandingPage.addStylesheetIncludeInternal( filename, media ); }
public void addStylesheetIncludeInternal(String filename, String media) {
String combined = media != null && !media.isEmpty() ? filename + "\" media=\""+ media : filename;
if(!stylesheets.contains(combined)){
stylesheets.add(combined);
}
}
public void addCustomHead(String header) { commandingPage.addCustomHeadInternal(header, header); }
public void addCustomHead(String key, String header) { commandingPage.addCustomHeadInternal(key, header); }
public void addCustomHeadInternal(String key, String header) {
customHeadNoDuplicates.put(key, header);
}
public void addBodyAttribute(String key, String value) { commandingPage.addBodyAttributeInternal(key, value); }
public void addBodyAttributeInternal(String key, String value) {
bodyAttributes.add(" "+key+"=\""+value+"\"");
}
protected abstract void initialize();
protected abstract void conversion();
protected abstract void loadArguments();
public abstract void initVarsAndArgs();
public void clearHibernateCache() {
// used to be only ' hibSession.clear(); ' but that doesn't revert already flushed changes.
// since flushing now happens automatically when querying, this could produce wrong results.
// e.g. output in page with validation errors shows changes that were not persisted to the db.
// see regression test in test/succeed-web/validate-false-and-flush.app
utils.HibernateUtil.getCurrentSession().getTransaction().rollback();
/* http://community.jboss.org/wiki/sessionsandtransactions
* Because Hibernate can't bind the "current session" to a transaction, as it does in a JTA environment,
* it binds it to the current Java thread. It is opened when getCurrentSession() is called for the first
* time, but in a "proxied" state that doesn't allow you to do anything except start a transaction. When
* the transaction ends, either through commit or roll back, the "current" Session is closed automatically.
* The next call to getCurrentSession() starts a new proxied Session, and so on. In other words,
* the session is bound to the thread behind the scenes, but scoped to a transaction, just like in a JTA environment.
*/
openNewTransactionThroughGetCurrentSession();
ThreadLocalServlet.get().reloadSessionManager(hibernateSession);
initVarsAndArgs();
hibernateCacheCleared = true;
}
protected org.hibernate.Session openNewTransactionThroughGetCurrentSession(){
hibernateSession = utils.HibernateUtil.getCurrentSession();
hibernateSession.beginTransaction();
return hibernateSession;
}
protected HttpServletRequest request;
protected ResponseWrapper response;
protected HttpServletResponse httpServletResponse;
protected Object[] args;
// public void setHibSession(Session s) {
// hibSession = s;
// }
//
// public Session getHibSession() {
// return hibSession;
// }
public HttpServletRequest getRequest() {
return request;
}
private String requestURLCached = null;
private String requestURICached = null;
public String getRequestURL(){
if(requestURLCached == null) {
requestURLCached = AbstractDispatchServletHelper.get().getRequestURL();
}
return requestURLCached;
}
public String getRequestURI(){
if(requestURICached == null) {
requestURICached = AbstractDispatchServletHelper.get().getRequestURI();
}
return requestURICached;
}
public ResponseWrapper getResponse() {
return response;
}
public void addResponseHeader(String key, String value) {
if( response != null ) {
response.setHeader(key, value);
}
}
protected boolean validated=true;
/*
* when this is true, it can mean:
* 1 no validation has been performed yet
* 2 some validation has been performed without errors
* 3 all validation has been performed without errors
*/
public boolean isValid() {
return validated;
}
public boolean isNotValid() {
return !validated;
}
public void setValidated(boolean validated) {
this.validated = validated;
}
/*
* complete action regularly but rollback hibernate session
* skips validation of entities at end of action, if validation messages are necessary
* use cancel() instead of rollback()
* can be used to replace templates with ajax without saving, e.g. for validation
*/
protected boolean rollback = false;
protected boolean validateFailedBeforeRollback = false;
public boolean isRollback() {
return rollback;
}
public void setRollback() {
validateFailedBeforeRollback = this.isNotValid();
//by setting validated true, the action will succeed
this.setValidated(true);
//the session will be rolled back, to cancel persisting any changes
this.rollback = true;
}
public List<String> failedCaptchaResponses = new ArrayList<String>();
protected boolean inSubmittedForm = false;
public boolean inSubmittedForm() {
return inSubmittedForm;
}
public void setInSubmittedForm(boolean b) {
this.inSubmittedForm = b;
}
// used for runtime check to detect nested forms
protected String inForm = null;
public boolean isInForm() {
return inForm != null;
}
public void enterForm(String t) {
inForm = t;
}
public String getEnclosingForm() {
return inForm;
}
public void leaveForm() {
inForm = null;
}
public void clearParammaps(){
parammap.clear();
parammapvalues.clear();
fileUploads.clear();
}
protected java.util.Map<String, String> parammap;
public java.util.Map<String, String> getParammap() {
return parammap;
}
protected Map<String,List<utils.File>> fileUploads;
public Map<String, List<utils.File>> getFileUploads() {
return fileUploads;
}
public List<utils.File> getFileUploads(String key) {
return fileUploads.get(key);
}
protected Map<String, List<String>> parammapvalues;
public Map<String, List<String>> getParammapvalues() {
return parammapvalues;
}
protected String pageTitle = "";
public String getPageTitle() {
return pageTitle;
}
public void setPageTitle(String pageTitle) {
this.pageTitle = pageTitle;
}
protected String formIdent = "";
public String getFormIdent() {
return formIdent;
}
public void setFormIdent(String fi) {
this.formIdent = fi;
}
protected boolean actionLinkUsed = false;
public boolean isActionLinkUsed() {
return actionLinkUsed;
}
public void setActionLinkUsed(boolean a) {
this.actionLinkUsed = a;
}
protected boolean ajaxRuntimeRequest = false;
public boolean isAjaxRuntimeRequest() {
return ajaxRuntimeRequest;
}
public void setAjaxRuntimeRequest(boolean a) {
ajaxRuntimeRequest = a;
}
protected String redirectUrl = "";
public boolean isRedirected(){
return !"".equals(redirectUrl);
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String a) {
this.redirectUrl = a;
}
// perform the actual redirect
public void redirect(){
try { response.sendRedirect(this.getRedirectUrl()); }
catch (IOException ioe) { org.webdsl.logging.Logger.error("redirect failed", ioe); }
}
protected String mimetype = "text/html; charset=UTF-8";
protected boolean mimetypeChanged = false;
public String getMimetype() {
return mimetype;
}
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
mimetypeChanged = true;
if(!isMarkupLangMimeType.matcher(mimetype).find()){
enableRawoutput();
}
disableTemplateSpans();
}
protected boolean downloadInline = false;
public boolean getDownloadInline() {
return downloadInline;
}
public void enableDownloadInline() {
this.downloadInline = true;
}
protected boolean ajaxActionExecuted = false;
public boolean isAjaxActionExecuted() {
return ajaxActionExecuted;
}
public void enableAjaxActionExecuted() {
ajaxActionExecuted = true;
}
protected boolean rawoutput = false;
public boolean isRawoutput() {
return rawoutput;
}
public void enableRawoutput() {
rawoutput = true;
}
public void disableRawoutput() {
rawoutput = false;
}
protected String[] pageArguments = null;
public void setPageArguments(String[] pa) {
pageArguments = pa;
}
public String[] getPageArguments() {
return pageArguments;
}
protected String httpMethod = null;
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public String getHttpMethod() {
return httpMethod;
}
protected boolean templateSpans = true;
public boolean templateSpans() {
return templateSpans;
}
public void disableTemplateSpans() {
templateSpans = false;
}
protected List<String> reRenderPlaceholders = null;
protected Map<String,String> reRenderPlaceholdersContent = null;
public boolean isReRenderPlaceholders() {
return reRenderPlaceholders != null;
}
public void addReRenderPlaceholders(String placeholder) {
if(reRenderPlaceholders == null){
reRenderPlaceholders = new ArrayList<String>();
reRenderPlaceholdersContent = new HashMap<String,String>();
}
reRenderPlaceholders.add(placeholder);
}
public void addReRenderPlaceholdersContent(String placeholder, String content) {
if(reRenderPlaceholders != null && reRenderPlaceholders.contains(placeholder)){
reRenderPlaceholdersContent.put(placeholder,content);
}
}
protected utils.File download = null;
public void setDownload(utils.File file){
this.download = file;
}
public boolean isDownloadSet(){
return this.download != null;
}
protected void download()
{
/*
Long id = download.getId();
org.hibernate.Session hibSession = HibernateUtilConfigured.getSessionFactory().openSession();
hibSession.beginTransaction();
hibSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
utils.File download = (utils.File)hibSession.load(utils.File.class,id);
*/
try
{
javax.servlet.ServletOutputStream outstream;
outstream = response.getOutputStream();
java.sql.Blob blob = download.getContent();
java.io.InputStream in;
in = blob.getBinaryStream();
response.setContentType(download.getContentType());
if(!downloadInline) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + download.getFileNameForDownload() + "\"");
}
java.io.BufferedOutputStream bufout = new java.io.BufferedOutputStream(outstream);
byte bytes[] = new byte[32768];
int index = in.read(bytes, 0, 32768);
while(index != -1)
{
bufout.write(bytes, 0, index);
index = in.read(bytes, 0, 32768);
}
bufout.flush();
}
catch(java.sql.SQLException ex)
{
org.webdsl.logging.Logger.error("exception in download serve", ex);
}
catch (IOException ex) {
if(ex.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
org.webdsl.logging.Logger.error( "ClientAbortException - " + ex.getMessage() );
} else {
org.webdsl.logging.Logger.error("exception in download serve",ex);
}
}
/*
hibSession.flush();
hibSession.getTransaction().commit();
*/
}
//data validation
public java.util.LinkedList<String> validationContext = new java.util.LinkedList<String>();
public String getValidationContext() {
//System.out.println("using" + validationContext.peek());
return validationContext.peek();
}
public void enterValidationContext(String ident) {
validationContext.add(ident);
//System.out.println("entering" + ident);
}
public void leaveValidationContext() {
/*String s = */ validationContext.removeLast();
//System.out.println("leaving" +s);
}
public boolean inValidationContext() {
return validationContext.size() != 0;
}
//form
public boolean formRequiresMultipartEnc = false;
//formGroup
public String formGroupLeftSize = "150";
//public java.util.Stack<utils.FormGroupContext> formGroupContexts = new java.util.Stack<utils.FormGroupContext>();
public utils.FormGroupContext getFormGroupContext() {
return (utils.FormGroupContext) tableContexts.peek();
}
public void enterFormGroupContext() {
tableContexts.push(new utils.FormGroupContext());
}
public void leaveFormGroupContext() {
tableContexts.pop();
}
public boolean inFormGroupContext() {
return !tableContexts.empty() && tableContexts.peek() instanceof utils.FormGroupContext;
}
public java.util.Stack<String> formGroupContextClosingTags = new java.util.Stack<String>();
public void formGroupContextsCheckEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInDoubleColumnContext()){ // ignore defaults when in scope of a double column
if(!temp.isInColumnContext()){ //don't nest left and right
temp.enterColumnContext();
if(temp.isInLeftContext()) {
out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">");
formGroupContextClosingTags.push("left");
temp.toRightContext();
}
else {
out.print("<div style=\"float: left;\">");
formGroupContextClosingTags.push("right");
temp.toLeftContext();
}
}
else{
formGroupContextClosingTags.push("none");
}
}
}
}
public void formGroupContextsCheckLeave(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInDoubleColumnContext()) {
String tags = formGroupContextClosingTags.pop();
if(tags.equals("left")){
//temp.toRightContext();
temp.leaveColumnContext();
out.print("</div>");
}
else if(tags.equals("right")){
//temp.toLeftContext();
temp.leaveColumnContext();
out.print("</div>");
}
}
}
}
public void formGroupContextsDisplayLeftEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInColumnContext()){
temp.enterColumnContext();
out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">");
formGroupContextClosingTags.push("left");
temp.toRightContext();
}
else{
formGroupContextClosingTags.push("none");
}
}
}
public void formGroupContextsDisplayRightEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInColumnContext()){
temp.enterColumnContext();
out.print("<div style=\"float: left;\">");
formGroupContextClosingTags.push("right");
temp.toLeftContext();
}
else{
formGroupContextClosingTags.push("none");
}
}
}
//label
public String getLabelString() {
return getLabelStringForTemplateContext(ThreadLocalTemplate.get().getUniqueId());
}
public java.util.Stack<String> labelStrings = new java.util.Stack<String>();
public java.util.Set<String> usedPageElementIds = new java.util.HashSet<String>();
public static java.util.Random rand = new java.util.Random();
//avoid duplicate ids; if multiple inputs are in a label, only the first is connected to the label
public String getLabelStringOnce() {
String s = labelStrings.peek();
if(usedPageElementIds.contains(s)){
do{
s += rand.nextInt();
}
while(usedPageElementIds.contains(s));
}
usedPageElementIds.add(s);
return s;
}
public java.util.Map<String,String> usedPageElementIdsTemplateContext = new java.util.HashMap<String,String>();
//subsequent calls from the same defined template (e.g. in different phases) should produce the same id
public String getLabelStringForTemplateContext(String context) {
String labelid = usedPageElementIdsTemplateContext.get(context);
if(labelid == null){
labelid = getLabelStringOnce();
usedPageElementIdsTemplateContext.put(context, labelid);
}
return labelid;
}
public void enterLabelContext(String ident) {
labelStrings.push(ident);
}
public void leaveLabelContext() {
labelStrings.pop();
}
public boolean inLabelContext() {
return !labelStrings.empty();
}
//section
public int sectionDepth = 0;
public int getSectionDepth() {
return sectionDepth;
}
public void enterSectionContext() {
sectionDepth++;
}
public void leaveSectionContext() {
sectionDepth--;
}
public boolean inSectionContext() {
return sectionDepth > 0;
}
//table
public java.util.Stack<Object> tableContexts = new java.util.Stack<Object>();
public utils.TableContext getTableContext() {
return (utils.TableContext) tableContexts.peek();
}
public void enterTableContext() {
tableContexts.push(new utils.TableContext());
}
public void leaveTableContext() {
tableContexts.pop();
}
public boolean inTableContext() {
return !tableContexts.empty() && tableContexts.peek() instanceof utils.TableContext;
}
public java.util.Stack<String> tableContextClosingTags = new java.util.Stack<String>();
//separate row and column checks, used by label
public void rowContextsCheckEnter(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
if(!x_temp.isInRowContext()) {
out.print("<tr>");
x_temp.enterRowContext();
tableContextClosingTags.push("</tr>");
}
else{
tableContextClosingTags.push("");
}
}
}
public void rowContextsCheckLeave(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
String tags = tableContextClosingTags.pop();
if(tags.equals("</tr>")){
x_temp.leaveRowContext();
out.print(tags);
}
}
}
public void columnContextsCheckEnter(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
if(x_temp.isInRowContext() && !x_temp.isInColumnContext()) {
out.print("<td>");
x_temp.enterColumnContext();
tableContextClosingTags.push("</td>");
}
else{
tableContextClosingTags.push("");
}
}
}
public void columnContextsCheckLeave(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
String tags = tableContextClosingTags.pop();
if(tags.equals("</td>")){
x_temp.leaveColumnContext();
out.print(tags);
}
}
}
//session manager
public void reloadSessionManagerFromExistingSessionId(UUID sessionId){
ThreadLocalServlet.get().reloadSessionManagerFromExistingSessionId(hibernateSession, sessionId);
initialize(); //reload session variables
}
//request vars
public HashMap<String, Object> requestScopedVariables = new HashMap<String, Object>();
public void initRequestVars(){
initRequestVars(null);
}
public abstract void initRequestVars(PrintWriter out);
protected long startTime = 0L;
public long getStartTime() {
return startTime;
}
public long getElapsedTime() {
return System.currentTimeMillis() - startTime;
}
public Object getRequestScopedVar(String key){
return commandingPage.requestScopedVariables.get(key);
}
public void addRequestScopedVar(String key, Object val){
if(val != null){
commandingPage.requestScopedVariables.put(key, val);
}
}
public void addRequestScopedVar(String key, WebDSLEntity val){
if(val != null){
val.setRequestVar();
commandingPage.requestScopedVariables.put(key, val);
}
}
// statistics to be shown in log
protected abstract void increaseStatReadOnly();
protected abstract void increaseStatReadOnlyFromCache();
protected abstract void increaseStatUpdate();
protected abstract void increaseStatActionFail();
protected abstract void increaseStatActionReadOnly();
protected abstract void increaseStatActionUpdate();
// register whether entity changes were made, see isChanged property of entities
protected boolean hasWrites = false;
public void setHasWrites(boolean b){
commandingPage.hasWrites = b;
}
protected void updatePageRequestStatistics(){
if(hasNotExecutedAction()){
if(!hasWrites || isRollback()){
if(pageCacheWasUsed){
increaseStatReadOnlyFromCache();
}
else{
increaseStatReadOnly();
}
}
else{
increaseStatUpdate();
}
}
else{
if(isNotValid()){
increaseStatActionFail();
}
else{
if(!hasWrites || isRollback()){
increaseStatActionReadOnly();
}
else{
increaseStatActionUpdate();
}
}
}
}
// Hibernate interceptor hooks (such as beforeTransactionCompletion) catch Throwable but then only log the error, e.g. when db transaction conflict occurs
// this causes the problem that a page might be rendered with data that was not actually committed
// workaround: store the exception in this variable and explicitly rethrow before sending page content to output stream
public Exception exceptionInHibernateInterceptor = null;
public static Environment loadTemplateMap(Class<?> clazz) {
return loadTemplateMap(clazz, null, staticEnv);
}
public static Environment loadTemplateMap(Class<?> clazz, String keyOverwrite, Environment env) {
reflectionLoadClassesHelper(clazz, "loadTemplateMap", new Object[] { keyOverwrite, env });
return env;
}
public static Object[] loadEmailAndTemplateMapArgs = new Object[] { staticEnv, emails };
public static void loadEmailAndTemplateMap(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadEmailAndTemplateMap", loadEmailAndTemplateMapArgs);
}
public static Object[] loadLiftedTemplateMapArgs = new Object[] { staticEnv };
public static void loadLiftedTemplateMap(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadLiftedTemplateMap", loadLiftedTemplateMapArgs);
}
public static Object[] loadRefArgClassesArgs = new Object[] { refargclasses };
public static void loadRefArgClasses(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadRefArgClasses", loadRefArgClassesArgs);
}
public static void reflectionLoadClassesHelper(Class<?> clazz, String method, Object[] args) {
for (java.lang.reflect.Method m : clazz.getMethods()) {
if (method.equals(m.getName())) { // will just skip if not defined, so the code generator does not need to generate empty methods
try {
m.invoke(null, args);
} catch (IllegalAccessException | IllegalArgumentException | java.lang.reflect.InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
}
}
|
UTF-8
|
Java
| 68,876 |
java
|
AbstractPageServlet.java
|
Java
|
[
{
"context": "us page cache\n \t\t){\n \t\t\tkey = key + servlet.getSessionManager().getId();\n \t\t\tcache = cacheUserSpecificPages;\n \t\t}",
"end": 19990,
"score": 0.8926440477371216,
"start": 19965,
"tag": "KEY",
"value": "getSessionManager().getId"
}
] | null |
[] |
package utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.webdsl.WebDSLEntity;
import org.webdsl.lang.Environment;
import org.webdsl.logging.Logger;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public abstract class AbstractPageServlet{
protected abstract void renderDebugJsVar(PrintWriter sout);
protected abstract boolean logSqlCheckAccess();
protected abstract void initTemplateClass();
protected abstract boolean isActionSubmit();
protected abstract String[] getUsedSessionEntityJoins();
protected TemplateServlet templateservlet = null;
protected abstract org.webdsl.WebDSLEntity getRequestLogEntry();
protected abstract void addPrincipalToRequestLog(org.webdsl.WebDSLEntity rle);
protected abstract void addLogSqlToSessionMessages();
public Session hibernateSession = null;
protected static Pattern isMarkupLangMimeType= Pattern.compile("html|xml$");
protected static Pattern baseURLPattern= Pattern.compile("(^\\w{0,6})(://[^/]+)");
protected AbstractPageServlet commandingPage = this;
public boolean isReadOnly = false;
public boolean isWebService(){ return false; }
public String placeholderId = "1";
static{
ajax_js_include_name = "ajax.js";
}
public void serve(HttpServletRequest request, HttpServletResponse httpServletResponse, Map<String, String> parammap, Map<String, List<String>> parammapvalues, Map<String,List<utils.File>> fileUploads) throws Exception
{
initTemplateClass();
this.startTime = System.currentTimeMillis();
ThreadLocalPage.set(this);
this.request=request;
this.httpServletResponse = httpServletResponse;
this.response = new ResponseWrapper(httpServletResponse);
this.parammap = parammap;
this.parammapvalues = parammapvalues;
this.fileUploads=fileUploads;
String ajaxParam = parammap.get( "__ajax_runtime_request__" );
if( ajaxParam != null ){
this.setAjaxRuntimeRequest( true );
if( ajaxParam != "1" ){
placeholderId = ajaxParam;
}
}
org.webdsl.WebDSLEntity rle = getRequestLogEntry();
org.apache.logging.log4j.ThreadContext.put("request", rle.getId().toString());
org.apache.logging.log4j.ThreadContext.put("template", "/" + getPageName());
utils.RequestAppender reqAppender = null;
if(parammap.get("disableopt") != null){
this.isOptimizationEnabled = false;
}
if(parammap.get("logsql") != null){
this.isLogSqlEnabled = true;
this.isPageCacheDisabled = true;
reqAppender = utils.RequestAppender.getInstance();
}
if(reqAppender != null){
reqAppender.addRequest(rle.getId().toString());
}
if(parammap.get("nocache") != null){
this.isPageCacheDisabled = true;
}
initRequestVars();
hibernateSession = utils.HibernateUtil.getCurrentSession();
hibernateSession.beginTransaction();
if(isReadOnly){
hibernateSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
}
else{
hibernateSession.setFlushMode(org.hibernate.FlushMode.COMMIT);
}
try
{
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
ThreadLocalServlet.get().loadSessionManager(hibernateSession, getUsedSessionEntityJoins());
ThreadLocalServlet.get().retrieveIncomingMessagesFromHttpSession();
initVarsAndArgs();
enterPlaceholderIdContext();
if(isActionSubmit()) {
if(parammap.get("__action__link__") != null) {
this.setActionLinkUsed(true);
}
templateservlet.storeInputs(null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
//storeinputs also finds which action is executed, since validation might be ignored using [ignore-validation] on the submit
boolean ignoreValidation = actionToBeExecutedHasDisabledValidation;
if (!ignoreValidation){
templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
}
if(validated){
templateservlet.handleActions(null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
}
}
if(isNotValid()){
// mark transaction so it will be aborted at the end
// entered form data can be used to update the form on the client with ajax, taking into account if's and other control flow template elements
// this also means that data in vars/args and hibernate session should not be cleared until form is rendered
abortTransaction();
}
String outstream = s.toString();
if(download != null) { //File.download() excecuted in action
download();
}
else {
boolean isAjaxResponse = true;
// regular render, or failed action render
if( hasNotExecutedAction() || isNotValid() ){
// ajax replace performed during validation, assuming that handles all validation
// all inputajax templates use rollback() to prevent making actual changes -> check for isRollback()
if(isAjaxRuntimeRequest() && outstream.length() > 0 && isRollback()){
response.getWriter().write("[");
response.getWriter().write(outstream);
if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions
if(logSqlCheckAccess()){
response.getWriter().write("{\"action\":\"logsql\",\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}");
}
else{
response.getWriter().write("{\"action\":\"logsql\",\"value\":\"Access to SQL logs was denied.\"}");
}
response.getWriter().write(",");
}
response.getWriter().write("{}]");
}
// action called but no action found
else if( !isWebService() && isValid() && isActionSubmit() ){
org.webdsl.logging.Logger.error("Error: server received POST request but was unable to dispatch to a proper action (" + getRequestURL() + ")" );
httpServletResponse.setStatus( 404 );
response.getWriter().write("404 \n Error: server received POST request but was unable to dispatch to a proper action");
}
// action inside ajax template called and failed
else if( isAjaxTemplateRequest() && isActionSubmit() ){
StringWriter s1 = renderPageOrTemplateContents();
response.getWriter().write("[{\"action\":\"replace\",\"id\":{\"type\":\"enclosing-placeholder\"},\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(s1.toString()) + "\"}]");
}
//actionLink or ajax action used (request came through js runtime), and action failed
else if( isActionLinkUsed() || isAjaxRuntimeRequest() ){
validationFormRerender = true;
renderPageOrTemplateContents();
if(submittedFormId != null){
response.getWriter().write("[{\"action\":\"replace\",\"id\":\"" + submittedFormId + "\",\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]");
}
else{
response.getWriter().write("[{\"action\":\"replace\",\"id\":{submitid:'" + submittedSubmitId + "'},\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]");
}
}
// 1 regular render without any action being executed
// 2 regular action submit, and action failed
// 3 redirect in page init
// 4 download in page init
else{
isAjaxResponse = false;
renderOrInitAction();
}
}
// successful action, always redirect, no render
else {
// actionLink or ajax action used and replace(placeholder) invoked
if( isReRenderPlaceholders() ){
StringBuilder commands = new StringBuilder("[");
templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null);
clearTemplateContext();
renderDynamicFormWithOnlyDirtyData = true;
shouldReInitializeTemplates = true;
renderPageOrTemplateContents(); // content of placeholders is collected in reRenderPlaceholdersContent map
//For now we do not support dynamically loading of resources in case of a rerendered placeholder,
//because this would try to load the js/css resources from the whole page while only a part gets rerendered
// if(this.javascripts.size() > 0) {
// commands.append( requireJSCommand() ).append(",");
// }
// if(this.stylesheets.size() > 0) {
// commands.append( requireCSSCommand() ).append(",");
// }
boolean addComma = false;
for(String ph : reRenderPlaceholders){
if(addComma){ commands.append(","); }
else { addComma = true; }
commands.append("{\"action\":\"replace\",\"id\":\"")
.append(ph)
.append("\",\"value\":\"")
.append(org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(reRenderPlaceholdersContent.get(ph)))
.append("\"}");
}
if( outstream.length() > 0 ){
commands.append( "," + outstream.substring(0, outstream.length() - 1) ); // Other ajax updates, such as clear(ph). Done after ph rerendering to allow customization.
}
commands.append("]");
response.getWriter().write( commands.toString() );
}
//hasExecutedAction() && isValid()
else if( isAjaxRuntimeRequest() ){
PrintWriter responseWriter = response.getWriter();
responseWriter.write("[");
if(this.javascripts.size() > 0) {
responseWriter.write( requireJSCommand() );
responseWriter.write(",");
}
if(this.stylesheets.size() > 0) {
responseWriter.write( requireCSSCommand() );
responseWriter.write(",");
}
responseWriter.write(outstream);
if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions
if(logSqlCheckAccess()){
responseWriter.write("{\"action\":\"logsql\",\"value\":\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}");
}
else{
responseWriter.write("{\"action\":\"logsql\",\"value\":\"Access to SQL logs was denied.\"}");
}
responseWriter.write(",");
}
if( this.validateFailedBeforeRollback ){
responseWriter.write("{\"action\":\"skip_next_action\"}]");
}
else {
responseWriter.write("{}]");
}
}
else if( isActionLinkUsed() ){
//action link also uses ajax when ajax is not enabled
//, send only redirect location, so the client can simply set
// window.location = req.responseText;
response.getWriter().write("[{\"action\":\"relocate\",\"value\":\""+this.getRedirectUrl() + "\"}]");
} else {
isAjaxResponse = false;
}
if(!isAjaxRuntimeRequest()) {
addLogSqlToSessionMessages();
}
//else: action successful + no validation error + regular submit
// -> always results in a redirect, no further action necessary here
}
if(isAjaxResponse){
response.setContentType("application/json");
}
}
updatePageRequestStatistics();
hibernateSession = utils.HibernateUtil.getCurrentSession();
if( isTransactionAborted() || isRollback() ){
try{
hibernateSession.getTransaction().rollback();
response.sendContent();
}
catch (org.hibernate.SessionException e){
if(!e.getMessage().equals("Session is closed!")){ // closed session is not an issue when rolling back
throw e;
}
}
}
else {
ThreadLocalServlet.get().storeOutgoingMessagesInHttpSession( !isRedirected() || isPostRequest() );
addPrincipalToRequestLog(rle);
if(!this.isAjaxRuntimeRequest()){
ThreadLocalServlet.get().setEndTimeAndStoreRequestLog(utils.HibernateUtil.getCurrentSession());
}
ThreadLocalServlet.get().setCookie(hibernateSession);
if(isReadOnly || !hasWrites){ // either page has read-only modifier, or no writes have been detected
hibernateSession.getTransaction().rollback();
}
else{
hibernateSession.flush();
validateEntities();
hibernateSession.getTransaction().commit();
invalidatePageCacheIfNeeded();
}
if(exceptionInHibernateInterceptor != null){
throw exceptionInHibernateInterceptor;
}
response.sendContent();
}
ThreadLocalOut.popChecked(out);
}
catch(utils.MultipleValidationExceptions mve){
String url = getRequestURL();
org.webdsl.logging.Logger.error("Validation exceptions occurred while handling request URL [ " + url + " ]. Transaction is rolled back.");
for(utils.ValidationException vex : mve.getValidationExceptions()){
org.webdsl.logging.Logger.error( "Validation error: " + vex.getErrorMessage() , vex );
}
hibernateSession.getTransaction().rollback();
setValidated(false);
throw mve;
}
catch(utils.EntityNotFoundException enfe) {
org.webdsl.logging.Logger.error( enfe.getMessage() + ". Transaction is rolled back." );
if(hibernateSession.isOpen()){
hibernateSession.getTransaction().rollback();
}
throw enfe;
}
catch (Exception e) {
String url = getRequestURL();
org.webdsl.logging.Logger.error("exception occurred while handling request URL [ " + url + " ]. Transaction is rolled back.");
org.webdsl.logging.Logger.error("exception message: "+e.getMessage(), e);
if(hibernateSession.isOpen()){
hibernateSession.getTransaction().rollback();
}
throw e;
}
finally{
cleanupThreadLocals();
org.apache.logging.log4j.ThreadContext.remove("request");
org.apache.logging.log4j.ThreadContext.remove("template");
if(reqAppender != null) reqAppender.removeRequest(rle.getId().toString());
}
}
// LoadingCache is thread-safe
public static boolean pageCacheEnabled = utils.BuildProperties.getNumCachedPages() > 0;
public static Cache<String, CacheResult> cacheAnonymousPages =
CacheBuilder.newBuilder()
.maximumSize(utils.BuildProperties.getNumCachedPages()).build();
public boolean invalidateAllPageCache = false;
protected boolean shouldTryCleanPageCaches = false;
public String invalidateAllPageCacheMessage;
public void invalidateAllPageCache(String entityname){
commandingPage.invalidateAllPageCacheInternal(entityname);
}
private void invalidateAllPageCacheInternal(String entityname){
invalidateAllPageCache = true;
invalidateAllPageCacheMessage = entityname;
}
public void shouldTryCleanPageCaches(){
commandingPage.shouldTryCleanPageCachesInternal();
}
private void shouldTryCleanPageCachesInternal(){
shouldTryCleanPageCaches = true;
}
public static void doInvalidateAllPageCache( String triggerReason ) {
Logger.info( "All page caches invalidated, triggered by: " + triggerReason );
cacheAnonymousPages.invalidateAll();
cacheUserSpecificPages.invalidateAll();
}
public static void doInvalidateUserSpecificPageCache( String triggerReason ) {
Logger.info( "User-specific page caches invalidated, triggered by: " + triggerReason );
cacheUserSpecificPages.invalidateAll();
}
public static Cache<String, CacheResult> cacheUserSpecificPages =
CacheBuilder.newBuilder()
.maximumSize(utils.BuildProperties.getNumCachedPages()).build();
public boolean invalidateUserSpecificPageCache = false;
public String invalidateUserSpecificPageCacheMessage;
public void invalidateUserSpecificPageCache(String entityname){
commandingPage.invalidateUserSpecificPageCacheInternal(entityname);
}
private void invalidateUserSpecificPageCacheInternal(String entityname){
invalidateUserSpecificPageCache = true;
String propertySetterTrace = Warning.getStackTraceLineAtIndex(4);
invalidateUserSpecificPageCacheMessage = entityname + " - " + propertySetterTrace;
}
public boolean pageCacheWasUsed = false;
public void invalidatePageCacheIfNeeded(){
if(pageCacheEnabled && shouldTryCleanPageCaches){
if(invalidateAllPageCache){
doInvalidateAllPageCache("change in: "+invalidateAllPageCacheMessage);
}
else if(invalidateUserSpecificPageCache){
doInvalidateUserSpecificPageCache("change in: "+invalidateUserSpecificPageCacheMessage);
}
}
}
public void renderOrInitAction() throws IOException{
String key = getRequestURL();
String s = "";
Cache<String, CacheResult> cache = null;
AbstractDispatchServletHelper servlet = ThreadLocalServlet.get();
if( // not using page cache if:
this.isPageCacheDisabled // ?nocache added to URL
|| this.isPostRequest() // post parameters are not included in cache key
|| isNotValid() // data validation errors need to be rendered
|| !servlet.getIncomingSuccessMessages().isEmpty() // success messages need to be rendered
){
StringWriter renderedContent = renderPageOrTemplateContents();
if(!mimetypeChanged){
s = renderResponse(renderedContent);
}
else{
s = renderedContent.toString();
}
}
else{ // using page cache
if( // use user-specific page cache if:
servlet.sessionHasChanges() // not necessarily login, any session data changes can be included in a rendered page
|| webdsl.generated.functions.loggedIn_.loggedIn_() // user might have old session from before application start, this check is needed to avoid those logged in pages ending up in the anonymous page cache
){
key = key + servlet.getSessionManager().getId();
cache = cacheUserSpecificPages;
}
else{
cache = cacheAnonymousPages;
}
try{
pageCacheWasUsed = true;
CacheResult result = cache.get(key,
new Callable<CacheResult>(){
public CacheResult call(){
// System.out.println("key not found");
pageCacheWasUsed = false;
StringWriter renderedContent = renderPageOrTemplateContents();
CacheResult result = new CacheResult();
if(!mimetypeChanged){
result.body = renderResponse(renderedContent);
}
else{
result.body = renderedContent.toString();
}
result.mimetype = getMimetype();
return result;
}
});
s = result.body;
setMimetype(result.mimetype);
}
catch(java.util.concurrent.ExecutionException e){
e.printStackTrace();
}
}
// redirect in init action can be triggered with GET request, the render call in the line above will execute such inits
if( !isPostRequest() && isRedirected() ){
redirect();
if(cache != null){ cache.invalidate(key); }
}
else if( download != null ){ //File.download() executed in page/template init block
download();
if(cache != null){ cache.invalidate(key); } // don't cache binary file response in this page response cache, can be cached on client with expires header
}
else{
response.setContentType(getMimetype());
PrintWriter sout = response.getWriter(); //reponse.getWriter() must be called after file download checks
sout.write(s);
}
}
public boolean renderDynamicFormWithOnlyDirtyData = false;
public StringWriter renderPageOrTemplateContents(){
if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); }
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
if(getParammap().get("dynamicform") == null){
// regular pages and forms
if(isNotValid()){
clearHibernateCache();
}
ThreadLocalOut.push(out);
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
}
else{
shouldReInitializeTemplates = false;
// dynamicform uses submitted variable data to process form content
// render form with newly entered data, rest with the current persisted data
if(isNotValid() && !renderDynamicFormWithOnlyDirtyData){
StringWriter theform = new StringWriter();
PrintWriter pwform = new PrintWriter(theform);
ThreadLocalOut.push(pwform);
// render, when encountering submitted form save in abstractpage
validationFormRerender = true;
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(pwform);
clearHibernateCache();
}
ThreadLocalOut.push(out);
// render, when isNotValid and encountering submitted form render old
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
}
return s;
}
public StringWriter renderPageOrTemplateContentsSingle(){
if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); }
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
templateservlet.render(null, args, new Environment(envGlobalAndSession), null);
ThreadLocalOut.popChecked(out);
return s;
}
private boolean validationFormRerender = false;
public boolean isValidationFormRerender(){
return validationFormRerender;
}
public String submittedFormContent = null;
public String submittedFormId = null;
public String submittedSubmitId = null;
// helper methods that enable a submit without enclosing form to be ajax-refreshed when validation error occurs
protected StringWriter submitWrapSW;
protected PrintWriter submitWrapOut;
public void submitWrapOpenHelper(String submitId){
if( ! inSubmittedForm && validationFormRerender && request != null && getParammap().get(submitId) != null ){
submittedSubmitId = submitId;
submitWrapSW = new java.io.StringWriter();
submitWrapOut = new java.io.PrintWriter(submitWrapSW);
ThreadLocalOut.push(submitWrapOut);
ThreadLocalOut.peek().print("<span submitid=" + submitId + ">");
}
}
public void submitWrapCloseHelper(){
if( ! inSubmittedForm && validationFormRerender && submitWrapSW != null ){
ThreadLocalOut.peek().print("</span>");
ThreadLocalOut.pop();
submittedFormContent = submitWrapSW.toString();
submitWrapSW = null;
}
}
private static String ajax_js_include_name;
public String renderResponse(StringWriter s) {
StringWriter sw = new StringWriter();
PrintWriter sout = new PrintWriter(sw);
ThreadLocalOut.push(sout);
addJavascriptInclude( utils.IncludePaths.jQueryJS() );
addJavascriptInclude( ajax_js_include_name );
sout.println("<!DOCTYPE html>");
sout.println("<html>");
sout.println("<head>");
if( !customHeadNoDuplicates.containsKey( "viewport" ) ) {
sout.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
}
if( !customHeadNoDuplicates.containsKey( "contenttype" ) ) {
sout.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
}
if( !customHeadNoDuplicates.containsKey( "favicon" ) ) {
sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+ CachedResourceFileNameHelper.fav_ico_link_tag_suffix);
}
if( !customHeadNoDuplicates.containsKey( "defaultcss" ) ) {
sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+ CachedResourceFileNameHelper.common_css_link_tag_suffix);
}
sout.println("<title>"+getPageTitle().replaceAll("<[^>]*>","")+"</title>");
renderDebugJsVar(sout);
sout.println("<script type=\"text/javascript\">var contextpath=\""+ThreadLocalPage.get().getAbsoluteLocation()+"\";</script>");
for(String sheet : this.stylesheets) {
String href = computeResourceSrc("stylesheets", sheet);
sout.print("<link rel=\"stylesheet\" href=\""+ href + "\" type=\"text/css\" />");
}
for(String script : this.javascripts) {
String src = computeResourceSrc("javascript", script);
sout.println("<script type=\"text/javascript\" src=\"" + src + "\"></script>");
}
for(Map.Entry<String,String> headEntry : customHeadNoDuplicates.entrySet()) {
// sout.println("<!-- " + headEntry.getKey() + " -->");
sout.println(headEntry.getValue());
}
sout.println("</head>");
sout.print("<body id=\""+this.getPageName()+"\"");
for(String attribute : this.bodyAttributes) {
sout.print(attribute);
}
sout.print(">");
renderLogSqlMessage();
renderIncomingSuccessMessages();
s.flush();
sout.write(s.toString());
if(this.isLogSqlEnabled()){
if(logSqlCheckAccess()){
sout.print("<hr/><div class=\"logsql\">");
sout.print("<script type=\"text/javascript\">$('a.navigate').on('click', function(event) { event.target.href += '?logsql' })</script>");
utils.HibernateLog.printHibernateLog(sout, this, null);
sout.print("</div>");
}
else{
sout.print("<hr/><div class=\"logsql\">Access to SQL logs was denied.</div>");
}
}
for(String script : this.tailJavascripts) {
String src = computeResourceSrc("javascript", script);
sout.println("<script type=\"text/javascript\" src=\"" + src + "\"></script>");
}
sout.print("</body>");
sout.println("</html>");
ThreadLocalOut.popChecked(sout);
return sw.toString();
}
private String computeResourceSrc(String resourceDirName, String url) {
if(url.startsWith("//") || url.startsWith("http://") || url.startsWith("https://")) {
return url;
} else {
String hashedName = CachedResourceFileNameHelper.getNameWithHash(resourceDirName, url);
return ThreadLocalPage.get().getAbsoluteLocation()+"/"+resourceDirName+"/"+hashedName;
}
}
private String requireJSCommand() {
StringBuilder aStr = new StringBuilder("{ \"action\":\"require_js\", \"value\": [");
boolean addComma = false;
for(String script : this.javascripts) {
if(addComma) {
aStr.append(",");
} else{
addComma = true;
}
String src = computeResourceSrc("javascript", script);
aStr.append( "\"" ).append( org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(src) ).append("\"");
}
aStr.append("] }");
return aStr.toString();
}
private String requireCSSCommand() {
StringBuilder aStr = new StringBuilder("{ \"action\":\"require_css\", \"value\": [");
boolean addComma = false;
for(String sheet : this.stylesheets) {
if(addComma) {
aStr.append(",");
} else{
addComma = true;
}
String href = computeResourceSrc("stylesheets", sheet);
aStr.append( "\"" ).append( org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(href) ).append("\"");
}
aStr.append("] }");
return aStr.toString();
}
//ajax/js runtime request related
protected abstract void initializeBasics(AbstractPageServlet ps, Object[] args);
public boolean isServingAsAjaxResponse = false;
public void serveAsAjaxResponse(Object[] args, TemplateCall templateArg, String placeholderId)
{
AbstractPageServlet ps = ThreadLocalPage.get();
TemplateServlet ts = ThreadLocalTemplate.get();
//inherit commandingPage
commandingPage = ps.commandingPage;
//use passed PageServlet ps here, since this is the context for this type of response
initializeBasics(ps, args);
ThreadLocalPage.set(this);
//outputstream threadlocal is already set, see to-java-servlet/ajax/ajax.str
this.isServingAsAjaxResponse = true;
this.placeholderId = placeholderId;
enterPlaceholderIdContext();
templateservlet.render(null, args, Environment.createNewLocalEnvironment(envGlobalAndSession), null); // new clean environment with only the global templates, and global/session vars
ThreadLocalTemplate.set(ts);
ThreadLocalPage.set(ps);
}
protected boolean isTemplate() { return false; }
public static AbstractPageServlet getRequestedPage(){
return ThreadLocalPage.get();
}
private boolean passedThroughAjaxTemplate = false;
public boolean passedThroughAjaxTemplate(){
return passedThroughAjaxTemplate;
}
public void setPassedThroughAjaxTemplate(boolean b){
passedThroughAjaxTemplate = b;
}
protected boolean isLogSqlEnabled = false;
public boolean isLogSqlEnabled() { return isLogSqlEnabled; }
public boolean isPageCacheDisabled = false;
protected boolean isOptimizationEnabled = true;
public boolean isOptimizationEnabled() { return isOptimizationEnabled; }
public String getExtraQueryArguments(String firstChar) { // firstChar is expected to be ? or &, depending on whether there are more query arguments
HttpServletRequest req = getRequest();
return (req != null && req.getQueryString() != null) ? (firstChar + req.getQueryString()) : "";
}
public abstract String getPageName();
public abstract String getUniqueName();
protected MessageDigest messageDigest = null;
public MessageDigest getMessageDigest(){
if(messageDigest == null){
try{
messageDigest = MessageDigest.getInstance("MD5");
}
catch(NoSuchAlgorithmException ae)
{
org.webdsl.logging.Logger.error("MD5 not available: "+ae.getMessage());
return null;
}
}
return messageDigest;
}
public boolean actionToBeExecutedHasDisabledValidation = false;
public boolean actionHasAjaxPageUpdates = false;
//TODO merge getActionTarget and getPageUrlWithParams
public String getActionTarget() {
if (isServingAsAjaxResponse){
return this.getUniqueName();
}
return getPageName();
}
//TODO merge getActionTarget and getPageUrlWithParams
public String getPageUrlWithParams(){ //used for action field in forms
if(isServingAsAjaxResponse){
return ThreadLocalPage.get().getAbsoluteLocation()+"/"+ThreadLocalPage.get().getActionTarget();
}
else{
//this doesn't work with ajax template render from action, since an ajax template needs to submit to a different page than the original request
return getRequestURL();
}
}
protected abstract void renderIncomingSuccessMessages();
protected abstract void renderLogSqlMessage();
public boolean isPostRequest(){
return ThreadLocalServlet.get().isPostRequest;
}
public boolean isNotPostRequest(){
return !ThreadLocalServlet.get().isPostRequest;
}
public boolean isAjaxTemplateRequest(){
return ThreadLocalServlet.get().getPages().get(ThreadLocalServlet.get().getRequestedPage()).isAjaxTemplate();
}
public abstract String getHiddenParams();
public abstract String getUrlQueryParams();
public abstract String getHiddenPostParamsJson();
//public javax.servlet.http.HttpSession session;
public static void cleanupThreadLocals(){
ThreadLocalEmailContext.set(null);
ThreadLocalPage.set(null);
ThreadLocalTemplate.setNull();
}
//templates scope
public static Environment staticEnv = Environment.createSharedEnvironment();
public Environment envGlobalAndSession = Environment.createLocalEnvironment();
//emails
protected static Map<String, Class<?>> emails = new HashMap<String, Class<?>>();
public static Map<String, Class<?>> getEmails() {
return emails;
}
public boolean sendEmail(String name, Object[] emailargs, Environment emailenv){
EmailServlet temp = renderEmail(name,emailargs,emailenv);
return temp.send();
}
public EmailServlet renderEmail(String name, Object[] emailargs, Environment emailenv){
EmailServlet temp = null;
try
{
temp = ((EmailServlet)getEmails().get(name).newInstance());
}
catch(IllegalAccessException iae)
{
org.webdsl.logging.Logger.error("Problem in email template lookup: " + iae.getMessage());
}
catch(InstantiationException ie)
{
org.webdsl.logging.Logger.error("Problem in email template lookup: " + ie.getMessage());
}
temp.render(emailargs, emailenv);
return temp;
}
//rendertemplate function
public String renderTemplate(String name, Object[] args, Environment env){
return executeTemplatePhase(RENDER_PHASE, name, args, env);
}
//validatetemplate function
public String validateTemplate(String name, Object[] args, Environment env){
return executeTemplatePhase(VALIDATE_PHASE, name, args, env);
}
public static final int DATABIND_PHASE = 1;
public static final int VALIDATE_PHASE = 2;
public static final int ACTION_PHASE = 3;
public static final int RENDER_PHASE = 4;
public String executeTemplatePhase(int phase, String name, Object[] args, Environment env){
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
ThreadLocalOut.push(out);
TemplateServlet enclosingTemplateObject = ThreadLocalTemplate.get();
try{
TemplateServlet temp = ((TemplateServlet)env.getTemplate(name).newInstance());
switch(phase){
case VALIDATE_PHASE: temp.validateInputs(name, args, env, null); break;
case RENDER_PHASE: temp.render(name, args, env, null); break;
}
}
catch(Exception oe){
try {
TemplateCall tcall = env.getWithcall(name); //'elements' or requires arg
TemplateServlet temp = ((TemplateServlet)env.getTemplate(tcall.name).newInstance());
String parent = env.getWithcall(name)==null?null:env.getWithcall(name).parentName;
switch(phase){
case VALIDATE_PHASE: temp.validateInputs(parent, tcall.args, env, null); break;
case RENDER_PHASE: temp.render(parent, tcall.args, env, null); break;
}
}
catch(Exception ie){
org.webdsl.logging.Logger.error("EXCEPTION",oe);
org.webdsl.logging.Logger.error("EXCEPTION",ie);
}
}
ThreadLocalTemplate.set(enclosingTemplateObject);
ThreadLocalOut.popChecked(out);
return s.toString();
}
//ref arg
protected static Map<String, Class<?>> refargclasses = new HashMap<String, Class<?>>();
public static Map<String, Class<?>> getRefArgClasses() {
return refargclasses;
}
public abstract String getAbsoluteLocation();
public String getXForwardedProto() {
if (request == null) {
return null;
} else {
return request.getHeader("x-forwarded-proto");
}
}
protected TemplateContext templateContext = new TemplateContext();
public String getTemplateContextString() {
return templateContext.getTemplateContextString();
}
public void enterPlaceholderIdContext() {
if( ! "1".equals( placeholderId ) ){
templateContext.enterTemplateContext( placeholderId );
}
}
public void enterTemplateContext(String s) {
templateContext.enterTemplateContext(s);
}
public void leaveTemplateContext() {
templateContext.leaveTemplateContext();
}
public void leaveTemplateContextChecked(String s) {
templateContext.leaveTemplateContextChecked(s);
}
public void clearTemplateContext(){
templateContext.clearTemplateContext();
enterPlaceholderIdContext();
}
public void setTemplateContext(TemplateContext tc){
templateContext = tc;
}
public TemplateContext getTemplateContext(){
return templateContext;
}
// objects scheduled to be checked after action completes, filled by hibernate event listener in hibernate util class
ArrayList<WebDSLEntity> entitiesToBeValidated = new ArrayList<WebDSLEntity>();
boolean allowAddingEntitiesForValidation = true;
public void clearEntitiesToBeValidated(){
entitiesToBeValidated = new ArrayList<WebDSLEntity>();
allowAddingEntitiesForValidation = true;
}
public void addEntityToBeValidated(WebDSLEntity w){
if(allowAddingEntitiesForValidation){
entitiesToBeValidated.add(w);
}
}
public void validateEntities(){
allowAddingEntitiesForValidation = false; //adding entities must be disabled when checking is performed, new entities may be loaded for checks, but do not have to be checked themselves
java.util.Set<WebDSLEntity> set = new java.util.HashSet<WebDSLEntity>(entitiesToBeValidated);
java.util.List<utils.ValidationException> exceptions = new java.util.LinkedList<utils.ValidationException>();
for(WebDSLEntity w : set){
if(w.isChanged()){
try {
// System.out.println("validating: "+ w.get_WebDslEntityType() + ":" + w.getName());
w.validateSave();
//System.out.println("done validating");
} catch(utils.ValidationException ve){
exceptions.add(ve);
} catch(utils.MultipleValidationExceptions ve) {
for(utils.ValidationException vex : ve.getValidationExceptions()){
exceptions.add(vex);
}
}
}
}
if(exceptions.size() > 0){
throw new utils.MultipleValidationExceptions(exceptions);
}
clearEntitiesToBeValidated();
}
protected List<utils.ValidationException> validationExceptions = new java.util.LinkedList<utils.ValidationException>();
public List<utils.ValidationException> getValidationExceptions() {
return validationExceptions;
}
public void addValidationException(String name, String message){
validationExceptions.add(new ValidationException(name,message));
}
public List<utils.ValidationException> getValidationExceptionsByName(String name) {
List<utils.ValidationException> list = new java.util.LinkedList<utils.ValidationException>();
for(utils.ValidationException v : validationExceptions){
if(v.getName().equals(name)){
list.add(v);
}
}
return list;
}
public List<String> getValidationErrorsByName(String name) {
List<String> list = new java.util.ArrayList<String>();
for(utils.ValidationException v : validationExceptions){
if(v.getName().equals(name)){
list.add(v.getErrorMessage());
}
}
return list;
}
public boolean hasExecutedAction = false;
public boolean hasExecutedAction(){ return hasExecutedAction; }
public boolean hasNotExecutedAction(){ return !hasExecutedAction; }
protected boolean abortTransaction = false;
public boolean isTransactionAborted(){ return abortTransaction; }
public void abortTransaction(){ abortTransaction = true; }
public java.util.List<String> ignoreset= new java.util.ArrayList<String>();
public boolean hibernateCacheCleared = false;
public boolean shouldReInitializeTemplates = false;
protected java.util.List<String> javascripts = new java.util.ArrayList<String>();
protected java.util.List<String> tailJavascripts = new java.util.ArrayList<String>();
protected java.util.List<String> stylesheets = new java.util.ArrayList<String>();
protected java.util.List<String> bodyAttributes = new java.util.ArrayList<String>();
protected java.util.Map<String,String> customHeadNoDuplicates = new java.util.HashMap<String,String>();
public void addJavascriptInclude(String filename) { commandingPage.addJavascriptIncludeInternal( filename ); }
public void addJavascriptIncludeInternal(String filename) {
if(!javascripts.contains(filename))
javascripts.add(filename);
}
public void addJavascriptTailInclude(String filename) { commandingPage.addJavascriptTailIncludeInternal( filename ); }
public void addJavascriptTailIncludeInternal(String filename) {
if(!tailJavascripts.contains(filename))
tailJavascripts.add(filename);
}
public void addStylesheetInclude(String filename) { commandingPage.addStylesheetIncludeInternal( filename ); }
public void addStylesheetIncludeInternal(String filename) {
if(!stylesheets.contains(filename)){
stylesheets.add(filename);
}
}
public void addStylesheetInclude(String filename, String media) { commandingPage.addStylesheetIncludeInternal( filename, media ); }
public void addStylesheetIncludeInternal(String filename, String media) {
String combined = media != null && !media.isEmpty() ? filename + "\" media=\""+ media : filename;
if(!stylesheets.contains(combined)){
stylesheets.add(combined);
}
}
public void addCustomHead(String header) { commandingPage.addCustomHeadInternal(header, header); }
public void addCustomHead(String key, String header) { commandingPage.addCustomHeadInternal(key, header); }
public void addCustomHeadInternal(String key, String header) {
customHeadNoDuplicates.put(key, header);
}
public void addBodyAttribute(String key, String value) { commandingPage.addBodyAttributeInternal(key, value); }
public void addBodyAttributeInternal(String key, String value) {
bodyAttributes.add(" "+key+"=\""+value+"\"");
}
protected abstract void initialize();
protected abstract void conversion();
protected abstract void loadArguments();
public abstract void initVarsAndArgs();
public void clearHibernateCache() {
// used to be only ' hibSession.clear(); ' but that doesn't revert already flushed changes.
// since flushing now happens automatically when querying, this could produce wrong results.
// e.g. output in page with validation errors shows changes that were not persisted to the db.
// see regression test in test/succeed-web/validate-false-and-flush.app
utils.HibernateUtil.getCurrentSession().getTransaction().rollback();
/* http://community.jboss.org/wiki/sessionsandtransactions
* Because Hibernate can't bind the "current session" to a transaction, as it does in a JTA environment,
* it binds it to the current Java thread. It is opened when getCurrentSession() is called for the first
* time, but in a "proxied" state that doesn't allow you to do anything except start a transaction. When
* the transaction ends, either through commit or roll back, the "current" Session is closed automatically.
* The next call to getCurrentSession() starts a new proxied Session, and so on. In other words,
* the session is bound to the thread behind the scenes, but scoped to a transaction, just like in a JTA environment.
*/
openNewTransactionThroughGetCurrentSession();
ThreadLocalServlet.get().reloadSessionManager(hibernateSession);
initVarsAndArgs();
hibernateCacheCleared = true;
}
protected org.hibernate.Session openNewTransactionThroughGetCurrentSession(){
hibernateSession = utils.HibernateUtil.getCurrentSession();
hibernateSession.beginTransaction();
return hibernateSession;
}
protected HttpServletRequest request;
protected ResponseWrapper response;
protected HttpServletResponse httpServletResponse;
protected Object[] args;
// public void setHibSession(Session s) {
// hibSession = s;
// }
//
// public Session getHibSession() {
// return hibSession;
// }
public HttpServletRequest getRequest() {
return request;
}
private String requestURLCached = null;
private String requestURICached = null;
public String getRequestURL(){
if(requestURLCached == null) {
requestURLCached = AbstractDispatchServletHelper.get().getRequestURL();
}
return requestURLCached;
}
public String getRequestURI(){
if(requestURICached == null) {
requestURICached = AbstractDispatchServletHelper.get().getRequestURI();
}
return requestURICached;
}
public ResponseWrapper getResponse() {
return response;
}
public void addResponseHeader(String key, String value) {
if( response != null ) {
response.setHeader(key, value);
}
}
protected boolean validated=true;
/*
* when this is true, it can mean:
* 1 no validation has been performed yet
* 2 some validation has been performed without errors
* 3 all validation has been performed without errors
*/
public boolean isValid() {
return validated;
}
public boolean isNotValid() {
return !validated;
}
public void setValidated(boolean validated) {
this.validated = validated;
}
/*
* complete action regularly but rollback hibernate session
* skips validation of entities at end of action, if validation messages are necessary
* use cancel() instead of rollback()
* can be used to replace templates with ajax without saving, e.g. for validation
*/
protected boolean rollback = false;
protected boolean validateFailedBeforeRollback = false;
public boolean isRollback() {
return rollback;
}
public void setRollback() {
validateFailedBeforeRollback = this.isNotValid();
//by setting validated true, the action will succeed
this.setValidated(true);
//the session will be rolled back, to cancel persisting any changes
this.rollback = true;
}
public List<String> failedCaptchaResponses = new ArrayList<String>();
protected boolean inSubmittedForm = false;
public boolean inSubmittedForm() {
return inSubmittedForm;
}
public void setInSubmittedForm(boolean b) {
this.inSubmittedForm = b;
}
// used for runtime check to detect nested forms
protected String inForm = null;
public boolean isInForm() {
return inForm != null;
}
public void enterForm(String t) {
inForm = t;
}
public String getEnclosingForm() {
return inForm;
}
public void leaveForm() {
inForm = null;
}
public void clearParammaps(){
parammap.clear();
parammapvalues.clear();
fileUploads.clear();
}
protected java.util.Map<String, String> parammap;
public java.util.Map<String, String> getParammap() {
return parammap;
}
protected Map<String,List<utils.File>> fileUploads;
public Map<String, List<utils.File>> getFileUploads() {
return fileUploads;
}
public List<utils.File> getFileUploads(String key) {
return fileUploads.get(key);
}
protected Map<String, List<String>> parammapvalues;
public Map<String, List<String>> getParammapvalues() {
return parammapvalues;
}
protected String pageTitle = "";
public String getPageTitle() {
return pageTitle;
}
public void setPageTitle(String pageTitle) {
this.pageTitle = pageTitle;
}
protected String formIdent = "";
public String getFormIdent() {
return formIdent;
}
public void setFormIdent(String fi) {
this.formIdent = fi;
}
protected boolean actionLinkUsed = false;
public boolean isActionLinkUsed() {
return actionLinkUsed;
}
public void setActionLinkUsed(boolean a) {
this.actionLinkUsed = a;
}
protected boolean ajaxRuntimeRequest = false;
public boolean isAjaxRuntimeRequest() {
return ajaxRuntimeRequest;
}
public void setAjaxRuntimeRequest(boolean a) {
ajaxRuntimeRequest = a;
}
protected String redirectUrl = "";
public boolean isRedirected(){
return !"".equals(redirectUrl);
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String a) {
this.redirectUrl = a;
}
// perform the actual redirect
public void redirect(){
try { response.sendRedirect(this.getRedirectUrl()); }
catch (IOException ioe) { org.webdsl.logging.Logger.error("redirect failed", ioe); }
}
protected String mimetype = "text/html; charset=UTF-8";
protected boolean mimetypeChanged = false;
public String getMimetype() {
return mimetype;
}
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
mimetypeChanged = true;
if(!isMarkupLangMimeType.matcher(mimetype).find()){
enableRawoutput();
}
disableTemplateSpans();
}
protected boolean downloadInline = false;
public boolean getDownloadInline() {
return downloadInline;
}
public void enableDownloadInline() {
this.downloadInline = true;
}
protected boolean ajaxActionExecuted = false;
public boolean isAjaxActionExecuted() {
return ajaxActionExecuted;
}
public void enableAjaxActionExecuted() {
ajaxActionExecuted = true;
}
protected boolean rawoutput = false;
public boolean isRawoutput() {
return rawoutput;
}
public void enableRawoutput() {
rawoutput = true;
}
public void disableRawoutput() {
rawoutput = false;
}
protected String[] pageArguments = null;
public void setPageArguments(String[] pa) {
pageArguments = pa;
}
public String[] getPageArguments() {
return pageArguments;
}
protected String httpMethod = null;
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public String getHttpMethod() {
return httpMethod;
}
protected boolean templateSpans = true;
public boolean templateSpans() {
return templateSpans;
}
public void disableTemplateSpans() {
templateSpans = false;
}
protected List<String> reRenderPlaceholders = null;
protected Map<String,String> reRenderPlaceholdersContent = null;
public boolean isReRenderPlaceholders() {
return reRenderPlaceholders != null;
}
public void addReRenderPlaceholders(String placeholder) {
if(reRenderPlaceholders == null){
reRenderPlaceholders = new ArrayList<String>();
reRenderPlaceholdersContent = new HashMap<String,String>();
}
reRenderPlaceholders.add(placeholder);
}
public void addReRenderPlaceholdersContent(String placeholder, String content) {
if(reRenderPlaceholders != null && reRenderPlaceholders.contains(placeholder)){
reRenderPlaceholdersContent.put(placeholder,content);
}
}
protected utils.File download = null;
public void setDownload(utils.File file){
this.download = file;
}
public boolean isDownloadSet(){
return this.download != null;
}
protected void download()
{
/*
Long id = download.getId();
org.hibernate.Session hibSession = HibernateUtilConfigured.getSessionFactory().openSession();
hibSession.beginTransaction();
hibSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
utils.File download = (utils.File)hibSession.load(utils.File.class,id);
*/
try
{
javax.servlet.ServletOutputStream outstream;
outstream = response.getOutputStream();
java.sql.Blob blob = download.getContent();
java.io.InputStream in;
in = blob.getBinaryStream();
response.setContentType(download.getContentType());
if(!downloadInline) {
response.setHeader("Content-Disposition", "attachment; filename=\"" + download.getFileNameForDownload() + "\"");
}
java.io.BufferedOutputStream bufout = new java.io.BufferedOutputStream(outstream);
byte bytes[] = new byte[32768];
int index = in.read(bytes, 0, 32768);
while(index != -1)
{
bufout.write(bytes, 0, index);
index = in.read(bytes, 0, 32768);
}
bufout.flush();
}
catch(java.sql.SQLException ex)
{
org.webdsl.logging.Logger.error("exception in download serve", ex);
}
catch (IOException ex) {
if(ex.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
org.webdsl.logging.Logger.error( "ClientAbortException - " + ex.getMessage() );
} else {
org.webdsl.logging.Logger.error("exception in download serve",ex);
}
}
/*
hibSession.flush();
hibSession.getTransaction().commit();
*/
}
//data validation
public java.util.LinkedList<String> validationContext = new java.util.LinkedList<String>();
public String getValidationContext() {
//System.out.println("using" + validationContext.peek());
return validationContext.peek();
}
public void enterValidationContext(String ident) {
validationContext.add(ident);
//System.out.println("entering" + ident);
}
public void leaveValidationContext() {
/*String s = */ validationContext.removeLast();
//System.out.println("leaving" +s);
}
public boolean inValidationContext() {
return validationContext.size() != 0;
}
//form
public boolean formRequiresMultipartEnc = false;
//formGroup
public String formGroupLeftSize = "150";
//public java.util.Stack<utils.FormGroupContext> formGroupContexts = new java.util.Stack<utils.FormGroupContext>();
public utils.FormGroupContext getFormGroupContext() {
return (utils.FormGroupContext) tableContexts.peek();
}
public void enterFormGroupContext() {
tableContexts.push(new utils.FormGroupContext());
}
public void leaveFormGroupContext() {
tableContexts.pop();
}
public boolean inFormGroupContext() {
return !tableContexts.empty() && tableContexts.peek() instanceof utils.FormGroupContext;
}
public java.util.Stack<String> formGroupContextClosingTags = new java.util.Stack<String>();
public void formGroupContextsCheckEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInDoubleColumnContext()){ // ignore defaults when in scope of a double column
if(!temp.isInColumnContext()){ //don't nest left and right
temp.enterColumnContext();
if(temp.isInLeftContext()) {
out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">");
formGroupContextClosingTags.push("left");
temp.toRightContext();
}
else {
out.print("<div style=\"float: left;\">");
formGroupContextClosingTags.push("right");
temp.toLeftContext();
}
}
else{
formGroupContextClosingTags.push("none");
}
}
}
}
public void formGroupContextsCheckLeave(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInDoubleColumnContext()) {
String tags = formGroupContextClosingTags.pop();
if(tags.equals("left")){
//temp.toRightContext();
temp.leaveColumnContext();
out.print("</div>");
}
else if(tags.equals("right")){
//temp.toLeftContext();
temp.leaveColumnContext();
out.print("</div>");
}
}
}
}
public void formGroupContextsDisplayLeftEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInColumnContext()){
temp.enterColumnContext();
out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">");
formGroupContextClosingTags.push("left");
temp.toRightContext();
}
else{
formGroupContextClosingTags.push("none");
}
}
}
public void formGroupContextsDisplayRightEnter(PrintWriter out) {
if(inFormGroupContext()){
utils.FormGroupContext temp = getFormGroupContext();
if(!temp.isInColumnContext()){
temp.enterColumnContext();
out.print("<div style=\"float: left;\">");
formGroupContextClosingTags.push("right");
temp.toLeftContext();
}
else{
formGroupContextClosingTags.push("none");
}
}
}
//label
public String getLabelString() {
return getLabelStringForTemplateContext(ThreadLocalTemplate.get().getUniqueId());
}
public java.util.Stack<String> labelStrings = new java.util.Stack<String>();
public java.util.Set<String> usedPageElementIds = new java.util.HashSet<String>();
public static java.util.Random rand = new java.util.Random();
//avoid duplicate ids; if multiple inputs are in a label, only the first is connected to the label
public String getLabelStringOnce() {
String s = labelStrings.peek();
if(usedPageElementIds.contains(s)){
do{
s += rand.nextInt();
}
while(usedPageElementIds.contains(s));
}
usedPageElementIds.add(s);
return s;
}
public java.util.Map<String,String> usedPageElementIdsTemplateContext = new java.util.HashMap<String,String>();
//subsequent calls from the same defined template (e.g. in different phases) should produce the same id
public String getLabelStringForTemplateContext(String context) {
String labelid = usedPageElementIdsTemplateContext.get(context);
if(labelid == null){
labelid = getLabelStringOnce();
usedPageElementIdsTemplateContext.put(context, labelid);
}
return labelid;
}
public void enterLabelContext(String ident) {
labelStrings.push(ident);
}
public void leaveLabelContext() {
labelStrings.pop();
}
public boolean inLabelContext() {
return !labelStrings.empty();
}
//section
public int sectionDepth = 0;
public int getSectionDepth() {
return sectionDepth;
}
public void enterSectionContext() {
sectionDepth++;
}
public void leaveSectionContext() {
sectionDepth--;
}
public boolean inSectionContext() {
return sectionDepth > 0;
}
//table
public java.util.Stack<Object> tableContexts = new java.util.Stack<Object>();
public utils.TableContext getTableContext() {
return (utils.TableContext) tableContexts.peek();
}
public void enterTableContext() {
tableContexts.push(new utils.TableContext());
}
public void leaveTableContext() {
tableContexts.pop();
}
public boolean inTableContext() {
return !tableContexts.empty() && tableContexts.peek() instanceof utils.TableContext;
}
public java.util.Stack<String> tableContextClosingTags = new java.util.Stack<String>();
//separate row and column checks, used by label
public void rowContextsCheckEnter(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
if(!x_temp.isInRowContext()) {
out.print("<tr>");
x_temp.enterRowContext();
tableContextClosingTags.push("</tr>");
}
else{
tableContextClosingTags.push("");
}
}
}
public void rowContextsCheckLeave(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
String tags = tableContextClosingTags.pop();
if(tags.equals("</tr>")){
x_temp.leaveRowContext();
out.print(tags);
}
}
}
public void columnContextsCheckEnter(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
if(x_temp.isInRowContext() && !x_temp.isInColumnContext()) {
out.print("<td>");
x_temp.enterColumnContext();
tableContextClosingTags.push("</td>");
}
else{
tableContextClosingTags.push("");
}
}
}
public void columnContextsCheckLeave(PrintWriter out) {
if(inTableContext()){
utils.TableContext x_temp = getTableContext();
String tags = tableContextClosingTags.pop();
if(tags.equals("</td>")){
x_temp.leaveColumnContext();
out.print(tags);
}
}
}
//session manager
public void reloadSessionManagerFromExistingSessionId(UUID sessionId){
ThreadLocalServlet.get().reloadSessionManagerFromExistingSessionId(hibernateSession, sessionId);
initialize(); //reload session variables
}
//request vars
public HashMap<String, Object> requestScopedVariables = new HashMap<String, Object>();
public void initRequestVars(){
initRequestVars(null);
}
public abstract void initRequestVars(PrintWriter out);
protected long startTime = 0L;
public long getStartTime() {
return startTime;
}
public long getElapsedTime() {
return System.currentTimeMillis() - startTime;
}
public Object getRequestScopedVar(String key){
return commandingPage.requestScopedVariables.get(key);
}
public void addRequestScopedVar(String key, Object val){
if(val != null){
commandingPage.requestScopedVariables.put(key, val);
}
}
public void addRequestScopedVar(String key, WebDSLEntity val){
if(val != null){
val.setRequestVar();
commandingPage.requestScopedVariables.put(key, val);
}
}
// statistics to be shown in log
protected abstract void increaseStatReadOnly();
protected abstract void increaseStatReadOnlyFromCache();
protected abstract void increaseStatUpdate();
protected abstract void increaseStatActionFail();
protected abstract void increaseStatActionReadOnly();
protected abstract void increaseStatActionUpdate();
// register whether entity changes were made, see isChanged property of entities
protected boolean hasWrites = false;
public void setHasWrites(boolean b){
commandingPage.hasWrites = b;
}
protected void updatePageRequestStatistics(){
if(hasNotExecutedAction()){
if(!hasWrites || isRollback()){
if(pageCacheWasUsed){
increaseStatReadOnlyFromCache();
}
else{
increaseStatReadOnly();
}
}
else{
increaseStatUpdate();
}
}
else{
if(isNotValid()){
increaseStatActionFail();
}
else{
if(!hasWrites || isRollback()){
increaseStatActionReadOnly();
}
else{
increaseStatActionUpdate();
}
}
}
}
// Hibernate interceptor hooks (such as beforeTransactionCompletion) catch Throwable but then only log the error, e.g. when db transaction conflict occurs
// this causes the problem that a page might be rendered with data that was not actually committed
// workaround: store the exception in this variable and explicitly rethrow before sending page content to output stream
public Exception exceptionInHibernateInterceptor = null;
public static Environment loadTemplateMap(Class<?> clazz) {
return loadTemplateMap(clazz, null, staticEnv);
}
public static Environment loadTemplateMap(Class<?> clazz, String keyOverwrite, Environment env) {
reflectionLoadClassesHelper(clazz, "loadTemplateMap", new Object[] { keyOverwrite, env });
return env;
}
public static Object[] loadEmailAndTemplateMapArgs = new Object[] { staticEnv, emails };
public static void loadEmailAndTemplateMap(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadEmailAndTemplateMap", loadEmailAndTemplateMapArgs);
}
public static Object[] loadLiftedTemplateMapArgs = new Object[] { staticEnv };
public static void loadLiftedTemplateMap(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadLiftedTemplateMap", loadLiftedTemplateMapArgs);
}
public static Object[] loadRefArgClassesArgs = new Object[] { refargclasses };
public static void loadRefArgClasses(Class<?> clazz) {
reflectionLoadClassesHelper(clazz, "loadRefArgClasses", loadRefArgClassesArgs);
}
public static void reflectionLoadClassesHelper(Class<?> clazz, String method, Object[] args) {
for (java.lang.reflect.Method m : clazz.getMethods()) {
if (method.equals(m.getName())) { // will just skip if not defined, so the code generator does not need to generate empty methods
try {
m.invoke(null, args);
} catch (IllegalAccessException | IllegalArgumentException | java.lang.reflect.InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
}
}
| 68,876 | 0.639192 | 0.638045 | 1,780 | 37.694382 | 33.485867 | 224 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.821348 | false | false |
15
|
d2e2b7273e1aac8cfa608177f1c7f615b7938c01
| 36,971,078,502,214 |
7c19b891e5185a1ded983b96f0723b08c5314c44
|
/src/main/java/com/appkingdoms/dao/AppEngineKingDao.java
|
3f05f1ce9030942baa665d2ddd1681a7ff2d8d9b
|
[] |
no_license
|
waprin/testingstuff
|
https://github.com/waprin/testingstuff
|
db4c81ff23dcbbfdac604d4c757cf2bbf8272083
|
9a714a22a76c02d7eb9e29e2edc29fb5559c0399
|
refs/heads/master
| 2015-08-05T20:28:31.724000 | 2012-02-21T23:07:31 | 2012-02-21T23:07:31 | 3,508,772 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.appkingdoms.dao;
import com.appkingdoms.entity.King;
import com.appkingdoms.entity.Realm;
import com.appkingdoms.entity.User;
import com.appkingdoms.util.JpaHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.List;
@SuppressWarnings("unchecked")
@Repository
public class AppEngineKingDao implements KingDao {
private final JpaHelper jpaHelper;
@Autowired
public AppEngineKingDao(JpaHelper jpaHelper) {
this.jpaHelper = jpaHelper;
}
public King getKingById(final Long kingId) {
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<King>() {
public King run(EntityManager em) {
King king = em.find(King.class, kingId);
return king;
}
});
}
public King persistNewKing(final King king) {
return jpaHelper.inTransaction(new JpaHelper.JpaRunnable<King>() {
public King run(EntityManager em) {
//save the new user
em.persist(king);
return king;
}
});
}
public List<King> getKingsByRealm(final Long realmId) {
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<List<King>>() {
public List<King> run(EntityManager em) {
Query kingQuery = em.createQuery("SELECT FROM " + King.class.getName() + " s WHERE s.realmId = :realmId");
kingQuery.setParameter("realmId", realmId);
// todo refactor daos to take limit and offset in signature
kingQuery.setMaxResults(20);
kingQuery.setFirstResult(0);
return kingQuery.getResultList();
}
});
}
public List<King> getKingsByUser(final Long userId) {
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<List<King>>() {
public List<King> run(EntityManager em) {
Query kingQuery = em.createQuery("SELECT FROM " + King.class.getName() + " s where s.userId = :userId");
kingQuery.setParameter("userId", userId);
kingQuery.setMaxResults(10);
kingQuery.setFirstResult(0);
return kingQuery.getResultList();
}
});
}
public King updateKing(final King king) {
return jpaHelper.inTransaction(new JpaHelper.JpaRunnable<King>() {
public King run(EntityManager em) {
final King kingToModify = em.find(King.class, king.getId());
if (!king.getGoldNum().equals(kingToModify.getGoldNum())) {
kingToModify.setGoldNum(king.getGoldNum());
}
if (!king.getLandNum().equals(kingToModify.getLandNum())) {
kingToModify.setLandNum(king.getLandNum());
}
if (!king.getPopulation().equals(kingToModify.getPopulation())) {
kingToModify.setPopulation(king.getPopulation());
}
if (!king.getSoldierTypeToNumber().equals(kingToModify.getSoldierTypeToNumber())) {
kingToModify.setSoldierTypeToNumber(king.getSoldierTypeToNumber());
}
if (!king.getLastExploreTime().equals(kingToModify.getLastExploreTime())) {
kingToModify.setLastExploreTime(king.getLastExploreTime());
}
return kingToModify;
}
});
}
@Override
public King loadKingById(final long kingId)
{
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<King>() {
@Override
public King run(EntityManager em) {
return em.find(King.class, kingId);
}
});
}
public King decreaseGold(final King king, final Long goldValue) {
return jpaHelper.inTransaction(new JpaHelper.JpaRunnable<King>() {
@Override
public King run(EntityManager em) {
Long currentValue = king.getGoldNum();
Long newValue = currentValue - goldValue;
king.setGoldNum(newValue);
return king;
}
});
}
@Override
public King loadKingForUserByRealmId(final User user, final Long realmId) {
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<King>() {
@Override
public King run(EntityManager em) {
Query kingQuery = em.createQuery("SELECT FROM " + King.class.getName() + " s where s.userId = :userId AND s.realmId = :realmId");
kingQuery.setParameter("userId", user.getId());
kingQuery.setParameter("realmId", realmId);
try { // so hard
return (King) kingQuery.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
});
}
}
|
UTF-8
|
Java
| 5,136 |
java
|
AppEngineKingDao.java
|
Java
|
[] | null |
[] |
package com.appkingdoms.dao;
import com.appkingdoms.entity.King;
import com.appkingdoms.entity.Realm;
import com.appkingdoms.entity.User;
import com.appkingdoms.util.JpaHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.List;
@SuppressWarnings("unchecked")
@Repository
public class AppEngineKingDao implements KingDao {
private final JpaHelper jpaHelper;
@Autowired
public AppEngineKingDao(JpaHelper jpaHelper) {
this.jpaHelper = jpaHelper;
}
public King getKingById(final Long kingId) {
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<King>() {
public King run(EntityManager em) {
King king = em.find(King.class, kingId);
return king;
}
});
}
public King persistNewKing(final King king) {
return jpaHelper.inTransaction(new JpaHelper.JpaRunnable<King>() {
public King run(EntityManager em) {
//save the new user
em.persist(king);
return king;
}
});
}
public List<King> getKingsByRealm(final Long realmId) {
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<List<King>>() {
public List<King> run(EntityManager em) {
Query kingQuery = em.createQuery("SELECT FROM " + King.class.getName() + " s WHERE s.realmId = :realmId");
kingQuery.setParameter("realmId", realmId);
// todo refactor daos to take limit and offset in signature
kingQuery.setMaxResults(20);
kingQuery.setFirstResult(0);
return kingQuery.getResultList();
}
});
}
public List<King> getKingsByUser(final Long userId) {
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<List<King>>() {
public List<King> run(EntityManager em) {
Query kingQuery = em.createQuery("SELECT FROM " + King.class.getName() + " s where s.userId = :userId");
kingQuery.setParameter("userId", userId);
kingQuery.setMaxResults(10);
kingQuery.setFirstResult(0);
return kingQuery.getResultList();
}
});
}
public King updateKing(final King king) {
return jpaHelper.inTransaction(new JpaHelper.JpaRunnable<King>() {
public King run(EntityManager em) {
final King kingToModify = em.find(King.class, king.getId());
if (!king.getGoldNum().equals(kingToModify.getGoldNum())) {
kingToModify.setGoldNum(king.getGoldNum());
}
if (!king.getLandNum().equals(kingToModify.getLandNum())) {
kingToModify.setLandNum(king.getLandNum());
}
if (!king.getPopulation().equals(kingToModify.getPopulation())) {
kingToModify.setPopulation(king.getPopulation());
}
if (!king.getSoldierTypeToNumber().equals(kingToModify.getSoldierTypeToNumber())) {
kingToModify.setSoldierTypeToNumber(king.getSoldierTypeToNumber());
}
if (!king.getLastExploreTime().equals(kingToModify.getLastExploreTime())) {
kingToModify.setLastExploreTime(king.getLastExploreTime());
}
return kingToModify;
}
});
}
@Override
public King loadKingById(final long kingId)
{
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<King>() {
@Override
public King run(EntityManager em) {
return em.find(King.class, kingId);
}
});
}
public King decreaseGold(final King king, final Long goldValue) {
return jpaHelper.inTransaction(new JpaHelper.JpaRunnable<King>() {
@Override
public King run(EntityManager em) {
Long currentValue = king.getGoldNum();
Long newValue = currentValue - goldValue;
king.setGoldNum(newValue);
return king;
}
});
}
@Override
public King loadKingForUserByRealmId(final User user, final Long realmId) {
return jpaHelper.withoutTransaction(new JpaHelper.JpaRunnable<King>() {
@Override
public King run(EntityManager em) {
Query kingQuery = em.createQuery("SELECT FROM " + King.class.getName() + " s where s.userId = :userId AND s.realmId = :realmId");
kingQuery.setParameter("userId", user.getId());
kingQuery.setParameter("realmId", realmId);
try { // so hard
return (King) kingQuery.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
});
}
}
| 5,136 | 0.592095 | 0.590927 | 134 | 37.335819 | 29.776016 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.455224 | false | false |
15
|
138c5abfbeed037deb21cbfba01ebb1a3cc27080
| 23,330,262,404,212 |
c74c2e590b6c6f967aff980ce465713b9e6fb7ef
|
/game-logic/src/main/java/com/bdoemu/core/network/sendable/SMLoginUserToFieldServer.java
|
2e7b25dcbdda03b7d632f2107b4cc4f398c47db0
|
[] |
no_license
|
lingfan/bdoemu
|
https://github.com/lingfan/bdoemu
|
812bb0abb219ddfc391adadf68079efa4af43353
|
9c49b29bfc9c5bfe3192b2a7fb1245ed459ef6c1
|
refs/heads/master
| 2021-01-01T13:10:13.075000 | 2019-12-02T09:23:20 | 2019-12-02T09:23:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bdoemu.core.network.sendable;
import com.bdoemu.commons.network.SendByteBuffer;
import com.bdoemu.commons.rmi.model.LoginAccountInfo;
import com.bdoemu.core.configs.NetworkConfig;
import com.bdoemu.core.network.GameClient;
import com.bdoemu.core.network.sendable.utils.WriteCharacterInfo;
import com.bdoemu.gameserver.dataholders.DyeingItemData;
import com.bdoemu.gameserver.dataholders.ItemData;
import com.bdoemu.gameserver.dataholders.PCSetData;
import com.bdoemu.gameserver.model.creature.player.templates.PCSetTemplate;
import com.bdoemu.gameserver.model.items.templates.DyeingItemT;
import com.bdoemu.gameserver.model.items.templates.ItemTemplate;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import java.util.Collection;
import java.util.TreeMap;
public class SMLoginUserToFieldServer extends WriteCharacterInfo {
private final GameClient client;
private final LoginAccountInfo loginAccountInfo;
private final Collection<BasicDBObject> players;
private final int characterSlots;
private final int packetNr;
private final int characterSize;
public SMLoginUserToFieldServer(final GameClient client, final LoginAccountInfo loginAccountInfo, final Collection<BasicDBObject> players, final int packetNr) {
if (NetworkConfig.ENCRYPT_PACKETS) {
this.setEncrypt(true);
}
this.characterSize = loginAccountInfo.getPlayers().size();
this.client = client;
this.loginAccountInfo = loginAccountInfo;
this.players = players;
this.characterSlots = loginAccountInfo.getCharacterSlots();
this.packetNr = packetNr;
}
protected void writeBody(final SendByteBuffer buffer) {
buffer.writeD(this.packetNr);
buffer.writeD(NetworkConfig.SERVER_VERSION);
buffer.writeD(this.client.getObjectId());
buffer.writeD(0);
buffer.writeQ(this.loginAccountInfo.getAccountId());
buffer.writeS(this.loginAccountInfo.getFamily(), 62);
buffer.writeH(-1);
buffer.writeH(this.characterSlots);
buffer.writeC(this.characterSize);
buffer.writeC(0);
buffer.writeQ(-1L);
buffer.writeQ(0L);
buffer.writeC(this.players.size());
for (final BasicDBObject player : this.players) {
final BasicDBObject location = (BasicDBObject) player.get("location");
final BasicDBObject equipment = (BasicDBObject) ((BasicDBObject) player.get("playerBag")).get("Equipments");
final String name = player.getString("name");
final PCSetTemplate pcSetTemplate = PCSetData.getInstance().getTemplate(player.getInt("classType"));
buffer.writeH(pcSetTemplate.getCharacterKey());
buffer.writeQ(player.getLong("_id"));
buffer.writeC(player.getInt("slot"));
buffer.writeS(name, 62);
buffer.writeD(player.getInt("level"));
buffer.writeD(player.getInt("equipSlotCacheCount"));
final BasicDBList itemsDB = (BasicDBList) equipment.get("items");
final TreeMap<Integer, BasicDBObject> equipmentMap = new TreeMap<Integer, BasicDBObject>();
for (final Object anItemsDB : itemsDB) {
final BasicDBObject itemDB = (BasicDBObject) anItemsDB;
equipmentMap.put(itemDB.getInt("index"), itemDB);
}
for (int index = 0; index < 31; ++index) {
final BasicDBObject item = equipmentMap.get(index);
if (item != null) {
final int itemId = item.getInt("itemId");
final ItemTemplate template = ItemData.getInstance().getItemTemplate(itemId);
buffer.writeH(itemId);
buffer.writeH(item.getInt("enchantLevel"));
buffer.writeQ((long) item.getInt("expirationPeriod"));
buffer.writeH((template.getEndurance() > 0) ? item.getInt("endurance") : 32767);
final BasicDBList palettesDB = (BasicDBList) item.get("colorPalettes");
final TreeMap<Integer, DyeingItemT> colorPalettes = new TreeMap<Integer, DyeingItemT>();
for (final Object aPalettesDB : palettesDB) {
final BasicDBObject obj = (BasicDBObject) aPalettesDB;
colorPalettes.put(obj.getInt("index"), DyeingItemData.getInstance().getTemplate(obj.getInt("itemId")));
}
for (int paletteIndex = 0; paletteIndex < 12; ++paletteIndex) {
final DyeingItemT dyeingItemT = colorPalettes.get(paletteIndex);
if (dyeingItemT != null) {
buffer.writeC(dyeingItemT.getPaletteType());
buffer.writeC(dyeingItemT.getPaletteIndex());
} else {
buffer.writeC(-1);
buffer.writeC(-1);
}
}
buffer.writeC(item.getInt("colorPaletteType", 0));
} else {
buffer.writeH(0);
buffer.writeH(0);
buffer.writeQ(-1L);
buffer.writeH(-2);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeC(0);
}
}
final BasicDBObject playerAppearance = (BasicDBObject) player.get("appearance");
final BasicDBObject face = (BasicDBObject) playerAppearance.get("face");
final BasicDBObject hairs = (BasicDBObject) playerAppearance.get("hairs");
final BasicDBObject beard = (BasicDBObject) face.get("beard");
final BasicDBObject mustache = (BasicDBObject) face.get("mustache");
final BasicDBObject whiskers = (BasicDBObject) face.get("whiskers");
final BasicDBObject eyebrows = (BasicDBObject) face.get("eyebrows");
buffer.writeC(face.getInt("_id"));
buffer.writeC(hairs.getInt("_id"));
buffer.writeC(beard.getInt("_id"));
buffer.writeC(mustache.getInt("_id"));
buffer.writeC(whiskers.getInt("_id"));
buffer.writeC(eyebrows.getInt("_id"));
buffer.writeD(player.getInt("basicCacheCount"));
buffer.writeC(player.getInt("zodiac"));
this.writeAppearanceData(buffer, player, this.loginAccountInfo.getFamily());
buffer.writeQ(player.getLong("deletionDate"));
buffer.writeC(0);
buffer.writeQ(player.getLong("lastLogin") / 1000L);
buffer.writeQ(player.getLong("creationDate") / 1000L);
buffer.writeF(location.getDouble("x"));
buffer.writeF(location.getDouble("z"));
buffer.writeF(location.getDouble("y"));
buffer.writeQ(player.getLong("blockDate"));
buffer.writeH(0);
buffer.writeQ(player.getLong("lastLogin") / 1000L);
buffer.writeB(new byte[58]);
buffer.writeC(0);
}
}
}
|
UTF-8
|
Java
| 7,502 |
java
|
SMLoginUserToFieldServer.java
|
Java
|
[] | null |
[] |
package com.bdoemu.core.network.sendable;
import com.bdoemu.commons.network.SendByteBuffer;
import com.bdoemu.commons.rmi.model.LoginAccountInfo;
import com.bdoemu.core.configs.NetworkConfig;
import com.bdoemu.core.network.GameClient;
import com.bdoemu.core.network.sendable.utils.WriteCharacterInfo;
import com.bdoemu.gameserver.dataholders.DyeingItemData;
import com.bdoemu.gameserver.dataholders.ItemData;
import com.bdoemu.gameserver.dataholders.PCSetData;
import com.bdoemu.gameserver.model.creature.player.templates.PCSetTemplate;
import com.bdoemu.gameserver.model.items.templates.DyeingItemT;
import com.bdoemu.gameserver.model.items.templates.ItemTemplate;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import java.util.Collection;
import java.util.TreeMap;
public class SMLoginUserToFieldServer extends WriteCharacterInfo {
private final GameClient client;
private final LoginAccountInfo loginAccountInfo;
private final Collection<BasicDBObject> players;
private final int characterSlots;
private final int packetNr;
private final int characterSize;
public SMLoginUserToFieldServer(final GameClient client, final LoginAccountInfo loginAccountInfo, final Collection<BasicDBObject> players, final int packetNr) {
if (NetworkConfig.ENCRYPT_PACKETS) {
this.setEncrypt(true);
}
this.characterSize = loginAccountInfo.getPlayers().size();
this.client = client;
this.loginAccountInfo = loginAccountInfo;
this.players = players;
this.characterSlots = loginAccountInfo.getCharacterSlots();
this.packetNr = packetNr;
}
protected void writeBody(final SendByteBuffer buffer) {
buffer.writeD(this.packetNr);
buffer.writeD(NetworkConfig.SERVER_VERSION);
buffer.writeD(this.client.getObjectId());
buffer.writeD(0);
buffer.writeQ(this.loginAccountInfo.getAccountId());
buffer.writeS(this.loginAccountInfo.getFamily(), 62);
buffer.writeH(-1);
buffer.writeH(this.characterSlots);
buffer.writeC(this.characterSize);
buffer.writeC(0);
buffer.writeQ(-1L);
buffer.writeQ(0L);
buffer.writeC(this.players.size());
for (final BasicDBObject player : this.players) {
final BasicDBObject location = (BasicDBObject) player.get("location");
final BasicDBObject equipment = (BasicDBObject) ((BasicDBObject) player.get("playerBag")).get("Equipments");
final String name = player.getString("name");
final PCSetTemplate pcSetTemplate = PCSetData.getInstance().getTemplate(player.getInt("classType"));
buffer.writeH(pcSetTemplate.getCharacterKey());
buffer.writeQ(player.getLong("_id"));
buffer.writeC(player.getInt("slot"));
buffer.writeS(name, 62);
buffer.writeD(player.getInt("level"));
buffer.writeD(player.getInt("equipSlotCacheCount"));
final BasicDBList itemsDB = (BasicDBList) equipment.get("items");
final TreeMap<Integer, BasicDBObject> equipmentMap = new TreeMap<Integer, BasicDBObject>();
for (final Object anItemsDB : itemsDB) {
final BasicDBObject itemDB = (BasicDBObject) anItemsDB;
equipmentMap.put(itemDB.getInt("index"), itemDB);
}
for (int index = 0; index < 31; ++index) {
final BasicDBObject item = equipmentMap.get(index);
if (item != null) {
final int itemId = item.getInt("itemId");
final ItemTemplate template = ItemData.getInstance().getItemTemplate(itemId);
buffer.writeH(itemId);
buffer.writeH(item.getInt("enchantLevel"));
buffer.writeQ((long) item.getInt("expirationPeriod"));
buffer.writeH((template.getEndurance() > 0) ? item.getInt("endurance") : 32767);
final BasicDBList palettesDB = (BasicDBList) item.get("colorPalettes");
final TreeMap<Integer, DyeingItemT> colorPalettes = new TreeMap<Integer, DyeingItemT>();
for (final Object aPalettesDB : palettesDB) {
final BasicDBObject obj = (BasicDBObject) aPalettesDB;
colorPalettes.put(obj.getInt("index"), DyeingItemData.getInstance().getTemplate(obj.getInt("itemId")));
}
for (int paletteIndex = 0; paletteIndex < 12; ++paletteIndex) {
final DyeingItemT dyeingItemT = colorPalettes.get(paletteIndex);
if (dyeingItemT != null) {
buffer.writeC(dyeingItemT.getPaletteType());
buffer.writeC(dyeingItemT.getPaletteIndex());
} else {
buffer.writeC(-1);
buffer.writeC(-1);
}
}
buffer.writeC(item.getInt("colorPaletteType", 0));
} else {
buffer.writeH(0);
buffer.writeH(0);
buffer.writeQ(-1L);
buffer.writeH(-2);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeH(-1);
buffer.writeC(0);
}
}
final BasicDBObject playerAppearance = (BasicDBObject) player.get("appearance");
final BasicDBObject face = (BasicDBObject) playerAppearance.get("face");
final BasicDBObject hairs = (BasicDBObject) playerAppearance.get("hairs");
final BasicDBObject beard = (BasicDBObject) face.get("beard");
final BasicDBObject mustache = (BasicDBObject) face.get("mustache");
final BasicDBObject whiskers = (BasicDBObject) face.get("whiskers");
final BasicDBObject eyebrows = (BasicDBObject) face.get("eyebrows");
buffer.writeC(face.getInt("_id"));
buffer.writeC(hairs.getInt("_id"));
buffer.writeC(beard.getInt("_id"));
buffer.writeC(mustache.getInt("_id"));
buffer.writeC(whiskers.getInt("_id"));
buffer.writeC(eyebrows.getInt("_id"));
buffer.writeD(player.getInt("basicCacheCount"));
buffer.writeC(player.getInt("zodiac"));
this.writeAppearanceData(buffer, player, this.loginAccountInfo.getFamily());
buffer.writeQ(player.getLong("deletionDate"));
buffer.writeC(0);
buffer.writeQ(player.getLong("lastLogin") / 1000L);
buffer.writeQ(player.getLong("creationDate") / 1000L);
buffer.writeF(location.getDouble("x"));
buffer.writeF(location.getDouble("z"));
buffer.writeF(location.getDouble("y"));
buffer.writeQ(player.getLong("blockDate"));
buffer.writeH(0);
buffer.writeQ(player.getLong("lastLogin") / 1000L);
buffer.writeB(new byte[58]);
buffer.writeC(0);
}
}
}
| 7,502 | 0.603306 | 0.595574 | 147 | 50.034012 | 26.428806 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.92517 | false | false |
15
|
419cbbca6440507052e187bfbfe2773297f36e6f
| 34,016,141,032,692 |
ba5a7e1bfb4b1a5c5b91dcd525d67365c667c9c3
|
/src/main/java/com/microservice/assignment/starbux/exception/StarbuxException.java
|
aaf4501663336b48df2a3f8149d9ecfa64d8ebc1
|
[
"Unlicense"
] |
permissive
|
yeganehparast/microservices
|
https://github.com/yeganehparast/microservices
|
e21d46383278cc417588e05f741b56e15998700f
|
63a7882e3698e620dac64186013820bfec028b88
|
refs/heads/main
| 2023-01-15T11:53:21.546000 | 2020-11-23T18:43:39 | 2020-11-23T18:43:39 | 315,145,173 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.microservice.assignment.starbux.exception;
/**
* General Exception class for Starbux application
*/
public class StarbuxException extends RuntimeException {
public StarbuxException(String message) {
super(message);
}
}
|
UTF-8
|
Java
| 253 |
java
|
StarbuxException.java
|
Java
|
[] | null |
[] |
package com.microservice.assignment.starbux.exception;
/**
* General Exception class for Starbux application
*/
public class StarbuxException extends RuntimeException {
public StarbuxException(String message) {
super(message);
}
}
| 253 | 0.73913 | 0.73913 | 11 | 21.818182 | 23.186274 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false |
15
|
0161e02e6f220e933e3afd320d439f11169f8a56
| 35,691,178,263,304 |
7bd0699b4170e7a6c33930bd5275171a1a31d3ab
|
/src/main/java/gui/form/base/InputBoxState.java
|
7c690068cc7ffea5a58820fb1144d0ef7fbe34fd
|
[] |
no_license
|
MidasLamb/Classr
|
https://github.com/MidasLamb/Classr
|
3e857a6423662025754fe10e69cc5310c3f20540
|
c26887cdaa5df3b882ee40d8a223d84eb57f9aea
|
refs/heads/master
| 2021-03-19T14:50:15.072000 | 2017-05-25T15:57:18 | 2017-05-25T15:57:18 | 82,708,493 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package gui.form.base;
import gui.inputHandlers.Typable;
import gui.inputHandlers.clicks.MouseClick;
/**
* Indicates the state of an InputBox.
*/
public abstract class InputBoxState extends State implements Typable {
/**
* Actions executed when clicked on this InputBox
*
* @param click
* MouseClick containing details of the click
*/
abstract void onClick(MouseClick click);
}
|
UTF-8
|
Java
| 425 |
java
|
InputBoxState.java
|
Java
|
[] | null |
[] |
package gui.form.base;
import gui.inputHandlers.Typable;
import gui.inputHandlers.clicks.MouseClick;
/**
* Indicates the state of an InputBox.
*/
public abstract class InputBoxState extends State implements Typable {
/**
* Actions executed when clicked on this InputBox
*
* @param click
* MouseClick containing details of the click
*/
abstract void onClick(MouseClick click);
}
| 425 | 0.696471 | 0.696471 | 18 | 21.611111 | 22.499725 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false |
15
|
94700ade55a585d1fdfbfb564f3eb30f6df84c32
| 35,270,271,474,510 |
99953f96dad85f3c9363599825940db69e184603
|
/src/main/java/hu/i42/simondavid/betterhardcore/items/ItemCampfire.java
|
ddf6822eb3e4b074c65a5cab344031e057e8f3eb
|
[] |
no_license
|
david-simon/BetterHardcore
|
https://github.com/david-simon/BetterHardcore
|
108c235ba5829bb2219b6f4994ddc2ac6579056e
|
f527d4f2d017b68dce6ec53414d951d8e2d33568
|
refs/heads/master
| 2017-12-06T22:31:03.368000 | 2017-01-31T18:07:00 | 2017-01-31T18:07:00 | 79,812,945 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package hu.i42.simondavid.betterhardcore.items;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
public class ItemCampfire extends ItemBlock {
public ItemCampfire(Block block) {
super(block);
}
}
|
UTF-8
|
Java
| 236 |
java
|
ItemCampfire.java
|
Java
|
[] | null |
[] |
package hu.i42.simondavid.betterhardcore.items;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
public class ItemCampfire extends ItemBlock {
public ItemCampfire(Block block) {
super(block);
}
}
| 236 | 0.75 | 0.741525 | 10 | 22.6 | 18.499729 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
15
|
4b2fc26a7177b6e9343bdcea00f6fc78ff58196f
| 34,144,990,049,117 |
2673b3095da8a043d9819d5931cf2e166c1616bf
|
/chapter7/src/main/java/com/packtpub/infinispan/chapter7/InterceptorProgrammaticConfiguration.java
|
0439c06c1ade0660e1841064f954d47fc75bfa86
|
[
"CC-BY-3.0"
] |
permissive
|
fmarchioni/Infinispan-book
|
https://github.com/fmarchioni/Infinispan-book
|
caebcaf40ab8b3f13e5f8b100daecb6a69bd9700
|
8b91f6d7304988a0cfa5c57bd37c6aa67c781c20
|
refs/heads/master
| 2021-01-16T22:52:56.687000 | 2012-06-19T18:00:07 | 2012-06-19T18:00:07 | 3,155,041 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.packtpub.infinispan.chapter7;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.InterceptorConfiguration;
/**
* Code snippet to demonstrate programmatically configuring a custom interceptor.
*/
public class InterceptorProgrammaticConfiguration {
public void configureInterceptor() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors()
.addInterceptor()
.interceptor(new ReadOnlyInterceptor())
.position(InterceptorConfiguration.Position.FIRST);
Configuration c = builder.build();
}
}
|
UTF-8
|
Java
| 709 |
java
|
InterceptorProgrammaticConfiguration.java
|
Java
|
[] | null |
[] |
package com.packtpub.infinispan.chapter7;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.InterceptorConfiguration;
/**
* Code snippet to demonstrate programmatically configuring a custom interceptor.
*/
public class InterceptorProgrammaticConfiguration {
public void configureInterceptor() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.customInterceptors()
.addInterceptor()
.interceptor(new ReadOnlyInterceptor())
.position(InterceptorConfiguration.Position.FIRST);
Configuration c = builder.build();
}
}
| 709 | 0.765867 | 0.764457 | 19 | 36.315788 | 26.355968 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false |
15
|
6c612a8e1592b32732d25aee9cf39ef41148358e
| 14,834,817,047,006 |
6c72b9fe32468c6526fa6493e284a8dfedc25b6e
|
/leetcode/3sum-closest/java/SolutionDP.java
|
eea6217a6fb0ae43a6abd2da61c8fca7b624d6ef
|
[] |
no_license
|
xxiao23/xiao-puzzle
|
https://github.com/xxiao23/xiao-puzzle
|
dd44bd897960261388d30eb0232e52793ef42afb
|
623b3a5d9a7dfdc58c9aba6496bf63fab0bebadd
|
refs/heads/master
| 2016-09-06T11:48:14.381000 | 2014-03-17T17:17:40 | 2014-03-17T17:17:40 | 1,697,727 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class SolutionDP {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
// sort the numbers
Arrays.sort(num);
// shift every number to become non-negative
int shift = Math.abs(num[0]);
target += 4 * shift;
for (int i : num) {
num[i] += shift;
}
// we need 4 DP tables
// from 1-sum to 4-sum
int[][][] dpTables = new int[4][target+1][num.length];
// compute 1-sum tables, trivial
for (int s = 0; s < target+1; ++s) {
for (int n = 0; n < num.length; ++n) {
if (num[n] == s) {
dpTables[0][s][n] = 1;
} else {
dpTables[0][s][n] = 0;
}
}
}
// build up k-sum tables from bottom up
// T(S, n, k) = T(S-num[n], n-1, k-1) + T(S, n-1, k)
for (int k = 1; k < 4; ++k) {
for (int s = 0; s < target+1; ++s) {
for (int n = 0; n < num.length; ++n) {
int a, b;
if (s-num[n] < 0 || n-1 < 0) {
a = 0;
} else {
a = dpTables[k-1][s-num[n]][n-1];
}
if (n-1 < 0) {
b = 0;
} else {
b = dpTables[k][s][n-1];
}
dpTables[k][s][n] = a + b;
} // n
} // s
} // k
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
// now construct the solutions from 4-sum DP table
for (int n = 3; n < num.length; ++n) {
if (dpTables[4][target][n] > 0) {
LinkedList<Integer> suffix = new LinkedList<Integer>();
result.addAll(constructSolution(dpTables, num, target, n, 4, shift, suffix));
}
}
return result;
}
private ArrayList<ArrayList<Integer>> constructSolution(int[][][] dpTables, int[] num, int target, int end, int k, int shift, LinkedList<Integer> suffix) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (k >= 1) {
for (int n = 0; n <= end; ++n) {
if (dpTables[k-1][target][n] > 0) {
LinkedList<Integer> newSuffix = new LinkedList<Integer>(suffix);
newSuffix.addFirst(s-shift);
result.addAll(constructSolution(dpTables, num, target-num[n], n-1, k-1, shift, newSuffix));
}
}
}
return result;
}
}
|
UTF-8
|
Java
| 2,055 |
java
|
SolutionDP.java
|
Java
|
[] | null |
[] |
public class SolutionDP {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
// sort the numbers
Arrays.sort(num);
// shift every number to become non-negative
int shift = Math.abs(num[0]);
target += 4 * shift;
for (int i : num) {
num[i] += shift;
}
// we need 4 DP tables
// from 1-sum to 4-sum
int[][][] dpTables = new int[4][target+1][num.length];
// compute 1-sum tables, trivial
for (int s = 0; s < target+1; ++s) {
for (int n = 0; n < num.length; ++n) {
if (num[n] == s) {
dpTables[0][s][n] = 1;
} else {
dpTables[0][s][n] = 0;
}
}
}
// build up k-sum tables from bottom up
// T(S, n, k) = T(S-num[n], n-1, k-1) + T(S, n-1, k)
for (int k = 1; k < 4; ++k) {
for (int s = 0; s < target+1; ++s) {
for (int n = 0; n < num.length; ++n) {
int a, b;
if (s-num[n] < 0 || n-1 < 0) {
a = 0;
} else {
a = dpTables[k-1][s-num[n]][n-1];
}
if (n-1 < 0) {
b = 0;
} else {
b = dpTables[k][s][n-1];
}
dpTables[k][s][n] = a + b;
} // n
} // s
} // k
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
// now construct the solutions from 4-sum DP table
for (int n = 3; n < num.length; ++n) {
if (dpTables[4][target][n] > 0) {
LinkedList<Integer> suffix = new LinkedList<Integer>();
result.addAll(constructSolution(dpTables, num, target, n, 4, shift, suffix));
}
}
return result;
}
private ArrayList<ArrayList<Integer>> constructSolution(int[][][] dpTables, int[] num, int target, int end, int k, int shift, LinkedList<Integer> suffix) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (k >= 1) {
for (int n = 0; n <= end; ++n) {
if (dpTables[k-1][target][n] > 0) {
LinkedList<Integer> newSuffix = new LinkedList<Integer>(suffix);
newSuffix.addFirst(s-shift);
result.addAll(constructSolution(dpTables, num, target-num[n], n-1, k-1, shift, newSuffix));
}
}
}
return result;
}
}
| 2,055 | 0.552798 | 0.531387 | 75 | 26.413334 | 26.981028 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.653333 | false | false |
15
|
91ca2b58f059c2ecab162d504bba4e353855aead
| 26,534,307,958,662 |
d64a9a7c06801eabed66d1b63e75a15d2b950505
|
/Mythruna-client/src/main/java/mythruna/client/Avatar.java
|
c8f4b40f914f0496c4d28b4d799bf2d6692f8575
|
[] |
no_license
|
VGAngel/tribrow
|
https://github.com/VGAngel/tribrow
|
c7d9db9d860dbedddfc57f945ef82c26cba75586
|
c80c4739d7af208a82cb61a120f361ce16cca99a
|
refs/heads/master
| 2020-06-05T08:26:19.616000 | 2015-03-24T20:12:08 | 2015-03-24T20:12:10 | 22,870,463 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package mythruna.client;
import com.jme3.animation.Bone;
import com.jme3.animation.Skeleton;
import com.jme3.animation.SkeletonControl;
import com.jme3.asset.AssetManager;
import com.jme3.collision.Collidable;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.font.Rectangle;
import com.jme3.material.MatParamTexture;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.BillboardControl;
import com.jme3.scene.control.Control;
import com.jme3.texture.Texture;
import mythruna.MaterialIndex;
import mythruna.es.EntityId;
import java.util.ArrayList;
import java.util.List;
public class Avatar extends Node {
public static final String DEFAULT_NAME = "Loading...";
public static final String TYPE = "Avatar";
private Spatial model;
private String name;
private float headHeight = 1.7F;
private BitmapFont font;
private BitmapText label;
private Node textNode;
private Quaternion facing;
private Node headNode;
private Node hairNode;
private SkeletonControl skeletonControl;
private List<Material> materials = new ArrayList();
public Avatar(AssetManager assets, String name) {
super("FemaleAvatar");
String tempName = name == null ? "Loading..." : name;
float scale = 0.2700617F;
this.model = assets.loadModel("Models/female-parts.j3o");
setupMaterial(this.model, assets);
if ((this.model instanceof Node))
fixBucket((Node) this.model);
this.model.setQueueBucket(RenderQueue.Bucket.Opaque);
this.model.setUserData("type", "Avatar");
attachChild(this.model);
this.model.setLocalTranslation(0.0F, -(this.headHeight / scale), 0.0F);
setLocalScale(scale, scale, scale);
this.font = assets.loadFont("Interface/knights24-outline.fnt");
this.textNode = new Node("LabelNode");
this.textNode.setLocalScale(0.7F, 0.7F, 0.7F);
updateText(tempName);
this.textNode.setLocalTranslation(0.0F, this.label.getHeight(), 0.0F);
attachChild(this.textNode);
System.out.println("Found skeleton:" + getSkeleton());
}
public int collideWith(Collidable other, CollisionResults results) {
return super.collideWith(other, results);
}
protected void showControls(Spatial s) {
System.out.println("show controls:" + s);
int count = s.getNumControls();
for (int i = 0; i < count; i++) {
Control c = s.getControl(i);
System.out.println(" c[" + i + "] = " + c);
}
if ((s instanceof Node)) {
for (Spatial child : ((Node) s).getChildren())
showControls(child);
}
}
protected void attachHead(Node n) {
this.headNode = n;
}
protected void attachHair(Node n) {
this.hairNode = n;
}
protected void setupMaterial(Spatial s, AssetManager assets) {
if ((s instanceof Geometry))
setupMaterial((Geometry) s, assets);
else
setupMaterial((Node) s, assets);
}
protected void setupMaterial(Node n, AssetManager assets) {
System.out.println("Node:" + n);
if ("head".equals(n.getName()))
attachHead(n);
else if ("hair".equals(n.getName())) {
attachHair(n);
}
for (Spatial s : n.getChildren())
setupMaterial(s, assets);
}
protected void setupMaterial(Geometry g, AssetManager assets) {
Material m = g.getMaterial();
System.out.println("geom:" + g + " has material:" + m);
System.out.println(" pos:" + g.getLocalTranslation());
MatParamTexture mpt = m.getTextureParam("DiffuseMap");
Texture t = mpt.getTextureValue();
System.out.println(" -- texture:" + t);
Material material = new Material(assets, "MatDefs/LightingWithFog2.j3md");
material.setTexture("DiffuseMap", t);
material.setColor("Diffuse", MaterialIndex.getDiffuse());
material.setColor("Ambient", MaterialIndex.getAmbient().mult(1.5F));
material.setColor("Specular", MaterialIndex.getSpecular());
material.setColor("FogColor", MaterialIndex.getFogColor());
material.setFloat("Shininess", 100.0F);
material.setFloat("SunFactor", 1.0F);
material.setFloat("LightFactor", 0.0F);
material.setBoolean("UseMaterialColors", true);
g.setMaterial(material);
this.materials.add(material);
}
public void setEntityId(EntityId id) {
if (id != null)
this.model.setUserData("id", Long.valueOf(id.getId()));
}
public long getEntityId() {
Long l = (Long) this.model.getUserData("id");
if (l == null)
return -1L;
return l.longValue();
}
protected void updateText(String s) {
if (this.label != null) {
this.label.removeFromParent();
}
this.label = new BitmapText(this.font, false);
this.label.setSize(1.0F);
this.label.setText(s);
float textWidth = this.label.getLineWidth() + 20.0F;
float textOffset = textWidth / 2.0F;
this.label.setBox(new Rectangle(-textOffset, 0.0F, textWidth, this.label.getHeight()));
this.label.setColor(new ColorRGBA(0.0F, 1.0F, 1.0F, 1.0F));
this.label.setAlignment(BitmapFont.Align.Center);
this.label.setQueueBucket(RenderQueue.Bucket.Transparent);
BillboardControl bc = new BillboardControl();
bc.setAlignment(BillboardControl.Alignment.Screen);
this.label.addControl(bc);
this.textNode.attachChild(this.label);
}
public void setName(String name) {
if ((this.name != null) && (this.name.equals(name)))
return;
if (name == null) {
return;
}
this.name = name;
updateText(name);
}
public String getName() {
return this.name;
}
public float getHeadHeight() {
return this.headHeight;
}
protected static void fixBucket(Node n) {
n.setQueueBucket(RenderQueue.Bucket.Opaque);
for (Spatial c : n.getChildren()) {
c.setQueueBucket(RenderQueue.Bucket.Opaque);
if ((c instanceof Node))
fixBucket((Node) c);
}
}
protected SkeletonControl findSkeletonControl(Node n) {
for (Spatial s : n.getChildren()) {
SkeletonControl sc = (SkeletonControl) s.getControl(SkeletonControl.class);
if (sc != null) {
return sc;
}
if ((s instanceof Node))
sc = findSkeletonControl((Node) s);
if (sc != null)
return sc;
}
return null;
}
protected Skeleton getSkeleton() {
if (this.skeletonControl != null)
return this.skeletonControl.getSkeleton();
this.skeletonControl = ((SkeletonControl) this.model.getControl(SkeletonControl.class));
if (this.skeletonControl != null) {
return this.skeletonControl.getSkeleton();
}
if ((this.model instanceof Node)) {
this.skeletonControl = findSkeletonControl((Node) this.model);
}
if (this.skeletonControl != null)
return this.skeletonControl.getSkeleton();
return null;
}
public void setLighting(float sun, float local) {
for (Material material : this.materials) {
material.setFloat("SunFactor", sun);
material.setFloat("LightFactor", local);
}
}
public void setFacing(Quaternion quat) {
if ((this.facing != null) && (this.facing.equals(quat))) {
return;
}
this.facing = quat.clone();
float[] angles = this.facing.toAngles(null);
Quaternion body = new Quaternion().fromAngles(0.0F, angles[1], 0.0F);
float angle = FastMath.clamp(angles[0], -1.570796F, 1.570796F);
Quaternion head = new Quaternion().fromAngles(angle * 0.5F, 0.0F, 0.0F);
Quaternion realHead = new Quaternion().fromAngles(angle * 0.5F, 0.0F, 0.0F);
setLocalRotation(body);
Bone b = getSkeleton().getBone("Head");
b.setUserControl(true);
b.setUserTransforms(Vector3f.ZERO, head, Vector3f.UNIT_XYZ);
if (this.headNode != null)
this.headNode.setLocalRotation(realHead);
if (this.hairNode != null)
this.hairNode.setLocalRotation(realHead);
}
public String toString() {
return "Avatar[" + getName() + ", " + getEntityId() + "]";
}
}
|
UTF-8
|
Java
| 8,944 |
java
|
Avatar.java
|
Java
|
[] | null |
[] |
package mythruna.client;
import com.jme3.animation.Bone;
import com.jme3.animation.Skeleton;
import com.jme3.animation.SkeletonControl;
import com.jme3.asset.AssetManager;
import com.jme3.collision.Collidable;
import com.jme3.collision.CollisionResults;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.font.Rectangle;
import com.jme3.material.MatParamTexture;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.BillboardControl;
import com.jme3.scene.control.Control;
import com.jme3.texture.Texture;
import mythruna.MaterialIndex;
import mythruna.es.EntityId;
import java.util.ArrayList;
import java.util.List;
public class Avatar extends Node {
public static final String DEFAULT_NAME = "Loading...";
public static final String TYPE = "Avatar";
private Spatial model;
private String name;
private float headHeight = 1.7F;
private BitmapFont font;
private BitmapText label;
private Node textNode;
private Quaternion facing;
private Node headNode;
private Node hairNode;
private SkeletonControl skeletonControl;
private List<Material> materials = new ArrayList();
public Avatar(AssetManager assets, String name) {
super("FemaleAvatar");
String tempName = name == null ? "Loading..." : name;
float scale = 0.2700617F;
this.model = assets.loadModel("Models/female-parts.j3o");
setupMaterial(this.model, assets);
if ((this.model instanceof Node))
fixBucket((Node) this.model);
this.model.setQueueBucket(RenderQueue.Bucket.Opaque);
this.model.setUserData("type", "Avatar");
attachChild(this.model);
this.model.setLocalTranslation(0.0F, -(this.headHeight / scale), 0.0F);
setLocalScale(scale, scale, scale);
this.font = assets.loadFont("Interface/knights24-outline.fnt");
this.textNode = new Node("LabelNode");
this.textNode.setLocalScale(0.7F, 0.7F, 0.7F);
updateText(tempName);
this.textNode.setLocalTranslation(0.0F, this.label.getHeight(), 0.0F);
attachChild(this.textNode);
System.out.println("Found skeleton:" + getSkeleton());
}
public int collideWith(Collidable other, CollisionResults results) {
return super.collideWith(other, results);
}
protected void showControls(Spatial s) {
System.out.println("show controls:" + s);
int count = s.getNumControls();
for (int i = 0; i < count; i++) {
Control c = s.getControl(i);
System.out.println(" c[" + i + "] = " + c);
}
if ((s instanceof Node)) {
for (Spatial child : ((Node) s).getChildren())
showControls(child);
}
}
protected void attachHead(Node n) {
this.headNode = n;
}
protected void attachHair(Node n) {
this.hairNode = n;
}
protected void setupMaterial(Spatial s, AssetManager assets) {
if ((s instanceof Geometry))
setupMaterial((Geometry) s, assets);
else
setupMaterial((Node) s, assets);
}
protected void setupMaterial(Node n, AssetManager assets) {
System.out.println("Node:" + n);
if ("head".equals(n.getName()))
attachHead(n);
else if ("hair".equals(n.getName())) {
attachHair(n);
}
for (Spatial s : n.getChildren())
setupMaterial(s, assets);
}
protected void setupMaterial(Geometry g, AssetManager assets) {
Material m = g.getMaterial();
System.out.println("geom:" + g + " has material:" + m);
System.out.println(" pos:" + g.getLocalTranslation());
MatParamTexture mpt = m.getTextureParam("DiffuseMap");
Texture t = mpt.getTextureValue();
System.out.println(" -- texture:" + t);
Material material = new Material(assets, "MatDefs/LightingWithFog2.j3md");
material.setTexture("DiffuseMap", t);
material.setColor("Diffuse", MaterialIndex.getDiffuse());
material.setColor("Ambient", MaterialIndex.getAmbient().mult(1.5F));
material.setColor("Specular", MaterialIndex.getSpecular());
material.setColor("FogColor", MaterialIndex.getFogColor());
material.setFloat("Shininess", 100.0F);
material.setFloat("SunFactor", 1.0F);
material.setFloat("LightFactor", 0.0F);
material.setBoolean("UseMaterialColors", true);
g.setMaterial(material);
this.materials.add(material);
}
public void setEntityId(EntityId id) {
if (id != null)
this.model.setUserData("id", Long.valueOf(id.getId()));
}
public long getEntityId() {
Long l = (Long) this.model.getUserData("id");
if (l == null)
return -1L;
return l.longValue();
}
protected void updateText(String s) {
if (this.label != null) {
this.label.removeFromParent();
}
this.label = new BitmapText(this.font, false);
this.label.setSize(1.0F);
this.label.setText(s);
float textWidth = this.label.getLineWidth() + 20.0F;
float textOffset = textWidth / 2.0F;
this.label.setBox(new Rectangle(-textOffset, 0.0F, textWidth, this.label.getHeight()));
this.label.setColor(new ColorRGBA(0.0F, 1.0F, 1.0F, 1.0F));
this.label.setAlignment(BitmapFont.Align.Center);
this.label.setQueueBucket(RenderQueue.Bucket.Transparent);
BillboardControl bc = new BillboardControl();
bc.setAlignment(BillboardControl.Alignment.Screen);
this.label.addControl(bc);
this.textNode.attachChild(this.label);
}
public void setName(String name) {
if ((this.name != null) && (this.name.equals(name)))
return;
if (name == null) {
return;
}
this.name = name;
updateText(name);
}
public String getName() {
return this.name;
}
public float getHeadHeight() {
return this.headHeight;
}
protected static void fixBucket(Node n) {
n.setQueueBucket(RenderQueue.Bucket.Opaque);
for (Spatial c : n.getChildren()) {
c.setQueueBucket(RenderQueue.Bucket.Opaque);
if ((c instanceof Node))
fixBucket((Node) c);
}
}
protected SkeletonControl findSkeletonControl(Node n) {
for (Spatial s : n.getChildren()) {
SkeletonControl sc = (SkeletonControl) s.getControl(SkeletonControl.class);
if (sc != null) {
return sc;
}
if ((s instanceof Node))
sc = findSkeletonControl((Node) s);
if (sc != null)
return sc;
}
return null;
}
protected Skeleton getSkeleton() {
if (this.skeletonControl != null)
return this.skeletonControl.getSkeleton();
this.skeletonControl = ((SkeletonControl) this.model.getControl(SkeletonControl.class));
if (this.skeletonControl != null) {
return this.skeletonControl.getSkeleton();
}
if ((this.model instanceof Node)) {
this.skeletonControl = findSkeletonControl((Node) this.model);
}
if (this.skeletonControl != null)
return this.skeletonControl.getSkeleton();
return null;
}
public void setLighting(float sun, float local) {
for (Material material : this.materials) {
material.setFloat("SunFactor", sun);
material.setFloat("LightFactor", local);
}
}
public void setFacing(Quaternion quat) {
if ((this.facing != null) && (this.facing.equals(quat))) {
return;
}
this.facing = quat.clone();
float[] angles = this.facing.toAngles(null);
Quaternion body = new Quaternion().fromAngles(0.0F, angles[1], 0.0F);
float angle = FastMath.clamp(angles[0], -1.570796F, 1.570796F);
Quaternion head = new Quaternion().fromAngles(angle * 0.5F, 0.0F, 0.0F);
Quaternion realHead = new Quaternion().fromAngles(angle * 0.5F, 0.0F, 0.0F);
setLocalRotation(body);
Bone b = getSkeleton().getBone("Head");
b.setUserControl(true);
b.setUserTransforms(Vector3f.ZERO, head, Vector3f.UNIT_XYZ);
if (this.headNode != null)
this.headNode.setLocalRotation(realHead);
if (this.hairNode != null)
this.hairNode.setLocalRotation(realHead);
}
public String toString() {
return "Avatar[" + getName() + ", " + getEntityId() + "]";
}
}
| 8,944 | 0.618851 | 0.605993 | 278 | 31.176258 | 23.43001 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.708633 | false | false |
15
|
e335a6543b8ccaceadaf0a380a2823eb18fdd444
| 33,715,493,278,325 |
b61ab43a0596bc9390c3a06e5407650d7d02ed14
|
/gmh-service/src/main/java/com/zes/squad/gmh/mapper/ConsumeSaleEmployeeMapper.java
|
5c2a8c1a051f802699725c0759eebb0b77d7ac2c
|
[] |
no_license
|
ZES-BJTU/gmh
|
https://github.com/ZES-BJTU/gmh
|
10e4b164a9853d8989a3e97e2745c93cefaa09b5
|
c333b5a33e49b2a66a715d83e1b93c455f8f37d3
|
refs/heads/master
| 2021-05-10T20:51:51.311000 | 2018-05-13T14:26:00 | 2018-05-13T14:26:00 | 117,359,861 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zes.squad.gmh.mapper;
import java.util.List;
import java.util.Map;
import com.zes.squad.gmh.entity.po.ConsumeSaleEmployeePo;
import com.zes.squad.gmh.entity.union.ConsumeSaleEmployeeUnion;
import com.zes.squad.gmh.entity.union.EmployeeSaleMoney;
public interface ConsumeSaleEmployeeMapper {
List<ConsumeSaleEmployeeUnion> getUnionByrecordId(Long consumeRecordId);
void insert(ConsumeSaleEmployeePo consumeSaleEmployee);
List<EmployeeSaleMoney> getSaleUnionByEmployeeId(Map<String, Object> map);
}
|
UTF-8
|
Java
| 544 |
java
|
ConsumeSaleEmployeeMapper.java
|
Java
|
[] | null |
[] |
package com.zes.squad.gmh.mapper;
import java.util.List;
import java.util.Map;
import com.zes.squad.gmh.entity.po.ConsumeSaleEmployeePo;
import com.zes.squad.gmh.entity.union.ConsumeSaleEmployeeUnion;
import com.zes.squad.gmh.entity.union.EmployeeSaleMoney;
public interface ConsumeSaleEmployeeMapper {
List<ConsumeSaleEmployeeUnion> getUnionByrecordId(Long consumeRecordId);
void insert(ConsumeSaleEmployeePo consumeSaleEmployee);
List<EmployeeSaleMoney> getSaleUnionByEmployeeId(Map<String, Object> map);
}
| 544 | 0.794118 | 0.794118 | 17 | 30 | 29.049654 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false |
15
|
8fa37edd942df7b771fa70fddae5e9f1f9513c19
| 33,715,493,276,797 |
63d319fbd88e49701d8dcc2919c8f3a6013e90d0
|
/Applications/CIM/plugins/es.tid.cim/src/es/tid/cim/impl/ComputerSystemImpl.java
|
258b35be9986855e0478eda72bb42e0e06166a2d
|
[] |
no_license
|
DevBoost/Reuseware
|
https://github.com/DevBoost/Reuseware
|
2e6b3626c0d434bb435fcf688e3a3c570714d980
|
4c2f0170df52f110c77ee8cffd2705af69b66506
|
refs/heads/master
| 2021-01-19T21:28:13.184000 | 2019-06-09T20:39:41 | 2019-06-09T20:48:34 | 5,324,741 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package es.tid.cim.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
import es.tid.cim.CimPackage;
import es.tid.cim.ComputerSystem;
import es.tid.cim.EnumDedicated;
import es.tid.cim.FilterList;
import es.tid.cim.ForwardingService;
import es.tid.cim.OperatingSystem;
import es.tid.cim.RouteCalculationService;
import es.tid.cim.RoutingPolicy;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Computer System</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getOtherIdentifyingInfo <em>Other Identifying Info</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getIdentifyingDescriptions <em>Identifying Descriptions</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getDedicated <em>Dedicated</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getOtherDedicatedDescriptions <em>Other Dedicated Descriptions</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getResetCapability <em>Reset Capability</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getHostedRoutingServices <em>Hosted Routing Services</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getHostedForwardingServices <em>Hosted Forwarding Services</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getHostedRoutingPolicy <em>Hosted Routing Policy</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getHostedFilterList <em>Hosted Filter List</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getRunningOS <em>Running OS</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ComputerSystemImpl extends SystemImpl implements ComputerSystem {
/**
* The default value of the '{@link #getOtherIdentifyingInfo() <em>Other Identifying Info</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherIdentifyingInfo()
* @generated
* @ordered
*/
protected static final String OTHER_IDENTIFYING_INFO_EDEFAULT = null;
/**
* The cached value of the '{@link #getOtherIdentifyingInfo() <em>Other Identifying Info</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherIdentifyingInfo()
* @generated
* @ordered
*/
protected String otherIdentifyingInfo = OTHER_IDENTIFYING_INFO_EDEFAULT;
/**
* The default value of the '{@link #getIdentifyingDescriptions() <em>Identifying Descriptions</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdentifyingDescriptions()
* @generated
* @ordered
*/
protected static final String IDENTIFYING_DESCRIPTIONS_EDEFAULT = null;
/**
* The cached value of the '{@link #getIdentifyingDescriptions() <em>Identifying Descriptions</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdentifyingDescriptions()
* @generated
* @ordered
*/
protected String identifyingDescriptions = IDENTIFYING_DESCRIPTIONS_EDEFAULT;
/**
* The cached value of the '{@link #getDedicated() <em>Dedicated</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDedicated()
* @generated
* @ordered
*/
protected EList<EnumDedicated> dedicated;
/**
* The cached value of the '{@link #getOtherDedicatedDescriptions() <em>Other Dedicated Descriptions</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherDedicatedDescriptions()
* @generated
* @ordered
*/
protected EList<String> otherDedicatedDescriptions;
/**
* The default value of the '{@link #getResetCapability() <em>Reset Capability</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResetCapability()
* @generated
* @ordered
*/
protected static final String RESET_CAPABILITY_EDEFAULT = null;
/**
* The cached value of the '{@link #getResetCapability() <em>Reset Capability</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResetCapability()
* @generated
* @ordered
*/
protected String resetCapability = RESET_CAPABILITY_EDEFAULT;
/**
* The cached value of the '{@link #getHostedRoutingServices() <em>Hosted Routing Services</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHostedRoutingServices()
* @generated
* @ordered
*/
protected EList<RouteCalculationService> hostedRoutingServices;
/**
* The cached value of the '{@link #getHostedForwardingServices() <em>Hosted Forwarding Services</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHostedForwardingServices()
* @generated
* @ordered
*/
protected EList<ForwardingService> hostedForwardingServices;
/**
* The cached value of the '{@link #getHostedRoutingPolicy() <em>Hosted Routing Policy</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHostedRoutingPolicy()
* @generated
* @ordered
*/
protected EList<RoutingPolicy> hostedRoutingPolicy;
/**
* The cached value of the '{@link #getHostedFilterList() <em>Hosted Filter List</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHostedFilterList()
* @generated
* @ordered
*/
protected EList<FilterList> hostedFilterList;
/**
* The cached value of the '{@link #getRunningOS() <em>Running OS</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRunningOS()
* @generated
* @ordered
*/
protected OperatingSystem runningOS;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComputerSystemImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return CimPackage.eINSTANCE.getComputerSystem();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getOtherIdentifyingInfo() {
return otherIdentifyingInfo;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOtherIdentifyingInfo(String newOtherIdentifyingInfo) {
String oldOtherIdentifyingInfo = otherIdentifyingInfo;
otherIdentifyingInfo = newOtherIdentifyingInfo;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO, oldOtherIdentifyingInfo, otherIdentifyingInfo));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getIdentifyingDescriptions() {
return identifyingDescriptions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIdentifyingDescriptions(String newIdentifyingDescriptions) {
String oldIdentifyingDescriptions = identifyingDescriptions;
identifyingDescriptions = newIdentifyingDescriptions;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS, oldIdentifyingDescriptions, identifyingDescriptions));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<EnumDedicated> getDedicated() {
if (dedicated == null) {
dedicated = new EDataTypeUniqueEList<EnumDedicated>(EnumDedicated.class, this, CimPackage.COMPUTER_SYSTEM__DEDICATED);
}
return dedicated;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<String> getOtherDedicatedDescriptions() {
if (otherDedicatedDescriptions == null) {
otherDedicatedDescriptions = new EDataTypeUniqueEList<String>(String.class, this, CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS);
}
return otherDedicatedDescriptions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getResetCapability() {
return resetCapability;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setResetCapability(String newResetCapability) {
String oldResetCapability = resetCapability;
resetCapability = newResetCapability;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY, oldResetCapability, resetCapability));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<RouteCalculationService> getHostedRoutingServices() {
if (hostedRoutingServices == null) {
hostedRoutingServices = new EObjectResolvingEList<RouteCalculationService>(RouteCalculationService.class, this, CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES);
}
return hostedRoutingServices;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ForwardingService> getHostedForwardingServices() {
if (hostedForwardingServices == null) {
hostedForwardingServices = new EObjectResolvingEList<ForwardingService>(ForwardingService.class, this, CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES);
}
return hostedForwardingServices;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<RoutingPolicy> getHostedRoutingPolicy() {
if (hostedRoutingPolicy == null) {
hostedRoutingPolicy = new EObjectResolvingEList<RoutingPolicy>(RoutingPolicy.class, this, CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY);
}
return hostedRoutingPolicy;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<FilterList> getHostedFilterList() {
if (hostedFilterList == null) {
hostedFilterList = new EObjectResolvingEList<FilterList>(FilterList.class, this, CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST);
}
return hostedFilterList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OperatingSystem getRunningOS() {
if (runningOS != null && runningOS.eIsProxy()) {
InternalEObject oldRunningOS = (InternalEObject)runningOS;
runningOS = (OperatingSystem)eResolveProxy(oldRunningOS);
if (runningOS != oldRunningOS) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, CimPackage.COMPUTER_SYSTEM__RUNNING_OS, oldRunningOS, runningOS));
}
}
return runningOS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OperatingSystem basicGetRunningOS() {
return runningOS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRunningOS(OperatingSystem newRunningOS) {
OperatingSystem oldRunningOS = runningOS;
runningOS = newRunningOS;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CimPackage.COMPUTER_SYSTEM__RUNNING_OS, oldRunningOS, runningOS));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO:
return getOtherIdentifyingInfo();
case CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS:
return getIdentifyingDescriptions();
case CimPackage.COMPUTER_SYSTEM__DEDICATED:
return getDedicated();
case CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS:
return getOtherDedicatedDescriptions();
case CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY:
return getResetCapability();
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES:
return getHostedRoutingServices();
case CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES:
return getHostedForwardingServices();
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY:
return getHostedRoutingPolicy();
case CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST:
return getHostedFilterList();
case CimPackage.COMPUTER_SYSTEM__RUNNING_OS:
if (resolve) return getRunningOS();
return basicGetRunningOS();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO:
setOtherIdentifyingInfo((String)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS:
setIdentifyingDescriptions((String)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__DEDICATED:
getDedicated().clear();
getDedicated().addAll((Collection<? extends EnumDedicated>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS:
getOtherDedicatedDescriptions().clear();
getOtherDedicatedDescriptions().addAll((Collection<? extends String>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY:
setResetCapability((String)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES:
getHostedRoutingServices().clear();
getHostedRoutingServices().addAll((Collection<? extends RouteCalculationService>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES:
getHostedForwardingServices().clear();
getHostedForwardingServices().addAll((Collection<? extends ForwardingService>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY:
getHostedRoutingPolicy().clear();
getHostedRoutingPolicy().addAll((Collection<? extends RoutingPolicy>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST:
getHostedFilterList().clear();
getHostedFilterList().addAll((Collection<? extends FilterList>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__RUNNING_OS:
setRunningOS((OperatingSystem)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO:
setOtherIdentifyingInfo(OTHER_IDENTIFYING_INFO_EDEFAULT);
return;
case CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS:
setIdentifyingDescriptions(IDENTIFYING_DESCRIPTIONS_EDEFAULT);
return;
case CimPackage.COMPUTER_SYSTEM__DEDICATED:
getDedicated().clear();
return;
case CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS:
getOtherDedicatedDescriptions().clear();
return;
case CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY:
setResetCapability(RESET_CAPABILITY_EDEFAULT);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES:
getHostedRoutingServices().clear();
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES:
getHostedForwardingServices().clear();
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY:
getHostedRoutingPolicy().clear();
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST:
getHostedFilterList().clear();
return;
case CimPackage.COMPUTER_SYSTEM__RUNNING_OS:
setRunningOS((OperatingSystem)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO:
return OTHER_IDENTIFYING_INFO_EDEFAULT == null ? otherIdentifyingInfo != null : !OTHER_IDENTIFYING_INFO_EDEFAULT.equals(otherIdentifyingInfo);
case CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS:
return IDENTIFYING_DESCRIPTIONS_EDEFAULT == null ? identifyingDescriptions != null : !IDENTIFYING_DESCRIPTIONS_EDEFAULT.equals(identifyingDescriptions);
case CimPackage.COMPUTER_SYSTEM__DEDICATED:
return dedicated != null && !dedicated.isEmpty();
case CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS:
return otherDedicatedDescriptions != null && !otherDedicatedDescriptions.isEmpty();
case CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY:
return RESET_CAPABILITY_EDEFAULT == null ? resetCapability != null : !RESET_CAPABILITY_EDEFAULT.equals(resetCapability);
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES:
return hostedRoutingServices != null && !hostedRoutingServices.isEmpty();
case CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES:
return hostedForwardingServices != null && !hostedForwardingServices.isEmpty();
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY:
return hostedRoutingPolicy != null && !hostedRoutingPolicy.isEmpty();
case CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST:
return hostedFilterList != null && !hostedFilterList.isEmpty();
case CimPackage.COMPUTER_SYSTEM__RUNNING_OS:
return runningOS != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (otherIdentifyingInfo: ");
result.append(otherIdentifyingInfo);
result.append(", identifyingDescriptions: ");
result.append(identifyingDescriptions);
result.append(", dedicated: ");
result.append(dedicated);
result.append(", otherDedicatedDescriptions: ");
result.append(otherDedicatedDescriptions);
result.append(", resetCapability: ");
result.append(resetCapability);
result.append(')');
return result.toString();
}
} //ComputerSystemImpl
|
UTF-8
|
Java
| 18,601 |
java
|
ComputerSystemImpl.java
|
Java
|
[] | null |
[] |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package es.tid.cim.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
import es.tid.cim.CimPackage;
import es.tid.cim.ComputerSystem;
import es.tid.cim.EnumDedicated;
import es.tid.cim.FilterList;
import es.tid.cim.ForwardingService;
import es.tid.cim.OperatingSystem;
import es.tid.cim.RouteCalculationService;
import es.tid.cim.RoutingPolicy;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Computer System</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getOtherIdentifyingInfo <em>Other Identifying Info</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getIdentifyingDescriptions <em>Identifying Descriptions</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getDedicated <em>Dedicated</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getOtherDedicatedDescriptions <em>Other Dedicated Descriptions</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getResetCapability <em>Reset Capability</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getHostedRoutingServices <em>Hosted Routing Services</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getHostedForwardingServices <em>Hosted Forwarding Services</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getHostedRoutingPolicy <em>Hosted Routing Policy</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getHostedFilterList <em>Hosted Filter List</em>}</li>
* <li>{@link es.tid.cim.impl.ComputerSystemImpl#getRunningOS <em>Running OS</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ComputerSystemImpl extends SystemImpl implements ComputerSystem {
/**
* The default value of the '{@link #getOtherIdentifyingInfo() <em>Other Identifying Info</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherIdentifyingInfo()
* @generated
* @ordered
*/
protected static final String OTHER_IDENTIFYING_INFO_EDEFAULT = null;
/**
* The cached value of the '{@link #getOtherIdentifyingInfo() <em>Other Identifying Info</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherIdentifyingInfo()
* @generated
* @ordered
*/
protected String otherIdentifyingInfo = OTHER_IDENTIFYING_INFO_EDEFAULT;
/**
* The default value of the '{@link #getIdentifyingDescriptions() <em>Identifying Descriptions</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdentifyingDescriptions()
* @generated
* @ordered
*/
protected static final String IDENTIFYING_DESCRIPTIONS_EDEFAULT = null;
/**
* The cached value of the '{@link #getIdentifyingDescriptions() <em>Identifying Descriptions</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdentifyingDescriptions()
* @generated
* @ordered
*/
protected String identifyingDescriptions = IDENTIFYING_DESCRIPTIONS_EDEFAULT;
/**
* The cached value of the '{@link #getDedicated() <em>Dedicated</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDedicated()
* @generated
* @ordered
*/
protected EList<EnumDedicated> dedicated;
/**
* The cached value of the '{@link #getOtherDedicatedDescriptions() <em>Other Dedicated Descriptions</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOtherDedicatedDescriptions()
* @generated
* @ordered
*/
protected EList<String> otherDedicatedDescriptions;
/**
* The default value of the '{@link #getResetCapability() <em>Reset Capability</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResetCapability()
* @generated
* @ordered
*/
protected static final String RESET_CAPABILITY_EDEFAULT = null;
/**
* The cached value of the '{@link #getResetCapability() <em>Reset Capability</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResetCapability()
* @generated
* @ordered
*/
protected String resetCapability = RESET_CAPABILITY_EDEFAULT;
/**
* The cached value of the '{@link #getHostedRoutingServices() <em>Hosted Routing Services</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHostedRoutingServices()
* @generated
* @ordered
*/
protected EList<RouteCalculationService> hostedRoutingServices;
/**
* The cached value of the '{@link #getHostedForwardingServices() <em>Hosted Forwarding Services</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHostedForwardingServices()
* @generated
* @ordered
*/
protected EList<ForwardingService> hostedForwardingServices;
/**
* The cached value of the '{@link #getHostedRoutingPolicy() <em>Hosted Routing Policy</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHostedRoutingPolicy()
* @generated
* @ordered
*/
protected EList<RoutingPolicy> hostedRoutingPolicy;
/**
* The cached value of the '{@link #getHostedFilterList() <em>Hosted Filter List</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHostedFilterList()
* @generated
* @ordered
*/
protected EList<FilterList> hostedFilterList;
/**
* The cached value of the '{@link #getRunningOS() <em>Running OS</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRunningOS()
* @generated
* @ordered
*/
protected OperatingSystem runningOS;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComputerSystemImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return CimPackage.eINSTANCE.getComputerSystem();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getOtherIdentifyingInfo() {
return otherIdentifyingInfo;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOtherIdentifyingInfo(String newOtherIdentifyingInfo) {
String oldOtherIdentifyingInfo = otherIdentifyingInfo;
otherIdentifyingInfo = newOtherIdentifyingInfo;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO, oldOtherIdentifyingInfo, otherIdentifyingInfo));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getIdentifyingDescriptions() {
return identifyingDescriptions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIdentifyingDescriptions(String newIdentifyingDescriptions) {
String oldIdentifyingDescriptions = identifyingDescriptions;
identifyingDescriptions = newIdentifyingDescriptions;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS, oldIdentifyingDescriptions, identifyingDescriptions));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<EnumDedicated> getDedicated() {
if (dedicated == null) {
dedicated = new EDataTypeUniqueEList<EnumDedicated>(EnumDedicated.class, this, CimPackage.COMPUTER_SYSTEM__DEDICATED);
}
return dedicated;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<String> getOtherDedicatedDescriptions() {
if (otherDedicatedDescriptions == null) {
otherDedicatedDescriptions = new EDataTypeUniqueEList<String>(String.class, this, CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS);
}
return otherDedicatedDescriptions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getResetCapability() {
return resetCapability;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setResetCapability(String newResetCapability) {
String oldResetCapability = resetCapability;
resetCapability = newResetCapability;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY, oldResetCapability, resetCapability));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<RouteCalculationService> getHostedRoutingServices() {
if (hostedRoutingServices == null) {
hostedRoutingServices = new EObjectResolvingEList<RouteCalculationService>(RouteCalculationService.class, this, CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES);
}
return hostedRoutingServices;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ForwardingService> getHostedForwardingServices() {
if (hostedForwardingServices == null) {
hostedForwardingServices = new EObjectResolvingEList<ForwardingService>(ForwardingService.class, this, CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES);
}
return hostedForwardingServices;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<RoutingPolicy> getHostedRoutingPolicy() {
if (hostedRoutingPolicy == null) {
hostedRoutingPolicy = new EObjectResolvingEList<RoutingPolicy>(RoutingPolicy.class, this, CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY);
}
return hostedRoutingPolicy;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<FilterList> getHostedFilterList() {
if (hostedFilterList == null) {
hostedFilterList = new EObjectResolvingEList<FilterList>(FilterList.class, this, CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST);
}
return hostedFilterList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OperatingSystem getRunningOS() {
if (runningOS != null && runningOS.eIsProxy()) {
InternalEObject oldRunningOS = (InternalEObject)runningOS;
runningOS = (OperatingSystem)eResolveProxy(oldRunningOS);
if (runningOS != oldRunningOS) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, CimPackage.COMPUTER_SYSTEM__RUNNING_OS, oldRunningOS, runningOS));
}
}
return runningOS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OperatingSystem basicGetRunningOS() {
return runningOS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRunningOS(OperatingSystem newRunningOS) {
OperatingSystem oldRunningOS = runningOS;
runningOS = newRunningOS;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CimPackage.COMPUTER_SYSTEM__RUNNING_OS, oldRunningOS, runningOS));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO:
return getOtherIdentifyingInfo();
case CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS:
return getIdentifyingDescriptions();
case CimPackage.COMPUTER_SYSTEM__DEDICATED:
return getDedicated();
case CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS:
return getOtherDedicatedDescriptions();
case CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY:
return getResetCapability();
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES:
return getHostedRoutingServices();
case CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES:
return getHostedForwardingServices();
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY:
return getHostedRoutingPolicy();
case CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST:
return getHostedFilterList();
case CimPackage.COMPUTER_SYSTEM__RUNNING_OS:
if (resolve) return getRunningOS();
return basicGetRunningOS();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO:
setOtherIdentifyingInfo((String)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS:
setIdentifyingDescriptions((String)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__DEDICATED:
getDedicated().clear();
getDedicated().addAll((Collection<? extends EnumDedicated>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS:
getOtherDedicatedDescriptions().clear();
getOtherDedicatedDescriptions().addAll((Collection<? extends String>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY:
setResetCapability((String)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES:
getHostedRoutingServices().clear();
getHostedRoutingServices().addAll((Collection<? extends RouteCalculationService>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES:
getHostedForwardingServices().clear();
getHostedForwardingServices().addAll((Collection<? extends ForwardingService>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY:
getHostedRoutingPolicy().clear();
getHostedRoutingPolicy().addAll((Collection<? extends RoutingPolicy>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST:
getHostedFilterList().clear();
getHostedFilterList().addAll((Collection<? extends FilterList>)newValue);
return;
case CimPackage.COMPUTER_SYSTEM__RUNNING_OS:
setRunningOS((OperatingSystem)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO:
setOtherIdentifyingInfo(OTHER_IDENTIFYING_INFO_EDEFAULT);
return;
case CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS:
setIdentifyingDescriptions(IDENTIFYING_DESCRIPTIONS_EDEFAULT);
return;
case CimPackage.COMPUTER_SYSTEM__DEDICATED:
getDedicated().clear();
return;
case CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS:
getOtherDedicatedDescriptions().clear();
return;
case CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY:
setResetCapability(RESET_CAPABILITY_EDEFAULT);
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES:
getHostedRoutingServices().clear();
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES:
getHostedForwardingServices().clear();
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY:
getHostedRoutingPolicy().clear();
return;
case CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST:
getHostedFilterList().clear();
return;
case CimPackage.COMPUTER_SYSTEM__RUNNING_OS:
setRunningOS((OperatingSystem)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case CimPackage.COMPUTER_SYSTEM__OTHER_IDENTIFYING_INFO:
return OTHER_IDENTIFYING_INFO_EDEFAULT == null ? otherIdentifyingInfo != null : !OTHER_IDENTIFYING_INFO_EDEFAULT.equals(otherIdentifyingInfo);
case CimPackage.COMPUTER_SYSTEM__IDENTIFYING_DESCRIPTIONS:
return IDENTIFYING_DESCRIPTIONS_EDEFAULT == null ? identifyingDescriptions != null : !IDENTIFYING_DESCRIPTIONS_EDEFAULT.equals(identifyingDescriptions);
case CimPackage.COMPUTER_SYSTEM__DEDICATED:
return dedicated != null && !dedicated.isEmpty();
case CimPackage.COMPUTER_SYSTEM__OTHER_DEDICATED_DESCRIPTIONS:
return otherDedicatedDescriptions != null && !otherDedicatedDescriptions.isEmpty();
case CimPackage.COMPUTER_SYSTEM__RESET_CAPABILITY:
return RESET_CAPABILITY_EDEFAULT == null ? resetCapability != null : !RESET_CAPABILITY_EDEFAULT.equals(resetCapability);
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_SERVICES:
return hostedRoutingServices != null && !hostedRoutingServices.isEmpty();
case CimPackage.COMPUTER_SYSTEM__HOSTED_FORWARDING_SERVICES:
return hostedForwardingServices != null && !hostedForwardingServices.isEmpty();
case CimPackage.COMPUTER_SYSTEM__HOSTED_ROUTING_POLICY:
return hostedRoutingPolicy != null && !hostedRoutingPolicy.isEmpty();
case CimPackage.COMPUTER_SYSTEM__HOSTED_FILTER_LIST:
return hostedFilterList != null && !hostedFilterList.isEmpty();
case CimPackage.COMPUTER_SYSTEM__RUNNING_OS:
return runningOS != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (otherIdentifyingInfo: ");
result.append(otherIdentifyingInfo);
result.append(", identifyingDescriptions: ");
result.append(identifyingDescriptions);
result.append(", dedicated: ");
result.append(dedicated);
result.append(", otherDedicatedDescriptions: ");
result.append(otherDedicatedDescriptions);
result.append(", resetCapability: ");
result.append(resetCapability);
result.append(')');
return result.toString();
}
} //ComputerSystemImpl
| 18,601 | 0.685447 | 0.685447 | 554 | 31.575811 | 32.155514 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.873646 | false | false |
15
|
6e734a73dd25b4d2e94e7c775aeb251986e397dd
| 33,715,493,276,180 |
f0400b6240a08714c0869f1bf0ab2512d6f1581f
|
/test-complete/src/test/java/com/marklogic/javaclient/TestPatchCardinality.java
|
54182bb505f69f6fbcbbe43bbb0e28e163923e74
|
[
"Apache-2.0"
] |
permissive
|
jmakeig/java-client-api
|
https://github.com/jmakeig/java-client-api
|
7085d6e96b893c70ba727f7382a33223765fb9fe
|
df4ba2ded68b893ee50dc453cbf966d9660d9f1c
|
refs/heads/master
| 2021-01-18T10:12:15.259000 | 2014-08-12T16:59:10 | 2014-08-12T16:59:10 | 25,699,198 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.marklogic.javaclient;
import static org.junit.Assert.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.document.DocumentManager.Metadata;
import com.marklogic.client.document.DocumentMetadataPatchBuilder.Cardinality;
import com.marklogic.client.document.DocumentPatchBuilder;
import com.marklogic.client.document.DocumentPatchBuilder.Position;
import com.marklogic.client.document.DocumentMetadataPatchBuilder;
import com.marklogic.client.document.JSONDocumentManager;
import com.marklogic.client.document.XMLDocumentManager;
import com.marklogic.client.io.DocumentMetadataHandle;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.StringHandle;
import com.marklogic.client.io.marker.DocumentPatchHandle;
import org.junit.*;
public class TestPatchCardinality extends BasicJavaClientREST {
private static String dbName = "TestPatchCardinalityDB";
private static String [] fNames = {"TestPatchCardinalityDB-1"};
private static String restServerName = "REST-Java-Client-API-Server";
@BeforeClass
public static void setUp() throws Exception
{
System.out.println("In setup");
setupJavaRESTServer(dbName, fNames[0], restServerName,8011);
setupAppServicesConstraint(dbName);
}
@SuppressWarnings("deprecation")
@Test public void testOneCardinalityNegative() throws IOException
{
System.out.println("Running testOneCardinalityNegative");
String[] filenames = {"cardinal1.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal1.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
String exception = "";
try
{
docMgr.patch(docId, patchHandle);
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
String expectedException = "Local message: write failed: Bad Request. Server Message: RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request: reason: invalid content patch operations for uri /cardinal/cardinal1.xml: invalid cardinality of 5 nodes for: /root/foo";
assertTrue("Exception is not thrown", exception.contains(expectedException));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testOneCardinalityPositve() throws IOException
{
System.out.println("Running testOneCardinalityPositive");
String[] filenames = {"cardinal2.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal2.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertTrue("fragment is not inserted", content.contains("<bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testOneOrMoreCardinalityPositve() throws IOException
{
System.out.println("Running testOneOrMoreCardinalityPositive");
String[] filenames = {"cardinal1.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal1.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ONE_OR_MORE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertTrue("fragment is not inserted", content.contains("<foo>one</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>two</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>three</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>four</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>five</foo><bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testOneOrMoreCardinalityNegative() throws IOException
{
System.out.println("Running testOneOrMoreCardinalityNegative");
String[] filenames = {"cardinal3.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal3.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ONE_OR_MORE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
String exception = "";
try
{
docMgr.patch(docId, patchHandle);
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
String expectedException = "Local message: write failed: Bad Request. Server Message: RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request: reason: invalid content patch operations for uri /cardinal/cardinal3.xml: invalid cardinality of 0 nodes for: /root/foo";
assertTrue("Exception is not thrown", exception.contains(expectedException));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testZeroOrOneCardinalityNegative() throws IOException
{
System.out.println("Running testZeroOrOneCardinalityNegative");
String[] filenames = {"cardinal1.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal1.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ZERO_OR_ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
String exception = "";
try
{
docMgr.patch(docId, patchHandle);
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
String expectedException = "Local message: write failed: Bad Request. Server Message: RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request: reason: invalid content patch operations for uri /cardinal/cardinal1.xml: invalid cardinality of 5 nodes for: /root/foo";
assertTrue("Exception is not thrown", exception.contains(expectedException));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testZeroOrOneCardinalityPositive() throws IOException
{
System.out.println("Running testZeroOrOneCardinalityPositive");
String[] filenames = {"cardinal2.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal2.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ZERO_OR_ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertTrue("fragment is not inserted", content.contains("<foo>one</foo><bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testZeroOrOneCardinalityPositiveWithZero() throws IOException
{
System.out.println("Running testZeroOrOneCardinalityPositiveWithZero");
String[] filenames = {"cardinal3.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal3.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ZERO_OR_ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertFalse("fragment is inserted", content.contains("<baz>one</baz><bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testZeroOrMoreCardinality() throws IOException
{
System.out.println("Running testZeroOrMoreCardinality");
String[] filenames = {"cardinal1.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal1.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ZERO_OR_MORE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertTrue("fragment is not inserted", content.contains("<foo>one</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>two</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>three</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>four</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>five</foo><bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testBug23843() throws IOException
{
System.out.println("Running testBug23843");
String[] filenames = {"cardinal1.xml","cardinal4.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
String docId = "";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentMetadataHandle readMetadataHandle = new DocumentMetadataHandle();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
if (filename == "cardinal1.xml"){
patchBldr.insertFragment("/root", Position.LAST_CHILD, Cardinality.ONE, "<bar>added</bar>");
}
else if (filename == "cardinal4.xml") {
patchBldr.insertFragment("/root", Position.LAST_CHILD, "<bar>added</bar>");
}
DocumentPatchHandle patchHandle = patchBldr.build();
String RawPatch = patchHandle.toString();
System.out.println("Before"+RawPatch);
String exception = "";
if (filename == "cardinal1.xml"){
try
{ docId= "/cardinal/cardinal1.xml";
docMgr.patch(docId, patchHandle);
System.out.println("After"+docMgr.readMetadata(docId, new DocumentMetadataHandle()).toString());
assertEquals("<?xml version=\"1.0\" encoding=\"utf-8\"?><rapi:metadata xmlns:rapi=\"http://marklogic.com/rest-api\" xmlns:prop=\"http://marklogic.com/xdmp/property\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"><rapi:collections></rapi:collections><rapi:permissions><rapi:permission><rapi:role-name>rest-reader</rapi:role-name><rapi:capability>read</rapi:capability></rapi:permission><rapi:permission><rapi:role-name>rest-writer</rapi:role-name><rapi:capability>update</rapi:capability></rapi:permission></rapi:permissions><prop:properties></prop:properties><rapi:quality>0</rapi:quality></rapi:metadata>", docMgr.readMetadata(docId, new DocumentMetadataHandle()).toString());
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
}
else if (filename == "cardinal4.xml") {
try
{
docId = "/cardinal/cardinal4.xml";
docMgr.clearMetadataCategories();
docMgr.patch(docId, new StringHandle(patchHandle.toString()));
docMgr.setMetadataCategories(Metadata.ALL);
System.out.println("After"+docMgr.readMetadata(docId, new DocumentMetadataHandle()).toString());
assertEquals("", "<?xml version=\"1.0\" encoding=\"utf-8\"?><rapi:metadata xmlns:rapi=\"http://marklogic.com/rest-api\" xmlns:prop=\"http://marklogic.com/xdmp/property\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"><rapi:collections></rapi:collections><rapi:permissions><rapi:permission><rapi:role-name>rest-reader</rapi:role-name><rapi:capability>read</rapi:capability></rapi:permission><rapi:permission><rapi:role-name>rest-writer</rapi:role-name><rapi:capability>update</rapi:capability></rapi:permission></rapi:permissions><prop:properties></prop:properties><rapi:quality>0</rapi:quality></rapi:metadata>", docMgr.readMetadata(docId, new DocumentMetadataHandle()).toString());
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
}
String actual = docMgr.read(docId, new StringHandle()).get();
System.out.println("Actual : "+actual);
}
// release client
client.release();
}
@AfterClass
public static void tearDown() throws Exception
{
System.out.println("In tear down");
tearDownJavaRESTServer(dbName, fNames, restServerName);
}
}
|
UTF-8
|
Java
| 15,632 |
java
|
TestPatchCardinality.java
|
Java
|
[] | null |
[] |
package com.marklogic.javaclient;
import static org.junit.Assert.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.document.DocumentManager.Metadata;
import com.marklogic.client.document.DocumentMetadataPatchBuilder.Cardinality;
import com.marklogic.client.document.DocumentPatchBuilder;
import com.marklogic.client.document.DocumentPatchBuilder.Position;
import com.marklogic.client.document.DocumentMetadataPatchBuilder;
import com.marklogic.client.document.JSONDocumentManager;
import com.marklogic.client.document.XMLDocumentManager;
import com.marklogic.client.io.DocumentMetadataHandle;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.StringHandle;
import com.marklogic.client.io.marker.DocumentPatchHandle;
import org.junit.*;
public class TestPatchCardinality extends BasicJavaClientREST {
private static String dbName = "TestPatchCardinalityDB";
private static String [] fNames = {"TestPatchCardinalityDB-1"};
private static String restServerName = "REST-Java-Client-API-Server";
@BeforeClass
public static void setUp() throws Exception
{
System.out.println("In setup");
setupJavaRESTServer(dbName, fNames[0], restServerName,8011);
setupAppServicesConstraint(dbName);
}
@SuppressWarnings("deprecation")
@Test public void testOneCardinalityNegative() throws IOException
{
System.out.println("Running testOneCardinalityNegative");
String[] filenames = {"cardinal1.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal1.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
String exception = "";
try
{
docMgr.patch(docId, patchHandle);
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
String expectedException = "Local message: write failed: Bad Request. Server Message: RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request: reason: invalid content patch operations for uri /cardinal/cardinal1.xml: invalid cardinality of 5 nodes for: /root/foo";
assertTrue("Exception is not thrown", exception.contains(expectedException));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testOneCardinalityPositve() throws IOException
{
System.out.println("Running testOneCardinalityPositive");
String[] filenames = {"cardinal2.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal2.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertTrue("fragment is not inserted", content.contains("<bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testOneOrMoreCardinalityPositve() throws IOException
{
System.out.println("Running testOneOrMoreCardinalityPositive");
String[] filenames = {"cardinal1.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal1.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ONE_OR_MORE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertTrue("fragment is not inserted", content.contains("<foo>one</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>two</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>three</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>four</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>five</foo><bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testOneOrMoreCardinalityNegative() throws IOException
{
System.out.println("Running testOneOrMoreCardinalityNegative");
String[] filenames = {"cardinal3.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal3.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ONE_OR_MORE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
String exception = "";
try
{
docMgr.patch(docId, patchHandle);
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
String expectedException = "Local message: write failed: Bad Request. Server Message: RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request: reason: invalid content patch operations for uri /cardinal/cardinal3.xml: invalid cardinality of 0 nodes for: /root/foo";
assertTrue("Exception is not thrown", exception.contains(expectedException));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testZeroOrOneCardinalityNegative() throws IOException
{
System.out.println("Running testZeroOrOneCardinalityNegative");
String[] filenames = {"cardinal1.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal1.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ZERO_OR_ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
String exception = "";
try
{
docMgr.patch(docId, patchHandle);
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
String expectedException = "Local message: write failed: Bad Request. Server Message: RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request: reason: invalid content patch operations for uri /cardinal/cardinal1.xml: invalid cardinality of 5 nodes for: /root/foo";
assertTrue("Exception is not thrown", exception.contains(expectedException));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testZeroOrOneCardinalityPositive() throws IOException
{
System.out.println("Running testZeroOrOneCardinalityPositive");
String[] filenames = {"cardinal2.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal2.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ZERO_OR_ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertTrue("fragment is not inserted", content.contains("<foo>one</foo><bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testZeroOrOneCardinalityPositiveWithZero() throws IOException
{
System.out.println("Running testZeroOrOneCardinalityPositiveWithZero");
String[] filenames = {"cardinal3.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal3.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ZERO_OR_ONE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertFalse("fragment is inserted", content.contains("<baz>one</baz><bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testZeroOrMoreCardinality() throws IOException
{
System.out.println("Running testZeroOrMoreCardinality");
String[] filenames = {"cardinal1.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
}
String docId = "/cardinal/cardinal1.xml";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
patchBldr.insertFragment("/root/foo", Position.AFTER, Cardinality.ZERO_OR_MORE, "<bar>added</bar>");
DocumentPatchHandle patchHandle = patchBldr.build();
docMgr.patch(docId, patchHandle);
String content = docMgr.read(docId, new StringHandle()).get();
System.out.println(content);
assertTrue("fragment is not inserted", content.contains("<foo>one</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>two</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>three</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>four</foo><bar>added</bar>"));
assertTrue("fragment is not inserted", content.contains("<foo>five</foo><bar>added</bar>"));
// release client
client.release();
}
@SuppressWarnings("deprecation")
@Test public void testBug23843() throws IOException
{
System.out.println("Running testBug23843");
String[] filenames = {"cardinal1.xml","cardinal4.xml"};
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-writer", "x", Authentication.DIGEST);
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/cardinal/", "XML");
String docId = "";
XMLDocumentManager docMgr = client.newXMLDocumentManager();
DocumentMetadataHandle readMetadataHandle = new DocumentMetadataHandle();
DocumentPatchBuilder patchBldr = docMgr.newPatchBuilder();
if (filename == "cardinal1.xml"){
patchBldr.insertFragment("/root", Position.LAST_CHILD, Cardinality.ONE, "<bar>added</bar>");
}
else if (filename == "cardinal4.xml") {
patchBldr.insertFragment("/root", Position.LAST_CHILD, "<bar>added</bar>");
}
DocumentPatchHandle patchHandle = patchBldr.build();
String RawPatch = patchHandle.toString();
System.out.println("Before"+RawPatch);
String exception = "";
if (filename == "cardinal1.xml"){
try
{ docId= "/cardinal/cardinal1.xml";
docMgr.patch(docId, patchHandle);
System.out.println("After"+docMgr.readMetadata(docId, new DocumentMetadataHandle()).toString());
assertEquals("<?xml version=\"1.0\" encoding=\"utf-8\"?><rapi:metadata xmlns:rapi=\"http://marklogic.com/rest-api\" xmlns:prop=\"http://marklogic.com/xdmp/property\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"><rapi:collections></rapi:collections><rapi:permissions><rapi:permission><rapi:role-name>rest-reader</rapi:role-name><rapi:capability>read</rapi:capability></rapi:permission><rapi:permission><rapi:role-name>rest-writer</rapi:role-name><rapi:capability>update</rapi:capability></rapi:permission></rapi:permissions><prop:properties></prop:properties><rapi:quality>0</rapi:quality></rapi:metadata>", docMgr.readMetadata(docId, new DocumentMetadataHandle()).toString());
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
}
else if (filename == "cardinal4.xml") {
try
{
docId = "/cardinal/cardinal4.xml";
docMgr.clearMetadataCategories();
docMgr.patch(docId, new StringHandle(patchHandle.toString()));
docMgr.setMetadataCategories(Metadata.ALL);
System.out.println("After"+docMgr.readMetadata(docId, new DocumentMetadataHandle()).toString());
assertEquals("", "<?xml version=\"1.0\" encoding=\"utf-8\"?><rapi:metadata xmlns:rapi=\"http://marklogic.com/rest-api\" xmlns:prop=\"http://marklogic.com/xdmp/property\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"><rapi:collections></rapi:collections><rapi:permissions><rapi:permission><rapi:role-name>rest-reader</rapi:role-name><rapi:capability>read</rapi:capability></rapi:permission><rapi:permission><rapi:role-name>rest-writer</rapi:role-name><rapi:capability>update</rapi:capability></rapi:permission></rapi:permissions><prop:properties></prop:properties><rapi:quality>0</rapi:quality></rapi:metadata>", docMgr.readMetadata(docId, new DocumentMetadataHandle()).toString());
}
catch (Exception e)
{
System.out.println(e.getMessage());
exception = e.getMessage();
}
}
String actual = docMgr.read(docId, new StringHandle()).get();
System.out.println("Actual : "+actual);
}
// release client
client.release();
}
@AfterClass
public static void tearDown() throws Exception
{
System.out.println("In tear down");
tearDownJavaRESTServer(dbName, fNames, restServerName);
}
}
| 15,632 | 0.73292 | 0.725115 | 410 | 37.126831 | 61.850357 | 742 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.756098 | false | false |
15
|
514151727356e820e0577bcb808a92cf02301f9e
| 17,136,919,531,510 |
ada221311e48a2e8c12fe3f6ce9836bf637cd60b
|
/kongsupports/src/main/java/com/kong/support/socket/helper/DataParser.java
|
b29bca4013a057ac96693efa01bde26652919e4a
|
[] |
no_license
|
PlayBoxjre/common-web
|
https://github.com/PlayBoxjre/common-web
|
806c027eb65ca0e4890e6e43d98f629fa65c3d77
|
1bc04bd5cd766ec5fe90a6643a9677ad8c30450d
|
refs/heads/master
| 2020-03-07T04:40:19.760000 | 2018-06-14T09:34:28 | 2018-06-14T09:34:28 | 127,273,046 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kong.support.socket.helper;
import com.kong.support.exceptions.BaseException;
import com.kong.support.exceptions.socket.DataParserException;
import java.nio.charset.Charset;
/**
* 数据解析器
*/
public interface DataParser {
/**
* 解析数据之前的操作
*/
public void preParse();
/**
* 解析数据
* @param text
* @return
* @throws DataParserException
*/
public <T> T parser(Class<T> tClass, byte[] text, Charset charset) throws DataParserException;
/**
* 完成解析
* @param parseByte
* @param ex
* @return
*/
public <T> T afterParse(T parseByte, BaseException ex);
}
|
UTF-8
|
Java
| 685 |
java
|
DataParser.java
|
Java
|
[] | null |
[] |
package com.kong.support.socket.helper;
import com.kong.support.exceptions.BaseException;
import com.kong.support.exceptions.socket.DataParserException;
import java.nio.charset.Charset;
/**
* 数据解析器
*/
public interface DataParser {
/**
* 解析数据之前的操作
*/
public void preParse();
/**
* 解析数据
* @param text
* @return
* @throws DataParserException
*/
public <T> T parser(Class<T> tClass, byte[] text, Charset charset) throws DataParserException;
/**
* 完成解析
* @param parseByte
* @param ex
* @return
*/
public <T> T afterParse(T parseByte, BaseException ex);
}
| 685 | 0.633385 | 0.633385 | 32 | 19.03125 | 21.928127 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false |
15
|
8e2be1b4057a51d4e417105c99183b1c643b76c3
| 9,053,791,072,166 |
eb9f655206c43c12b497c667ba56a0d358b6bc3a
|
/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/redundantCollectionOperation/beforeAsListForEachUnused.java
|
3fbe78cbc9e5b6574afe1f5f440a7b38227a8be3
|
[
"Apache-2.0"
] |
permissive
|
JetBrains/intellij-community
|
https://github.com/JetBrains/intellij-community
|
2ed226e200ecc17c037dcddd4a006de56cd43941
|
05dbd4575d01a213f3f4d69aa4968473f2536142
|
refs/heads/master
| 2023-09-03T17:06:37.560000 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 |
Apache-2.0
| false | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | 2023-09-12T03:37:30 | 2023-09-12T06:46:46 | 4,523,919 | 15,754 | 4,972 | 237 | null | false | false |
// "Unwrap" "false"
import java.util.Arrays;
class Test {
void test(String[] data) {
List<String> list = Arrays.as<caret>List(data);
}
}
|
UTF-8
|
Java
| 145 |
java
|
beforeAsListForEachUnused.java
|
Java
|
[] | null |
[] |
// "Unwrap" "false"
import java.util.Arrays;
class Test {
void test(String[] data) {
List<String> list = Arrays.as<caret>List(data);
}
}
| 145 | 0.641379 | 0.641379 | 8 | 17.25 | 16.184483 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
15
|
22fa42d43010e5e9bdc87c22754f78af8799790c
| 9,053,791,070,204 |
8a4ae1a934e1b662dacbc82f6c9142210171c97a
|
/Objects/src/bloodlife/system/httputils2service.java
|
f71214c3d8a8f8b8603d6cd315fa83eb3f262c59
|
[] |
no_license
|
richardz14/myproject
|
https://github.com/richardz14/myproject
|
5ca31d10c279b860e421427bae89bbbc1c6dd439
|
4d70939fa902d03ce3e7bec030ed6568c1731ba8
|
refs/heads/master
| 2021-01-17T11:55:47.582000 | 2017-09-19T17:25:33 | 2017-09-19T17:25:33 | 84,049,747 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bloodlife.system;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.objects.ServiceHelper;
import anywheresoftware.b4a.debug.*;
public class httputils2service extends android.app.Service {
public static class httputils2service_BR extends android.content.BroadcastReceiver {
@Override
public void onReceive(android.content.Context context, android.content.Intent intent) {
android.content.Intent in = new android.content.Intent(context, httputils2service.class);
if (intent != null)
in.putExtra("b4a_internal_intent", intent);
context.startService(in);
}
}
static httputils2service mostCurrent;
public static BA processBA;
private ServiceHelper _service;
public static Class<?> getObject() {
return httputils2service.class;
}
@Override
public void onCreate() {
mostCurrent = this;
if (processBA == null) {
processBA = new BA(this, null, null, "bloodlife.system", "bloodlife.system.httputils2service");
if (BA.isShellModeRuntimeCheck(processBA)) {
processBA.raiseEvent2(null, true, "SHELL", false);
}
try {
Class.forName(BA.applicationContext.getPackageName() + ".main").getMethod("initializeProcessGlobals").invoke(null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
processBA.loadHtSubs(this.getClass());
ServiceHelper.init();
}
_service = new ServiceHelper(this);
processBA.service = this;
processBA.setActivityPaused(false);
if (BA.isShellModeRuntimeCheck(processBA)) {
processBA.raiseEvent2(null, true, "CREATE", true, "bloodlife.system.httputils2service", processBA, _service, anywheresoftware.b4a.keywords.Common.Density);
}
if (!false && ServiceHelper.StarterHelper.startFromServiceCreate(processBA, true) == false) {
}
else {
BA.LogInfo("** Service (httputils2service) Create **");
processBA.raiseEvent(null, "service_create");
}
processBA.runHook("oncreate", this, null);
if (false) {
if (ServiceHelper.StarterHelper.waitForLayout != null)
BA.handler.post(ServiceHelper.StarterHelper.waitForLayout);
}
}
@Override
public void onStart(android.content.Intent intent, int startId) {
onStartCommand(intent, 0, 0);
}
@Override
public int onStartCommand(final android.content.Intent intent, int flags, int startId) {
if (ServiceHelper.StarterHelper.onStartCommand(processBA))
handleStart(intent);
else {
ServiceHelper.StarterHelper.waitForLayout = new Runnable() {
public void run() {
BA.LogInfo("** Service (httputils2service) Create **");
processBA.raiseEvent(null, "service_create");
handleStart(intent);
}
};
}
processBA.runHook("onstartcommand", this, new Object[] {intent, flags, startId});
return android.app.Service.START_NOT_STICKY;
}
private void handleStart(android.content.Intent intent) {
BA.LogInfo("** Service (httputils2service) Start **");
java.lang.reflect.Method startEvent = processBA.htSubs.get("service_start");
if (startEvent != null) {
if (startEvent.getParameterTypes().length > 0) {
anywheresoftware.b4a.objects.IntentWrapper iw = new anywheresoftware.b4a.objects.IntentWrapper();
if (intent != null) {
if (intent.hasExtra("b4a_internal_intent"))
iw.setObject((android.content.Intent) intent.getParcelableExtra("b4a_internal_intent"));
else
iw.setObject(intent);
}
processBA.raiseEvent(null, "service_start", iw);
}
else {
processBA.raiseEvent(null, "service_start");
}
}
}
@Override
public android.os.IBinder onBind(android.content.Intent intent) {
return null;
}
@Override
public void onDestroy() {
BA.LogInfo("** Service (httputils2service) Destroy **");
processBA.raiseEvent(null, "service_destroy");
processBA.service = null;
mostCurrent = null;
processBA.setActivityPaused(true);
processBA.runHook("ondestroy", this, null);
}
public anywheresoftware.b4a.keywords.Common __c = null;
public static anywheresoftware.b4a.http.HttpClientWrapper _hc = null;
public static anywheresoftware.b4a.objects.collections.Map _taskidtojob = null;
public static String _tempfolder = "";
public static int _taskcounter = 0;
public bloodlife.system.main _main = null;
public bloodlife.system.login_form _login_form = null;
public bloodlife.system.create_account _create_account = null;
public bloodlife.system.menu_form _menu_form = null;
public bloodlife.system.search_frame _search_frame = null;
public bloodlife.system.help_frame _help_frame = null;
public bloodlife.system.my_profile _my_profile = null;
public bloodlife.system.about_frame _about_frame = null;
public static String _completejob(int _taskid,boolean _success,String _errormessage) throws Exception{
bloodlife.system.httpjob _job = null;
//BA.debugLineNum = 64;BA.debugLine="Sub CompleteJob(TaskId As Int, success As Boolean,";
//BA.debugLineNum = 65;BA.debugLine="Dim job As HttpJob";
_job = new bloodlife.system.httpjob();
//BA.debugLineNum = 66;BA.debugLine="job = TaskIdToJob.Get(TaskId)";
_job = (bloodlife.system.httpjob)(_taskidtojob.Get((Object)(_taskid)));
//BA.debugLineNum = 67;BA.debugLine="TaskIdToJob.Remove(TaskId)";
_taskidtojob.Remove((Object)(_taskid));
//BA.debugLineNum = 68;BA.debugLine="job.success = success";
_job._success = _success;
//BA.debugLineNum = 69;BA.debugLine="job.errorMessage = errorMessage";
_job._errormessage = _errormessage;
//BA.debugLineNum = 70;BA.debugLine="job.Complete(TaskId)";
_job._complete(_taskid);
//BA.debugLineNum = 71;BA.debugLine="End Sub";
return "";
}
public static String _hc_responseerror(anywheresoftware.b4a.http.HttpClientWrapper.HttpResponeWrapper _response,String _reason,int _statuscode,int _taskid) throws Exception{
//BA.debugLineNum = 52;BA.debugLine="Sub hc_ResponseError (Response As HttpResponse, Re";
//BA.debugLineNum = 53;BA.debugLine="If Response <> Null Then";
if (_response!= null) {
//BA.debugLineNum = 54;BA.debugLine="Try";
try { //BA.debugLineNum = 55;BA.debugLine="Log(Response.GetString(\"UTF8\"))";
anywheresoftware.b4a.keywords.Common.Log(_response.GetString("UTF8"));
}
catch (Exception e5) {
processBA.setLastException(e5); //BA.debugLineNum = 57;BA.debugLine="Log(\"Failed to read error message.\")";
anywheresoftware.b4a.keywords.Common.Log("Failed to read error message.");
};
//BA.debugLineNum = 59;BA.debugLine="Response.Release";
_response.Release();
};
//BA.debugLineNum = 61;BA.debugLine="CompleteJob(TaskId, False, Reason)";
_completejob(_taskid,anywheresoftware.b4a.keywords.Common.False,_reason);
//BA.debugLineNum = 62;BA.debugLine="End Sub";
return "";
}
public static String _hc_responsesuccess(anywheresoftware.b4a.http.HttpClientWrapper.HttpResponeWrapper _response,int _taskid) throws Exception{
//BA.debugLineNum = 39;BA.debugLine="Sub hc_ResponseSuccess (Response As HttpResponse,";
//BA.debugLineNum = 40;BA.debugLine="Response.GetAsynchronously(\"response\", File.OpenO";
_response.GetAsynchronously(processBA,"response",(java.io.OutputStream)(anywheresoftware.b4a.keywords.Common.File.OpenOutput(_tempfolder,BA.NumberToString(_taskid),anywheresoftware.b4a.keywords.Common.False).getObject()),anywheresoftware.b4a.keywords.Common.True,_taskid);
//BA.debugLineNum = 42;BA.debugLine="End Sub";
return "";
}
public static String _process_globals() throws Exception{
//BA.debugLineNum = 7;BA.debugLine="Sub Process_Globals";
//BA.debugLineNum = 8;BA.debugLine="Private hc As HttpClient";
_hc = new anywheresoftware.b4a.http.HttpClientWrapper();
//BA.debugLineNum = 9;BA.debugLine="Private TaskIdToJob As Map";
_taskidtojob = new anywheresoftware.b4a.objects.collections.Map();
//BA.debugLineNum = 10;BA.debugLine="Public TempFolder";
_tempfolder = "";
//BA.debugLineNum = 11;BA.debugLine="Private taskCounter As Int";
_taskcounter = 0;
//BA.debugLineNum = 12;BA.debugLine="End Sub";
return "";
}
public static String _response_streamfinish(boolean _success,int _taskid) throws Exception{
//BA.debugLineNum = 44;BA.debugLine="Sub Response_StreamFinish (Success As Boolean, Tas";
//BA.debugLineNum = 45;BA.debugLine="If Success Then";
if (_success) {
//BA.debugLineNum = 46;BA.debugLine="CompleteJob(TaskId, Success, \"\")";
_completejob(_taskid,_success,"");
}else {
//BA.debugLineNum = 48;BA.debugLine="CompleteJob(TaskId, Success, LastException.Messa";
_completejob(_taskid,_success,anywheresoftware.b4a.keywords.Common.LastException(processBA).getMessage());
};
//BA.debugLineNum = 50;BA.debugLine="End Sub";
return "";
}
public static String _service_create() throws Exception{
//BA.debugLineNum = 14;BA.debugLine="Sub Service_Create";
//BA.debugLineNum = 15;BA.debugLine="TempFolder = File.DirInternalCache";
_tempfolder = anywheresoftware.b4a.keywords.Common.File.getDirInternalCache();
//BA.debugLineNum = 16;BA.debugLine="hc.Initialize(\"hc\")";
_hc.Initialize("hc");
//BA.debugLineNum = 17;BA.debugLine="TaskIdToJob.Initialize";
_taskidtojob.Initialize();
//BA.debugLineNum = 18;BA.debugLine="End Sub";
return "";
}
public static String _service_destroy() throws Exception{
//BA.debugLineNum = 24;BA.debugLine="Sub Service_Destroy";
//BA.debugLineNum = 26;BA.debugLine="End Sub";
return "";
}
public static String _service_start(anywheresoftware.b4a.objects.IntentWrapper _startingintent) throws Exception{
//BA.debugLineNum = 20;BA.debugLine="Sub Service_Start (StartingIntent As Intent)";
//BA.debugLineNum = 22;BA.debugLine="End Sub";
return "";
}
public static int _submitjob(bloodlife.system.httpjob _job) throws Exception{
//BA.debugLineNum = 28;BA.debugLine="Public Sub SubmitJob(job As HttpJob) As Int";
//BA.debugLineNum = 29;BA.debugLine="taskCounter = taskCounter + 1";
_taskcounter = (int) (_taskcounter+1);
//BA.debugLineNum = 30;BA.debugLine="TaskIdToJob.Put(taskCounter, job)";
_taskidtojob.Put((Object)(_taskcounter),(Object)(_job));
//BA.debugLineNum = 31;BA.debugLine="If job.Username <> \"\" AND job.Password <> \"\" Then";
if ((_job._username).equals("") == false && (_job._password).equals("") == false) {
//BA.debugLineNum = 32;BA.debugLine="hc.ExecuteCredentials(job.GetRequest, taskCounte";
_hc.ExecuteCredentials(processBA,_job._getrequest(),_taskcounter,_job._username,_job._password);
}else {
//BA.debugLineNum = 34;BA.debugLine="hc.Execute(job.GetRequest, taskCounter)";
_hc.Execute(processBA,_job._getrequest(),_taskcounter);
};
//BA.debugLineNum = 36;BA.debugLine="Return taskCounter";
if (true) return _taskcounter;
//BA.debugLineNum = 37;BA.debugLine="End Sub";
return 0;
}
}
|
UTF-8
|
Java
| 10,793 |
java
|
httputils2service.java
|
Java
|
[] | null |
[] |
package bloodlife.system;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.objects.ServiceHelper;
import anywheresoftware.b4a.debug.*;
public class httputils2service extends android.app.Service {
public static class httputils2service_BR extends android.content.BroadcastReceiver {
@Override
public void onReceive(android.content.Context context, android.content.Intent intent) {
android.content.Intent in = new android.content.Intent(context, httputils2service.class);
if (intent != null)
in.putExtra("b4a_internal_intent", intent);
context.startService(in);
}
}
static httputils2service mostCurrent;
public static BA processBA;
private ServiceHelper _service;
public static Class<?> getObject() {
return httputils2service.class;
}
@Override
public void onCreate() {
mostCurrent = this;
if (processBA == null) {
processBA = new BA(this, null, null, "bloodlife.system", "bloodlife.system.httputils2service");
if (BA.isShellModeRuntimeCheck(processBA)) {
processBA.raiseEvent2(null, true, "SHELL", false);
}
try {
Class.forName(BA.applicationContext.getPackageName() + ".main").getMethod("initializeProcessGlobals").invoke(null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
processBA.loadHtSubs(this.getClass());
ServiceHelper.init();
}
_service = new ServiceHelper(this);
processBA.service = this;
processBA.setActivityPaused(false);
if (BA.isShellModeRuntimeCheck(processBA)) {
processBA.raiseEvent2(null, true, "CREATE", true, "bloodlife.system.httputils2service", processBA, _service, anywheresoftware.b4a.keywords.Common.Density);
}
if (!false && ServiceHelper.StarterHelper.startFromServiceCreate(processBA, true) == false) {
}
else {
BA.LogInfo("** Service (httputils2service) Create **");
processBA.raiseEvent(null, "service_create");
}
processBA.runHook("oncreate", this, null);
if (false) {
if (ServiceHelper.StarterHelper.waitForLayout != null)
BA.handler.post(ServiceHelper.StarterHelper.waitForLayout);
}
}
@Override
public void onStart(android.content.Intent intent, int startId) {
onStartCommand(intent, 0, 0);
}
@Override
public int onStartCommand(final android.content.Intent intent, int flags, int startId) {
if (ServiceHelper.StarterHelper.onStartCommand(processBA))
handleStart(intent);
else {
ServiceHelper.StarterHelper.waitForLayout = new Runnable() {
public void run() {
BA.LogInfo("** Service (httputils2service) Create **");
processBA.raiseEvent(null, "service_create");
handleStart(intent);
}
};
}
processBA.runHook("onstartcommand", this, new Object[] {intent, flags, startId});
return android.app.Service.START_NOT_STICKY;
}
private void handleStart(android.content.Intent intent) {
BA.LogInfo("** Service (httputils2service) Start **");
java.lang.reflect.Method startEvent = processBA.htSubs.get("service_start");
if (startEvent != null) {
if (startEvent.getParameterTypes().length > 0) {
anywheresoftware.b4a.objects.IntentWrapper iw = new anywheresoftware.b4a.objects.IntentWrapper();
if (intent != null) {
if (intent.hasExtra("b4a_internal_intent"))
iw.setObject((android.content.Intent) intent.getParcelableExtra("b4a_internal_intent"));
else
iw.setObject(intent);
}
processBA.raiseEvent(null, "service_start", iw);
}
else {
processBA.raiseEvent(null, "service_start");
}
}
}
@Override
public android.os.IBinder onBind(android.content.Intent intent) {
return null;
}
@Override
public void onDestroy() {
BA.LogInfo("** Service (httputils2service) Destroy **");
processBA.raiseEvent(null, "service_destroy");
processBA.service = null;
mostCurrent = null;
processBA.setActivityPaused(true);
processBA.runHook("ondestroy", this, null);
}
public anywheresoftware.b4a.keywords.Common __c = null;
public static anywheresoftware.b4a.http.HttpClientWrapper _hc = null;
public static anywheresoftware.b4a.objects.collections.Map _taskidtojob = null;
public static String _tempfolder = "";
public static int _taskcounter = 0;
public bloodlife.system.main _main = null;
public bloodlife.system.login_form _login_form = null;
public bloodlife.system.create_account _create_account = null;
public bloodlife.system.menu_form _menu_form = null;
public bloodlife.system.search_frame _search_frame = null;
public bloodlife.system.help_frame _help_frame = null;
public bloodlife.system.my_profile _my_profile = null;
public bloodlife.system.about_frame _about_frame = null;
public static String _completejob(int _taskid,boolean _success,String _errormessage) throws Exception{
bloodlife.system.httpjob _job = null;
//BA.debugLineNum = 64;BA.debugLine="Sub CompleteJob(TaskId As Int, success As Boolean,";
//BA.debugLineNum = 65;BA.debugLine="Dim job As HttpJob";
_job = new bloodlife.system.httpjob();
//BA.debugLineNum = 66;BA.debugLine="job = TaskIdToJob.Get(TaskId)";
_job = (bloodlife.system.httpjob)(_taskidtojob.Get((Object)(_taskid)));
//BA.debugLineNum = 67;BA.debugLine="TaskIdToJob.Remove(TaskId)";
_taskidtojob.Remove((Object)(_taskid));
//BA.debugLineNum = 68;BA.debugLine="job.success = success";
_job._success = _success;
//BA.debugLineNum = 69;BA.debugLine="job.errorMessage = errorMessage";
_job._errormessage = _errormessage;
//BA.debugLineNum = 70;BA.debugLine="job.Complete(TaskId)";
_job._complete(_taskid);
//BA.debugLineNum = 71;BA.debugLine="End Sub";
return "";
}
public static String _hc_responseerror(anywheresoftware.b4a.http.HttpClientWrapper.HttpResponeWrapper _response,String _reason,int _statuscode,int _taskid) throws Exception{
//BA.debugLineNum = 52;BA.debugLine="Sub hc_ResponseError (Response As HttpResponse, Re";
//BA.debugLineNum = 53;BA.debugLine="If Response <> Null Then";
if (_response!= null) {
//BA.debugLineNum = 54;BA.debugLine="Try";
try { //BA.debugLineNum = 55;BA.debugLine="Log(Response.GetString(\"UTF8\"))";
anywheresoftware.b4a.keywords.Common.Log(_response.GetString("UTF8"));
}
catch (Exception e5) {
processBA.setLastException(e5); //BA.debugLineNum = 57;BA.debugLine="Log(\"Failed to read error message.\")";
anywheresoftware.b4a.keywords.Common.Log("Failed to read error message.");
};
//BA.debugLineNum = 59;BA.debugLine="Response.Release";
_response.Release();
};
//BA.debugLineNum = 61;BA.debugLine="CompleteJob(TaskId, False, Reason)";
_completejob(_taskid,anywheresoftware.b4a.keywords.Common.False,_reason);
//BA.debugLineNum = 62;BA.debugLine="End Sub";
return "";
}
public static String _hc_responsesuccess(anywheresoftware.b4a.http.HttpClientWrapper.HttpResponeWrapper _response,int _taskid) throws Exception{
//BA.debugLineNum = 39;BA.debugLine="Sub hc_ResponseSuccess (Response As HttpResponse,";
//BA.debugLineNum = 40;BA.debugLine="Response.GetAsynchronously(\"response\", File.OpenO";
_response.GetAsynchronously(processBA,"response",(java.io.OutputStream)(anywheresoftware.b4a.keywords.Common.File.OpenOutput(_tempfolder,BA.NumberToString(_taskid),anywheresoftware.b4a.keywords.Common.False).getObject()),anywheresoftware.b4a.keywords.Common.True,_taskid);
//BA.debugLineNum = 42;BA.debugLine="End Sub";
return "";
}
public static String _process_globals() throws Exception{
//BA.debugLineNum = 7;BA.debugLine="Sub Process_Globals";
//BA.debugLineNum = 8;BA.debugLine="Private hc As HttpClient";
_hc = new anywheresoftware.b4a.http.HttpClientWrapper();
//BA.debugLineNum = 9;BA.debugLine="Private TaskIdToJob As Map";
_taskidtojob = new anywheresoftware.b4a.objects.collections.Map();
//BA.debugLineNum = 10;BA.debugLine="Public TempFolder";
_tempfolder = "";
//BA.debugLineNum = 11;BA.debugLine="Private taskCounter As Int";
_taskcounter = 0;
//BA.debugLineNum = 12;BA.debugLine="End Sub";
return "";
}
public static String _response_streamfinish(boolean _success,int _taskid) throws Exception{
//BA.debugLineNum = 44;BA.debugLine="Sub Response_StreamFinish (Success As Boolean, Tas";
//BA.debugLineNum = 45;BA.debugLine="If Success Then";
if (_success) {
//BA.debugLineNum = 46;BA.debugLine="CompleteJob(TaskId, Success, \"\")";
_completejob(_taskid,_success,"");
}else {
//BA.debugLineNum = 48;BA.debugLine="CompleteJob(TaskId, Success, LastException.Messa";
_completejob(_taskid,_success,anywheresoftware.b4a.keywords.Common.LastException(processBA).getMessage());
};
//BA.debugLineNum = 50;BA.debugLine="End Sub";
return "";
}
public static String _service_create() throws Exception{
//BA.debugLineNum = 14;BA.debugLine="Sub Service_Create";
//BA.debugLineNum = 15;BA.debugLine="TempFolder = File.DirInternalCache";
_tempfolder = anywheresoftware.b4a.keywords.Common.File.getDirInternalCache();
//BA.debugLineNum = 16;BA.debugLine="hc.Initialize(\"hc\")";
_hc.Initialize("hc");
//BA.debugLineNum = 17;BA.debugLine="TaskIdToJob.Initialize";
_taskidtojob.Initialize();
//BA.debugLineNum = 18;BA.debugLine="End Sub";
return "";
}
public static String _service_destroy() throws Exception{
//BA.debugLineNum = 24;BA.debugLine="Sub Service_Destroy";
//BA.debugLineNum = 26;BA.debugLine="End Sub";
return "";
}
public static String _service_start(anywheresoftware.b4a.objects.IntentWrapper _startingintent) throws Exception{
//BA.debugLineNum = 20;BA.debugLine="Sub Service_Start (StartingIntent As Intent)";
//BA.debugLineNum = 22;BA.debugLine="End Sub";
return "";
}
public static int _submitjob(bloodlife.system.httpjob _job) throws Exception{
//BA.debugLineNum = 28;BA.debugLine="Public Sub SubmitJob(job As HttpJob) As Int";
//BA.debugLineNum = 29;BA.debugLine="taskCounter = taskCounter + 1";
_taskcounter = (int) (_taskcounter+1);
//BA.debugLineNum = 30;BA.debugLine="TaskIdToJob.Put(taskCounter, job)";
_taskidtojob.Put((Object)(_taskcounter),(Object)(_job));
//BA.debugLineNum = 31;BA.debugLine="If job.Username <> \"\" AND job.Password <> \"\" Then";
if ((_job._username).equals("") == false && (_job._password).equals("") == false) {
//BA.debugLineNum = 32;BA.debugLine="hc.ExecuteCredentials(job.GetRequest, taskCounte";
_hc.ExecuteCredentials(processBA,_job._getrequest(),_taskcounter,_job._username,_job._password);
}else {
//BA.debugLineNum = 34;BA.debugLine="hc.Execute(job.GetRequest, taskCounter)";
_hc.Execute(processBA,_job._getrequest(),_taskcounter);
};
//BA.debugLineNum = 36;BA.debugLine="Return taskCounter";
if (true) return _taskcounter;
//BA.debugLineNum = 37;BA.debugLine="End Sub";
return 0;
}
}
| 10,793 | 0.715371 | 0.702307 | 237 | 44.540085 | 36.127811 | 272 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.78481 | false | false |
15
|
254bc1380080ff87573749e6a98023845aba1ef5
| 16,767,552,359,744 |
86118440c28bbf7e47f2f4ee6991742aaebe9dba
|
/src/test/java/application/repositories/UserRepositoryTest.java
|
cb26ac68d3a5f069461aee9c1f9d4d940052cefe
|
[] |
no_license
|
ErikPereiraAlves/Spring-Boot-Maven-H2-AngularJS-HTML-Users
|
https://github.com/ErikPereiraAlves/Spring-Boot-Maven-H2-AngularJS-HTML-Users
|
26f9fb45151945e7f95ce109c1349b39e19d4990
|
0078923f9af43861f9d66d52d426a7210ebe92e2
|
refs/heads/master
| 2021-01-24T12:19:43.210000 | 2018-02-27T14:00:52 | 2018-02-27T14:00:52 | 123,131,041 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package application.repositories;
import com.erikalves.application.model.User;
import com.erikalves.application.repositories.UserRepository;
import com.erikalves.application.utils.Util;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.List;
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest {
private static final Logger LOGGER = LoggerFactory.getLogger(UserRepositoryTest.class);
@Autowired(required = true)
UserRepository repository;
User createdUser;
Long existingUserId =1l;
@Before
public void begin() {
createdUser = new User();
createdUser.setUserName("Erik Alves");
}
@Test
public void shouldCreateUpdateDeleteUser() {
shouldCreateUser();
shouldUpdateUser();
shouldDeleteUser();
}
public void shouldCreateUser() {
User localUser = repository.save(createdUser);
LOGGER.debug("saved entity ID {}", localUser);
Assert.assertNotNull(localUser.getUserId());
LOGGER.debug(" *** CREATE RESULT *** {}", localUser);
}
public void shouldDeleteUser() {
Long id = createdUser.getUserId();
repository.delete(id);
repository.flush();
User deletedUser = repository.findOne(id);
Assert.assertEquals(null, deletedUser);
LOGGER.debug(" *** DELETE RESULT *** {}", deletedUser);
}
public void shouldUpdateUser() {
createdUser.setUserName("Name updated by JUNIT - John Doe is my name now");
User updatedUser = repository.save(createdUser);
Assert.assertTrue(null != updatedUser);
Assert.assertTrue("Name updated by JUNIT - John Doe is my name now".equals(updatedUser.getUserName()));
LOGGER.debug(" *** UPDATE RESULT *** {}", updatedUser.getUserName());
}
@Test
public void shouldFindSpecificUser() {
User findUser = repository.getOne(existingUserId);
Assert.assertTrue(null != findUser);
LOGGER.debug(" *** RESULT *** {}", findUser.toString());
}
@Test
public void shouldFindAllUsers() {
List<User> list = repository.findAll();
LOGGER.debug(" *** LIST *** {}", list);
Assert.assertTrue(null != list);
for(User user: list){
Assert.assertTrue(null != user);
Assert.assertTrue(null != user.getUserId());
LOGGER.debug(" *** RESULT *** {}", user.toString());
}
}
}
|
UTF-8
|
Java
| 2,804 |
java
|
UserRepositoryTest.java
|
Java
|
[
{
"context": "er = new User();\n createdUser.setUserName(\"Erik Alves\");\n\n }\n\n @Test\n public void shouldCreate",
"end": 1002,
"score": 0.9966900944709778,
"start": 992,
"tag": "NAME",
"value": "Erik Alves"
},
{
"context": " createdUser.setUserName(\"Name updated by JUNIT - John Doe is my name now\");\n User updatedUser = repo",
"end": 1849,
"score": 0.9996196031570435,
"start": 1841,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " Assert.assertTrue(\"Name updated by JUNIT - John Doe is my name now\".equals(updatedUser.getUserName())",
"end": 2032,
"score": 0.998853325843811,
"start": 2024,
"tag": "NAME",
"value": "John Doe"
}
] | null |
[] |
package application.repositories;
import com.erikalves.application.model.User;
import com.erikalves.application.repositories.UserRepository;
import com.erikalves.application.utils.Util;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.List;
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest {
private static final Logger LOGGER = LoggerFactory.getLogger(UserRepositoryTest.class);
@Autowired(required = true)
UserRepository repository;
User createdUser;
Long existingUserId =1l;
@Before
public void begin() {
createdUser = new User();
createdUser.setUserName("<NAME>");
}
@Test
public void shouldCreateUpdateDeleteUser() {
shouldCreateUser();
shouldUpdateUser();
shouldDeleteUser();
}
public void shouldCreateUser() {
User localUser = repository.save(createdUser);
LOGGER.debug("saved entity ID {}", localUser);
Assert.assertNotNull(localUser.getUserId());
LOGGER.debug(" *** CREATE RESULT *** {}", localUser);
}
public void shouldDeleteUser() {
Long id = createdUser.getUserId();
repository.delete(id);
repository.flush();
User deletedUser = repository.findOne(id);
Assert.assertEquals(null, deletedUser);
LOGGER.debug(" *** DELETE RESULT *** {}", deletedUser);
}
public void shouldUpdateUser() {
createdUser.setUserName("Name updated by JUNIT - <NAME> is my name now");
User updatedUser = repository.save(createdUser);
Assert.assertTrue(null != updatedUser);
Assert.assertTrue("Name updated by JUNIT - <NAME> is my name now".equals(updatedUser.getUserName()));
LOGGER.debug(" *** UPDATE RESULT *** {}", updatedUser.getUserName());
}
@Test
public void shouldFindSpecificUser() {
User findUser = repository.getOne(existingUserId);
Assert.assertTrue(null != findUser);
LOGGER.debug(" *** RESULT *** {}", findUser.toString());
}
@Test
public void shouldFindAllUsers() {
List<User> list = repository.findAll();
LOGGER.debug(" *** LIST *** {}", list);
Assert.assertTrue(null != list);
for(User user: list){
Assert.assertTrue(null != user);
Assert.assertTrue(null != user.getUserId());
LOGGER.debug(" *** RESULT *** {}", user.toString());
}
}
}
| 2,796 | 0.663338 | 0.661912 | 97 | 27.917526 | 25.028919 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57732 | false | false |
15
|
243498030401d188bc3a3030a35c6a860f798874
| 6,210,522,738,757 |
61234ad4ce9c1a579986116a59423040e580d3c0
|
/app/src/seeker/java/com/wecare/android/ui/main/order/OrderFragmentModule.java
|
f558fb552d32c254787e2f81d3e62fd41de0a0eb
|
[] |
no_license
|
SS-Muhammad-Ateeq/wecares-android_app-35706a163db3
|
https://github.com/SS-Muhammad-Ateeq/wecares-android_app-35706a163db3
|
7f8f35ca57d75ee96694526b880c172a0cd36e9c
|
93427c8e6eda267d72c1370b08ed5e114d992fe9
|
refs/heads/master
| 2023-01-11T13:35:25.515000 | 2020-11-10T22:20:38 | 2020-11-10T22:20:38 | 311,798,467 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wecare.android.ui.main.order;
import dagger.Module;
import dagger.Provides;
@Module
public class OrderFragmentModule {
@Provides
OrderPagerAdapter provideOrderPagerAdapter(OrderFragment fragment) {
return new OrderPagerAdapter(fragment.getChildFragmentManager(), fragment.getBaseActivity());
}
}
|
UTF-8
|
Java
| 332 |
java
|
OrderFragmentModule.java
|
Java
|
[] | null |
[] |
package com.wecare.android.ui.main.order;
import dagger.Module;
import dagger.Provides;
@Module
public class OrderFragmentModule {
@Provides
OrderPagerAdapter provideOrderPagerAdapter(OrderFragment fragment) {
return new OrderPagerAdapter(fragment.getChildFragmentManager(), fragment.getBaseActivity());
}
}
| 332 | 0.777108 | 0.777108 | 14 | 22.714285 | 29.535521 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false |
15
|
0f55808d35523afcfaa7c3ed85354e3e6ffec6e2
| 10,591,389,408,477 |
e44abd8bbc2d245db14099bf0406bb021cecad26
|
/Temp2/app/src/main/java/haha/MainActivity.java
|
292629d0cd5c4973dbc7d00d9acc50e394ca50c7
|
[] |
no_license
|
ymeddmn/Rubbsh
|
https://github.com/ymeddmn/Rubbsh
|
9007e2be6bc43da49ae4faf70f463511ee951c5a
|
406207e4e6c521c310b19be49753d36ede29400f
|
refs/heads/master
| 2022-12-07T09:36:01.137000 | 2020-08-23T00:21:36 | 2020-08-23T00:21:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package haha;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.haha.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getPackage();
}
private void getPackage() {
PackageManager pckMan = getPackageManager();
ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
List<PackageInfo> packageInfo = pckMan.getInstalledPackages(0);
for (PackageInfo info : packageInfo) {
if(Build.VERSION.SDK_INT>=28){
Log.e("包信息",info.packageName+info.getLongVersionCode()+"哈哈");
}else {
Log.e("包信息",info.packageName+info.versionName);
}
}
}
}
|
UTF-8
|
Java
| 1,175 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package haha;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.haha.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getPackage();
}
private void getPackage() {
PackageManager pckMan = getPackageManager();
ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
List<PackageInfo> packageInfo = pckMan.getInstalledPackages(0);
for (PackageInfo info : packageInfo) {
if(Build.VERSION.SDK_INT>=28){
Log.e("包信息",info.packageName+info.getLongVersionCode()+"哈哈");
}else {
Log.e("包信息",info.packageName+info.versionName);
}
}
}
}
| 1,175 | 0.685073 | 0.681622 | 41 | 27.268293 | 24.063965 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.585366 | false | false |
15
|
c1ad3c460c8fb885a413ae24616ad867396ec81c
| 10,591,389,411,727 |
a2ebfe0cfcbb2796f96e370850c4eb9801384451
|
/ic-search/ic-search-api/src/main/java/com/yt/ic/search/api/SearchIndexService.java
|
fde897468f29e231cd67205637a4368ca1010674
|
[] |
no_license
|
dliang123/search
|
https://github.com/dliang123/search
|
468107b4cdc52887b27c9df41428b53cd48b67eb
|
2eeefdc35b95e49f7975eb56db917422f5b90cfc
|
refs/heads/master
| 2021-01-23T14:16:33.131000 | 2017-11-19T12:05:44 | 2017-11-19T12:05:44 | 102,681,489 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yt.ic.search.api;
import com.yt.ic.search.model.Index;
import com.yt.ic.search.model.SearchMode;
import java.io.IOException;
import java.util.List;
/**
* 搜索索引服务
*
*/
public interface SearchIndexService {
/**
* 根据输入范围和词句查询索引,返回结果按照评分高->低排序
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
* @param queryString 查询词句
* @param indexField 索引字段
* @param maxSize 返回索引最大条数,如果{@code maxSize <= 0 || maxSize > 100},使用默认值10
* @return 索引列表,按照评分高->低排序
*/
List<Index> queryIndexes(String scope, String queryString, String indexField,
SearchMode searchMode, int maxSize) throws IOException;
// /**
// * 根据输入范围和词句查询索引,分页返回,总条数最大值为100,返回结果按照评分高->低排序
// * @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
// * @param queryString 查询词句
// * @param indexField 索引字段
// * @param pageRequest 分页请求
// * @return
// */
// PageCustom<Index> queryIndexes(
// String scope, String queryString, String indexField, SearchMode searchMode,
// PageRequestCustom pageRequest) throws IOException;
/**
* 删除指定scope的全部索引
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
*/
void deleteAllIndexes(String scope) throws IOException;
/**
* 添加索引
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
* @param index 索引对象
*/
void addIndex(String scope, Index index) throws IOException;
/**
* 添加索引
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
* @param fields 索引字段列表
*/
// void addIndex(String scope, Iterable<IndexField> fields) throws IOException;
/**
* 批量添加索引
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
* @param indexes 索引列表
*/
void addIndexes(String scope, Iterable<Index> indexes) throws IOException;
}
|
UTF-8
|
Java
| 2,363 |
java
|
SearchIndexService.java
|
Java
|
[] | null |
[] |
package com.yt.ic.search.api;
import com.yt.ic.search.model.Index;
import com.yt.ic.search.model.SearchMode;
import java.io.IOException;
import java.util.List;
/**
* 搜索索引服务
*
*/
public interface SearchIndexService {
/**
* 根据输入范围和词句查询索引,返回结果按照评分高->低排序
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
* @param queryString 查询词句
* @param indexField 索引字段
* @param maxSize 返回索引最大条数,如果{@code maxSize <= 0 || maxSize > 100},使用默认值10
* @return 索引列表,按照评分高->低排序
*/
List<Index> queryIndexes(String scope, String queryString, String indexField,
SearchMode searchMode, int maxSize) throws IOException;
// /**
// * 根据输入范围和词句查询索引,分页返回,总条数最大值为100,返回结果按照评分高->低排序
// * @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
// * @param queryString 查询词句
// * @param indexField 索引字段
// * @param pageRequest 分页请求
// * @return
// */
// PageCustom<Index> queryIndexes(
// String scope, String queryString, String indexField, SearchMode searchMode,
// PageRequestCustom pageRequest) throws IOException;
/**
* 删除指定scope的全部索引
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
*/
void deleteAllIndexes(String scope) throws IOException;
/**
* 添加索引
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
* @param index 索引对象
*/
void addIndex(String scope, Index index) throws IOException;
/**
* 添加索引
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
* @param fields 索引字段列表
*/
// void addIndex(String scope, Iterable<IndexField> fields) throws IOException;
/**
* 批量添加索引
* @param scope 索引范围,建立所以时,不同的scope会建立不同的索引
* @param indexes 索引列表
*/
void addIndexes(String scope, Iterable<Index> indexes) throws IOException;
}
| 2,363 | 0.650589 | 0.645541 | 65 | 26.446154 | 25.233086 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.369231 | false | false |
15
|
cf79707421ce1648e9b7b95019f239419628dec9
| 28,260,884,847,140 |
3b7b56cbc3aa74e8803327bbf77c57f460eb368c
|
/jdk12-reference/src/main/java/org/jstlang/domain/definition/step/StringCaseDef.java
|
b64bd484b668f20ec286a369030e8a0012489551
|
[
"MIT"
] |
permissive
|
michelbetancourt/jstl
|
https://github.com/michelbetancourt/jstl
|
66842adfc300b9e69cf99dbb6b023e3f1918d84b
|
0b35081ff6a8dff0a958c1caa7d58f13f196443c
|
refs/heads/master
| 2020-06-29T14:35:59.415000 | 2019-11-26T02:48:36 | 2019-11-26T02:48:36 | 200,561,894 | 0 | 1 |
MIT
| false | 2019-10-10T02:56:32 | 2019-08-05T01:32:37 | 2019-10-06T23:06:59 | 2019-10-10T02:56:32 | 243 | 0 | 1 | 3 |
Java
| false | false |
package org.jstlang.domain.definition.step;
public enum StringCaseDef {
upper, lower;
}
|
UTF-8
|
Java
| 94 |
java
|
StringCaseDef.java
|
Java
|
[] | null |
[] |
package org.jstlang.domain.definition.step;
public enum StringCaseDef {
upper, lower;
}
| 94 | 0.744681 | 0.744681 | 6 | 14.666667 | 16.213848 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
15
|
bb67bbbf9585160278c30fec95f53e1e5e4ada25
| 841,813,654,930 |
d8ab248ae5a8afb654bdd3f18e390b1cf3e2c0ca
|
/MainProject/com/pcmsolutions/device/EMU/E4/SampleClassManager.java
|
9a4a6142a57d5b7623c558a4d415a61f08540e76
|
[] |
no_license
|
nico75000/zoeos
|
https://github.com/nico75000/zoeos
|
e2391f8f13f672e1d1c536cc2299878e38e81ede
|
a8853f8cf71556693931b3647d30741fa6260b07
|
refs/heads/master
| 2021-01-01T03:44:21.813000 | 2009-11-05T03:48:22 | 2009-11-05T03:48:22 | 56,063,868 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pcmsolutions.device.EMU.E4;
import com.pcmsolutions.device.EMU.E4.sample.SampleModel;
import com.pcmsolutions.device.EMU.E4.sample.ReadableSample;
import java.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: pmeehan
* Date: 24-May-2003
* Time: 12:13:42
* To change this template use Options | File Templates.
*/
class SampleClassManager {
private final static ArrayList profiles = new ArrayList();
public static void addSampleClass(Class sampleClass, String prefix) {
if (!SampleModel.class.isAssignableFrom(sampleClass))
throw new IllegalArgumentException("Invalid sample class - must implement SampleModel");
if (!ReadableSample.class.isAssignableFrom(sampleClass))
throw new IllegalArgumentException("Invalid sample class - must implement ReadableSample");
profiles.add(new SampleClassProfile(sampleClass, prefix));
}
public static SampleModel getMostDerivedSampleInstance(SampleModel baseClass, String name) throws InstantiationException, IllegalAccessException {
Class[] ca = getAllSampleClasses(name);
Class candidate = baseClass.getClass();
for (int i = 0, n = ca.length; i < n; i++) {
if (ca[i].isInstance(baseClass)) // ca[i] guaranteed non-null by virtue of addSampleClass semantics
candidate = mostDerived(ca[i], candidate);
}
if (candidate != baseClass.getClass()) {
SampleModel pm = (SampleModel) candidate.newInstance();
pm.setSample(baseClass.getSample());
pm.setSampleContext(baseClass.getSampleContext());
return (ReadableSample)pm;
}
return baseClass;
}
private static Class[] getAllSampleClasses(String name) {
ArrayList classes = new ArrayList();
SampleClassProfile pcp;
String prefix;
for (int i = 0, n = profiles.size(); i < n; i++) {
pcp = (SampleClassProfile) profiles.get(i);
prefix = pcp.getPrefix();
if (prefix == null || name.indexOf(prefix) == 0)
classes.add(pcp.getSampleClass());
}
Class[] ca = new Class[classes.size()];
return (Class[]) classes.toArray(ca);
}
private static Class mostDerived(Class a, Class b) {
if (a == null && b != null)
return b;
if (a != null && b == null)
return a;
if (a == null && b == null)
return a;
if (a.isAssignableFrom(b))
return b;
return a;
}
private static class SampleClassProfile {
private Class sampleClass;
private String prefix;
public SampleClassProfile(Class sampleClass, String prefix) {
this.prefix = prefix;
this.sampleClass = sampleClass;
}
public String getPrefix() {
return prefix;
}
public Class getSampleClass() {
return sampleClass;
}
public SampleModel getInstance() {
return null;
}
}
}
|
UTF-8
|
Java
| 3,174 |
java
|
SampleClassManager.java
|
Java
|
[
{
"context": "st;\r\n\r\n/**\r\n * Created by IntelliJ IDEA.\r\n * User: pmeehan\r\n * Date: 24-May-2003\r\n * Time: 12:13:42\r\n * To c",
"end": 250,
"score": 0.9996597766876221,
"start": 243,
"tag": "USERNAME",
"value": "pmeehan"
}
] | null |
[] |
package com.pcmsolutions.device.EMU.E4;
import com.pcmsolutions.device.EMU.E4.sample.SampleModel;
import com.pcmsolutions.device.EMU.E4.sample.ReadableSample;
import java.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: pmeehan
* Date: 24-May-2003
* Time: 12:13:42
* To change this template use Options | File Templates.
*/
class SampleClassManager {
private final static ArrayList profiles = new ArrayList();
public static void addSampleClass(Class sampleClass, String prefix) {
if (!SampleModel.class.isAssignableFrom(sampleClass))
throw new IllegalArgumentException("Invalid sample class - must implement SampleModel");
if (!ReadableSample.class.isAssignableFrom(sampleClass))
throw new IllegalArgumentException("Invalid sample class - must implement ReadableSample");
profiles.add(new SampleClassProfile(sampleClass, prefix));
}
public static SampleModel getMostDerivedSampleInstance(SampleModel baseClass, String name) throws InstantiationException, IllegalAccessException {
Class[] ca = getAllSampleClasses(name);
Class candidate = baseClass.getClass();
for (int i = 0, n = ca.length; i < n; i++) {
if (ca[i].isInstance(baseClass)) // ca[i] guaranteed non-null by virtue of addSampleClass semantics
candidate = mostDerived(ca[i], candidate);
}
if (candidate != baseClass.getClass()) {
SampleModel pm = (SampleModel) candidate.newInstance();
pm.setSample(baseClass.getSample());
pm.setSampleContext(baseClass.getSampleContext());
return (ReadableSample)pm;
}
return baseClass;
}
private static Class[] getAllSampleClasses(String name) {
ArrayList classes = new ArrayList();
SampleClassProfile pcp;
String prefix;
for (int i = 0, n = profiles.size(); i < n; i++) {
pcp = (SampleClassProfile) profiles.get(i);
prefix = pcp.getPrefix();
if (prefix == null || name.indexOf(prefix) == 0)
classes.add(pcp.getSampleClass());
}
Class[] ca = new Class[classes.size()];
return (Class[]) classes.toArray(ca);
}
private static Class mostDerived(Class a, Class b) {
if (a == null && b != null)
return b;
if (a != null && b == null)
return a;
if (a == null && b == null)
return a;
if (a.isAssignableFrom(b))
return b;
return a;
}
private static class SampleClassProfile {
private Class sampleClass;
private String prefix;
public SampleClassProfile(Class sampleClass, String prefix) {
this.prefix = prefix;
this.sampleClass = sampleClass;
}
public String getPrefix() {
return prefix;
}
public Class getSampleClass() {
return sampleClass;
}
public SampleModel getInstance() {
return null;
}
}
}
| 3,174 | 0.594833 | 0.589162 | 93 | 32.129032 | 28.807566 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55914 | false | false |
15
|
0d9d3e134947aa066cff282ee550687a4359a895
| 27,788,438,476,172 |
606feacf003e5299617db6596cdce2417df2b768
|
/VallaHackathon/app/src/main/java/com/obturecode/vallahackathon/domain/GetInfoPhoto.java
|
a7348a2027f23377b3ce831911ecd2676524564b
|
[] |
no_license
|
migueltg/arquitecture-example
|
https://github.com/migueltg/arquitecture-example
|
69af835213580f72f283bfbb32992c5ad26ec6d2
|
8952c5cdf3e56601f1f68ac0284ba3526e074073
|
refs/heads/master
| 2020-12-01T01:14:18.468000 | 2015-03-04T17:05:09 | 2015-03-04T17:05:09 | 31,678,297 | 2 | 0 | null | true | 2015-03-04T20:27:57 | 2015-03-04T20:27:55 | 2015-03-04T20:27:56 | 2015-03-04T17:05:09 | 0 | 0 | 0 | 0 |
Java
| null | null |
package com.obturecode.vallahackathon.domain;
import com.obturecode.vallahackathon.data.error.ApiError;
import com.obturecode.vallahackathon.data.error.ParserError;
import com.obturecode.vallahackathon.data.error.ResponseError;
import com.obturecode.vallahackathon.data.getExifPhoto;
import com.obturecode.vallahackathon.domain.entity.Exif;
import com.obturecode.vallahackathon.domain.entity.Photo;
import com.obturecode.vallahackathon.domain.error.GenericError;
import com.obturecode.vallahackathon.domain.error.InternetError;
import com.obturecode.vallahackathon.domain.error.PermissionError;
/**
* Created by husky on 02/03/15.
*/
public class GetInfoPhoto {
public interface GetInfoPhotoDelegate{
public void GetInfoPhotoResult(Photo photo);
public void GetInfoPhotoError(Error e);
}
private GetInfoPhotoDelegate delegate;
private getExifPhoto data;
private Photo photo;
public void get(Photo photo, GetInfoPhotoDelegate delegate){
this.delegate = delegate;
this.photo = photo;
data = new getExifPhoto();
data.get(photo,new getExifPhoto.getExifPhotoDelegate(){
@Override
public void exifPhotoResult(Exif exif) {
GetInfoPhoto.this.photo.setExif(exif);
GetInfoPhoto.this.delegate.GetInfoPhotoResult(GetInfoPhoto.this.photo);
}
@Override
public void exifPhotoError(Error e) {
if(e instanceof ParserError || e instanceof ResponseError)
GetInfoPhoto.this.delegate.GetInfoPhotoError(new GenericError());
else if(e instanceof ApiError)
GetInfoPhoto.this.delegate.GetInfoPhotoError(new PermissionError());
else
GetInfoPhoto.this.delegate.GetInfoPhotoError(new InternetError());
}
}
);
}
public void cancel(){
data.cancel();
data= null;
}
}
|
UTF-8
|
Java
| 2,096 |
java
|
GetInfoPhoto.java
|
Java
|
[
{
"context": "n.domain.error.PermissionError;\n\n/**\n * Created by husky on 02/03/15.\n */\npublic class GetInfoPhoto {\n\n ",
"end": 620,
"score": 0.9995329976081848,
"start": 615,
"tag": "USERNAME",
"value": "husky"
}
] | null |
[] |
package com.obturecode.vallahackathon.domain;
import com.obturecode.vallahackathon.data.error.ApiError;
import com.obturecode.vallahackathon.data.error.ParserError;
import com.obturecode.vallahackathon.data.error.ResponseError;
import com.obturecode.vallahackathon.data.getExifPhoto;
import com.obturecode.vallahackathon.domain.entity.Exif;
import com.obturecode.vallahackathon.domain.entity.Photo;
import com.obturecode.vallahackathon.domain.error.GenericError;
import com.obturecode.vallahackathon.domain.error.InternetError;
import com.obturecode.vallahackathon.domain.error.PermissionError;
/**
* Created by husky on 02/03/15.
*/
public class GetInfoPhoto {
public interface GetInfoPhotoDelegate{
public void GetInfoPhotoResult(Photo photo);
public void GetInfoPhotoError(Error e);
}
private GetInfoPhotoDelegate delegate;
private getExifPhoto data;
private Photo photo;
public void get(Photo photo, GetInfoPhotoDelegate delegate){
this.delegate = delegate;
this.photo = photo;
data = new getExifPhoto();
data.get(photo,new getExifPhoto.getExifPhotoDelegate(){
@Override
public void exifPhotoResult(Exif exif) {
GetInfoPhoto.this.photo.setExif(exif);
GetInfoPhoto.this.delegate.GetInfoPhotoResult(GetInfoPhoto.this.photo);
}
@Override
public void exifPhotoError(Error e) {
if(e instanceof ParserError || e instanceof ResponseError)
GetInfoPhoto.this.delegate.GetInfoPhotoError(new GenericError());
else if(e instanceof ApiError)
GetInfoPhoto.this.delegate.GetInfoPhotoError(new PermissionError());
else
GetInfoPhoto.this.delegate.GetInfoPhotoError(new InternetError());
}
}
);
}
public void cancel(){
data.cancel();
data= null;
}
}
| 2,096 | 0.645038 | 0.642176 | 56 | 36.392857 | 28.173365 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535714 | false | false |
15
|
b67102511ceac683a800854b0f03b12e58550c24
| 27,797,028,342,770 |
55b577e5a9a942eed0348af956f1369f29844e75
|
/jpa/src/main/java/Task1/domain/dto/RoadCellDTO.java
|
9ba84be14e82de5a56b1e1aca366c05b5df854c8
|
[] |
no_license
|
AnnaAndropova/CarTraffic
|
https://github.com/AnnaAndropova/CarTraffic
|
3242b74421e95ad37b257bb21a10e4c684ce9bf8
|
21a54174536d7ec2e8d0bcf9835ec6bbd234883c
|
refs/heads/master
| 2023-05-09T04:52:46.793000 | 2021-06-04T20:42:54 | 2021-06-04T20:42:54 | 347,173,027 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Task1.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RoadCellDTO {
private Integer id;
private Integer car;
private Integer roadId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCar() {
return car;
}
public void setCar(Integer car) {
this.car = car;
}
public Integer getRoadId() {
return roadId;
}
public void setRoadId(Integer roadId) {
this.roadId = roadId;
}
}
|
UTF-8
|
Java
| 657 |
java
|
RoadCellDTO.java
|
Java
|
[] | null |
[] |
package Task1.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RoadCellDTO {
private Integer id;
private Integer car;
private Integer roadId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCar() {
return car;
}
public void setCar(Integer car) {
this.car = car;
}
public Integer getRoadId() {
return roadId;
}
public void setRoadId(Integer roadId) {
this.roadId = roadId;
}
}
| 657 | 0.630137 | 0.628615 | 39 | 15.846154 | 13.154971 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
15
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.