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
sequence | 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
sequence | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f8d8a6a5e1633a2bd2860a7623996b9d80c1e72b | 7,155,415,516,348 | 584dca5b86c1c790cc4fab2de02c162954c3ddd3 | /src/main/java/de/drentech/innihald/documentrepository/ocr/OcrUtil.java | b3eededaa1428394e792c278d9f65e2be7ace9d5 | [
"MIT"
] | permissive | Innihald/document_repository | https://github.com/Innihald/document_repository | c4fb9c8e7433cab554931d02a28fa1f167d72be6 | b7b9dbcc4c94d1e1e481ad278ba63e19ccbeedef | refs/heads/master | 2022-12-12T15:01:04.253000 | 2020-09-11T10:39:02 | 2020-09-11T10:39:02 | 294,129,419 | 0 | 0 | null | false | 2020-09-09T19:30:32 | 2020-09-09T13:59:33 | 2020-09-09T14:03:12 | 2020-09-09T19:30:31 | 82 | 0 | 0 | 0 | Java | false | false | package de.drentech.innihald.documentrepository.ocr;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.enterprise.context.ApplicationScoped;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
@ApplicationScoped
public class OcrUtil {
public String getOcrTextFromPdf(PDDocument pdf, String languageCode) throws IOException {
PDFRenderer renderer = new PDFRenderer(pdf);
StringBuilder ocrText = new StringBuilder();
for (int pageNumber = 0; pageNumber < pdf.getNumberOfPages(); pageNumber++) {
BufferedImage pageImage = renderer.renderImageWithDPI(pageNumber, 300, ImageType.RGB); //TODO: use this to generate thumbnail
File tempFile = File.createTempFile("tempfile_" + pageNumber, ".png");
ImageIO.write(pageImage, "png", tempFile);
String ocrCommand = String.format("tesseract -l %s --oem 1 %s -", languageCode, tempFile.getAbsolutePath());
System.out.println("Command run: " + ocrCommand);
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", ocrCommand);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream())
);
String line;
while ((line = reader.readLine()) != null) {
ocrText.append(line).append("\n\r");
}
int exitVal = process.waitFor();
} catch (Exception e) {
ocrText.append("ERROR_NO_OCR");
e.printStackTrace();
} finally {
boolean delete = tempFile.delete();
}
}
return ocrText.toString();
}
}
| UTF-8 | Java | 2,123 | java | OcrUtil.java | Java | [] | null | [] | package de.drentech.innihald.documentrepository.ocr;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.enterprise.context.ApplicationScoped;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
@ApplicationScoped
public class OcrUtil {
public String getOcrTextFromPdf(PDDocument pdf, String languageCode) throws IOException {
PDFRenderer renderer = new PDFRenderer(pdf);
StringBuilder ocrText = new StringBuilder();
for (int pageNumber = 0; pageNumber < pdf.getNumberOfPages(); pageNumber++) {
BufferedImage pageImage = renderer.renderImageWithDPI(pageNumber, 300, ImageType.RGB); //TODO: use this to generate thumbnail
File tempFile = File.createTempFile("tempfile_" + pageNumber, ".png");
ImageIO.write(pageImage, "png", tempFile);
String ocrCommand = String.format("tesseract -l %s --oem 1 %s -", languageCode, tempFile.getAbsolutePath());
System.out.println("Command run: " + ocrCommand);
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", ocrCommand);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream())
);
String line;
while ((line = reader.readLine()) != null) {
ocrText.append(line).append("\n\r");
}
int exitVal = process.waitFor();
} catch (Exception e) {
ocrText.append("ERROR_NO_OCR");
e.printStackTrace();
} finally {
boolean delete = tempFile.delete();
}
}
return ocrText.toString();
}
}
| 2,123 | 0.607631 | 0.605276 | 57 | 35.245613 | 31.20126 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719298 | false | false | 13 |
b0ccb79e46e0198653fd40aa04d5176dbbbcd5c2 | 15,908,558,920,835 | 8b9cdee30dcd939c18699959e98dc74236589000 | /src/main/java/data/NegativeData.java | ae9dd092821f103ac52d3bf49ef2fb08d3fedf90 | [] | no_license | ArtBi/SuperCalculator_WebDriver | https://github.com/ArtBi/SuperCalculator_WebDriver | d059db768b0cf93010b39246cc0821db68fa4129 | 9cf2989be8ca4777656531218059ed7dcdb3ca3c | refs/heads/master | 2021-01-18T22:19:45.883000 | 2016-11-05T15:30:46 | 2016-11-05T15:31:12 | 72,486,164 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package data;
import org.testng.annotations.*;
/**
* Created by RtB on 28.10.2016.
*/
public class NegativeData {
@DataProvider(name = "addition-provider")
public static Object[][] additionTestProvider() {
return new Object[][]{
{"", "", "NaN"},
{"", "-1", "NaN"},
{"--1", "-1", "NaN"},
{"-1", "--1", "NaN"},
{"", "1", "NaN"},
{"1", "", "NaN"},
{"text", "text", "NaN"},
{"text", "@#$#%%^^@#!@!", "NaN"},
};
}
@DataProvider(name = "subtraction-provider")
public static Object[][] subtractionTestProvider() {
return new Object[][]{
{"", "", "NaN"},
{"", "-1", "NaN"},
{"--1", "-1", "NaN"},
{"-1", "--1", "NaN"},
{"", "1", "NaN"},
{"1", "", "NaN"},
{"text", "text", "NaN"},
{"text", "@#$#%%^^@#!@!", "NaN"},
};
}
@DataProvider(name = "division-provider")
public static Object[][] divisionTestProvider() {
return new Object[][]{
{"1", "0", "Infinity"},
{"1", "-0", "Infinity"},
{"0", "0", "NaN"},
{"gsd", "0", "NaN"},
};
}
@DataProvider(name = "multiplication-provider")
public static Object[][] multiplicationTestProvider() {
return new Object[][]{
{"", "", "NaN"},
{"-a", "1", "NaN"},
{"%$#%$%#%$", "3", "NaN"},
{"-1", "-a", "NaN"},
{"A", "2","NaN"},
{"2", "\"","NaN"},
{"\"", "9","NaN"},
{"", "-7","NaN"},
{"", "-","NaN"}
};
}
@DataProvider(name = "percentage-provider")
public static Object[][] percentageTestProvider() {
return new Object[][]{
{"", "", "NaN"},
{"15", "", "NaN"},
{"", "100", "NaN"},
{"-0", "100", "NaN"},
{"sfsdf", "100", "NaN"}
};
}
}
| UTF-8 | Java | 2,220 | java | NegativeData.java | Java | [
{
"context": "rt org.testng.annotations.*;\r\n\r\n/**\r\n * Created by RtB on 28.10.2016.\r\n */\r\npublic class NegativeData {\r",
"end": 75,
"score": 0.9994392395019531,
"start": 72,
"tag": "USERNAME",
"value": "RtB"
}
] | null | [] | package data;
import org.testng.annotations.*;
/**
* Created by RtB on 28.10.2016.
*/
public class NegativeData {
@DataProvider(name = "addition-provider")
public static Object[][] additionTestProvider() {
return new Object[][]{
{"", "", "NaN"},
{"", "-1", "NaN"},
{"--1", "-1", "NaN"},
{"-1", "--1", "NaN"},
{"", "1", "NaN"},
{"1", "", "NaN"},
{"text", "text", "NaN"},
{"text", "@#$#%%^^@#!@!", "NaN"},
};
}
@DataProvider(name = "subtraction-provider")
public static Object[][] subtractionTestProvider() {
return new Object[][]{
{"", "", "NaN"},
{"", "-1", "NaN"},
{"--1", "-1", "NaN"},
{"-1", "--1", "NaN"},
{"", "1", "NaN"},
{"1", "", "NaN"},
{"text", "text", "NaN"},
{"text", "@#$#%%^^@#!@!", "NaN"},
};
}
@DataProvider(name = "division-provider")
public static Object[][] divisionTestProvider() {
return new Object[][]{
{"1", "0", "Infinity"},
{"1", "-0", "Infinity"},
{"0", "0", "NaN"},
{"gsd", "0", "NaN"},
};
}
@DataProvider(name = "multiplication-provider")
public static Object[][] multiplicationTestProvider() {
return new Object[][]{
{"", "", "NaN"},
{"-a", "1", "NaN"},
{"%$#%$%#%$", "3", "NaN"},
{"-1", "-a", "NaN"},
{"A", "2","NaN"},
{"2", "\"","NaN"},
{"\"", "9","NaN"},
{"", "-7","NaN"},
{"", "-","NaN"}
};
}
@DataProvider(name = "percentage-provider")
public static Object[][] percentageTestProvider() {
return new Object[][]{
{"", "", "NaN"},
{"15", "", "NaN"},
{"", "100", "NaN"},
{"-0", "100", "NaN"},
{"sfsdf", "100", "NaN"}
};
}
}
| 2,220 | 0.322523 | 0.300901 | 73 | 28.410959 | 16.721601 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.465753 | false | false | 13 |
18d29112b958c0993add2742c400e54d56bdaa88 | 28,132,035,843,433 | 6e20fc51db65163f03aea11e73e4862ae846eb1d | /web/src/main/java/org/zerock/web/BoardController.java | 905eeba6a2bf0dedcbf6a0f18b4d6bd0fae05d1c | [] | no_license | Jung-hyeon-Park/UsedGames | https://github.com/Jung-hyeon-Park/UsedGames | f9c8aee89a3b9c3d32e7d61bd191683ba396f65b | 1d749af65e7c5ee3a0cec5793bd604a683621baa | refs/heads/master | 2018-10-29T22:54:12.928000 | 2018-10-12T01:43:12 | 2018-10-12T01:43:12 | 144,663,701 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.zerock.web;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.zerock.domain.BoardVO;
import org.zerock.domain.UserVO;
import org.zerock.service.BoardService;
@RequestMapping("/board")
@Controller
public class BoardController {
@Inject
private BoardService boardService;
// 게시글 생성
@RequestMapping(value="/insertBoard.do", method=RequestMethod.GET)
public void board(Model model) throws Exception {
model.addAttribute("posts", boardService.selectPost());
}
@RequestMapping(value="/insertBoard.do", method=RequestMethod.POST)
public String insertBoard(MultipartHttpServletRequest request, Model model, BoardVO boardVO, HttpSession session) throws Exception {
UserVO userVO = (UserVO)session.getAttribute("login");
boardVO.setUserIdx(userVO.getIdx());
MultipartFile mf = request.getFile("image_file");
String path = request.getRealPath("/resources/uploadFile/image");
String fileName = mf.getOriginalFilename();
File uploadFile = new File(path+"//"+fileName);
try {
mf.transferTo(uploadFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
boardVO.setImage(fileName);
boardService.insertBoard(boardVO);
return "redirect:/board/listAll.do";
}
//게시글 리스트
@RequestMapping(value="/listAll.do", method=RequestMethod.GET)
public void listAll(Model model) throws Exception {
model.addAttribute("posts", boardService.selectBoard());
}
//상세 게시글
@RequestMapping(value="/readBoard.do", method=RequestMethod.GET)
public void readBoard(@RequestParam("idx") int idx, Model model) throws Exception {
BoardVO boardVO = boardService.readBoard(idx);
model.addAttribute("boardVO", boardVO);
}
//게시글 삭제
@RequestMapping(value="/deleteBoard.do", method=RequestMethod.POST)
public String deleteBoard(@RequestParam("idx") int idx, RedirectAttributes rttr) throws Exception {
boardService.deleteBoard(idx);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/listAll.do";
}
//게시글 수정
@RequestMapping(value="/updateBoard.do", method=RequestMethod.GET)
public void updateBoard(@RequestParam("idx") int idx, Model model) throws Exception {
model.addAttribute(boardService.readBoard(idx));
}
@RequestMapping(value="/updateBoard.do", method=RequestMethod.POST)
public String updateBoard(BoardVO boardVO, RedirectAttributes rttr) throws Exception {
boardService.updateBoard(boardVO);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/listAll.do";
}
}
| UTF-8 | Java | 3,271 | java | BoardController.java | Java | [] | null | [] | package org.zerock.web;
import java.io.File;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.zerock.domain.BoardVO;
import org.zerock.domain.UserVO;
import org.zerock.service.BoardService;
@RequestMapping("/board")
@Controller
public class BoardController {
@Inject
private BoardService boardService;
// 게시글 생성
@RequestMapping(value="/insertBoard.do", method=RequestMethod.GET)
public void board(Model model) throws Exception {
model.addAttribute("posts", boardService.selectPost());
}
@RequestMapping(value="/insertBoard.do", method=RequestMethod.POST)
public String insertBoard(MultipartHttpServletRequest request, Model model, BoardVO boardVO, HttpSession session) throws Exception {
UserVO userVO = (UserVO)session.getAttribute("login");
boardVO.setUserIdx(userVO.getIdx());
MultipartFile mf = request.getFile("image_file");
String path = request.getRealPath("/resources/uploadFile/image");
String fileName = mf.getOriginalFilename();
File uploadFile = new File(path+"//"+fileName);
try {
mf.transferTo(uploadFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
boardVO.setImage(fileName);
boardService.insertBoard(boardVO);
return "redirect:/board/listAll.do";
}
//게시글 리스트
@RequestMapping(value="/listAll.do", method=RequestMethod.GET)
public void listAll(Model model) throws Exception {
model.addAttribute("posts", boardService.selectBoard());
}
//상세 게시글
@RequestMapping(value="/readBoard.do", method=RequestMethod.GET)
public void readBoard(@RequestParam("idx") int idx, Model model) throws Exception {
BoardVO boardVO = boardService.readBoard(idx);
model.addAttribute("boardVO", boardVO);
}
//게시글 삭제
@RequestMapping(value="/deleteBoard.do", method=RequestMethod.POST)
public String deleteBoard(@RequestParam("idx") int idx, RedirectAttributes rttr) throws Exception {
boardService.deleteBoard(idx);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/listAll.do";
}
//게시글 수정
@RequestMapping(value="/updateBoard.do", method=RequestMethod.GET)
public void updateBoard(@RequestParam("idx") int idx, Model model) throws Exception {
model.addAttribute(boardService.readBoard(idx));
}
@RequestMapping(value="/updateBoard.do", method=RequestMethod.POST)
public String updateBoard(BoardVO boardVO, RedirectAttributes rttr) throws Exception {
boardService.updateBoard(boardVO);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/listAll.do";
}
}
| 3,271 | 0.737496 | 0.737496 | 104 | 28.951923 | 28.269438 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.759615 | false | false | 13 |
2158d5416e022eda3d122750be7cd24474024501 | 30,631,706,788,558 | bacde5bb0effd64aa061a729d73e07642d876368 | /vnp/Defense Run/src/org/com/vnp/defenserun/data/NormalQuaivat.java | fc06ba7675b18862416cd70f4118c816fec27fa4 | [] | no_license | fordream/store-vnp | https://github.com/fordream/store-vnp | fe10d74acd1a780fb88f90e4854d15ce44ecb68c | 6ca37dd4a69a63ea65d601aad695150e70f8d603 | refs/heads/master | 2020-12-02T15:05:14.994000 | 2015-10-23T13:52:51 | 2015-10-23T13:52:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.com.vnp.defenserun.data;
public class NormalQuaivat extends Quaivat {
}
| UTF-8 | Java | 86 | java | NormalQuaivat.java | Java | [] | null | [] | package org.com.vnp.defenserun.data;
public class NormalQuaivat extends Quaivat {
}
| 86 | 0.790698 | 0.790698 | 5 | 16.200001 | 19.6 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 13 |
e3eb107e2e1908bc43ab9e42c546680e826b51c5 | 28,278,064,718,924 | 14136dbf87ce6951b65de054b7d82aad76d1de68 | /site/permi-parent/shiro-spring-redis/src/main/java/com/outrun/permission/oper/dao/relation/User_arole_dao.java | f80fbcf8f6d0687607423378b66a8502d7a43f2c | [] | no_license | outrunJ/projects | https://github.com/outrunJ/projects | 082484d6e914d79175fccf25048c814fed9b0166 | 7ea2ad0384112399972fca87da022b8e5f0e3e86 | refs/heads/master | 2016-08-31T01:52:27.111000 | 2016-08-25T09:35:57 | 2016-08-25T09:35:57 | 35,462,581 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.outrun.permission.oper.dao.relation;
import java.sql.SQLException;
import com.outrun.permission.oper.dao.base.PermiBaseDao;
import com.outrun.permission.oper.entity.relation.User_arole;
public interface User_arole_dao extends PermiBaseDao<User_arole>{
public abstract boolean detachAroles(String[] userIds) throws SQLException;
public abstract int decoupleRoles(String[] userIds, Object[] aroleIds) throws SQLException;
public abstract Object[] aroleIds(String[] ids) throws SQLException;
}
| UTF-8 | Java | 513 | java | User_arole_dao.java | Java | [] | null | [] | package com.outrun.permission.oper.dao.relation;
import java.sql.SQLException;
import com.outrun.permission.oper.dao.base.PermiBaseDao;
import com.outrun.permission.oper.entity.relation.User_arole;
public interface User_arole_dao extends PermiBaseDao<User_arole>{
public abstract boolean detachAroles(String[] userIds) throws SQLException;
public abstract int decoupleRoles(String[] userIds, Object[] aroleIds) throws SQLException;
public abstract Object[] aroleIds(String[] ids) throws SQLException;
}
| 513 | 0.808967 | 0.808967 | 16 | 31.0625 | 33.345669 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false | 13 |
773cbdac99c608be77da06990d855c1161f6c434 | 30,262,339,602,779 | e88d8f11e8ea08e6d166b9b9cd4da65dcd1606ed | /src/test/java/com/qa/pippin/TestCases/HomePageTest.java | e4441e53e0bac1648e9b57e31830c15b754851ed | [] | no_license | varshitha-automation/AutomationCoding-Challenge | https://github.com/varshitha-automation/AutomationCoding-Challenge | b01ea416772ad88a75223db5c49042d4c19d90e3 | 8cb376b9b3ae302e2bd14efedb2fdf300d4deeae | refs/heads/master | 2023-05-14T00:48:57.051000 | 2021-06-05T10:46:57 | 2021-06-05T10:46:57 | 374,087,811 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qa.pippin.TestCases;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com.qa.pippin.Listener.listen;
import com.qa.pippin.TestBase.Base;
import com.qa.pippin.pages.HomePage;
import com.qa.pippin.pages.LoginPage;
import com.qa.pippin.pages.PlaceOrderPage;
@Listeners(listen.class)
public class HomePageTest extends Base{
private WebDriver driver;
HomePage homepage;
PlaceOrderPage placeorderpage;
LoginPage loginpage;
@BeforeMethod
public void setUp() throws IOException
{
WebDriver driver=initialization();
this.driver = driver;
loginpage = new LoginPage(driver);
homepage = new HomePage(driver);
homepage=loginpage.login();
}
@Test
public void placeTest()
{
placeorderpage=homepage.placeOrder();
}
@AfterMethod
public void tearDown()
{
driver.quit();
}
}
| UTF-8 | Java | 1,005 | java | HomePageTest.java | Java | [] | null | [] | package com.qa.pippin.TestCases;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com.qa.pippin.Listener.listen;
import com.qa.pippin.TestBase.Base;
import com.qa.pippin.pages.HomePage;
import com.qa.pippin.pages.LoginPage;
import com.qa.pippin.pages.PlaceOrderPage;
@Listeners(listen.class)
public class HomePageTest extends Base{
private WebDriver driver;
HomePage homepage;
PlaceOrderPage placeorderpage;
LoginPage loginpage;
@BeforeMethod
public void setUp() throws IOException
{
WebDriver driver=initialization();
this.driver = driver;
loginpage = new LoginPage(driver);
homepage = new HomePage(driver);
homepage=loginpage.login();
}
@Test
public void placeTest()
{
placeorderpage=homepage.placeOrder();
}
@AfterMethod
public void tearDown()
{
driver.quit();
}
}
| 1,005 | 0.770149 | 0.770149 | 50 | 19.1 | 16.021547 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.2 | false | false | 13 |
a8f813ac0db950a2e3fed1a5cf2f97ff779780c7 | 30,872,224,959,799 | 578d7cf6846165afc6086b8d81faf020d9578979 | /web/juzhai/trunk/src/main/java/com/juzhai/core/web/filter/CheckLoginFilter.java | ca121ccc115a00123b0d95f2543030dc1eb1b269 | [] | no_license | dalinhuang/weguan | https://github.com/dalinhuang/weguan | edd2ec613e71f2c9509a10628d8517fe53862344 | 4d3feaffe2e7374e632247a66e8f320d3e3a9f1f | refs/heads/master | 2016-09-13T18:55:22.557000 | 2014-06-12T08:00:48 | 2014-06-12T08:00:48 | 56,267,129 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.juzhai.core.web.filter;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.juzhai.core.Constants;
import com.juzhai.core.exception.NeedLoginException;
import com.juzhai.core.exception.NeedLoginException.RunType;
import com.juzhai.core.web.session.LoginSessionManager;
import com.juzhai.core.web.session.UserContext;
import com.juzhai.core.web.util.HttpRequestUtil;
import com.juzhai.passport.exception.ReportAccountException;
import com.juzhai.passport.service.ILoginService;
import com.juzhai.passport.service.IProfileService;
@Component
public class CheckLoginFilter implements Filter {
public static final String LOGIN_USER_KEY = "loginUser";
public static final String IS_FROM_QQ_PLUS = "isQplus";
@Autowired
private LoginSessionManager loginSessionManager;
@Autowired
private ILoginService loginService;
@Autowired
private IProfileService profileService;
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse rep = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
try {
UserContext context = loginSessionManager.getUserContext(req);
req.setAttribute("context", context);
if (!context.hasLogin()) {
loginService.persistentAutoLogin(req, rep);
// context = loginSessionManager.getUserContext(req);
}
context = (UserContext) req.getAttribute("context");
// else if (context.hasLogin()) {
// loginService.isShield(context.getUid(), req, rep);
// }
if (context.hasLogin()) {
loginService.isShield(context.getUid(), req, rep);
loginService.updateOnlineState(context.getUid());
// 获取登录用户信息
req.setAttribute(LOGIN_USER_KEY,
profileService.getProfileCacheByUid(context.getUid()));
}
// 判断是否来自q+
// if (null == req.getSession().getAttribute(IS_FROM_QQ_PLUS)) {
String userAgent = context.getUserAgentPermanentCode();
req.setAttribute(
IS_FROM_QQ_PLUS,
StringUtils.isEmpty(userAgent) ? false : userAgent
.contains("Qplus"));
// }
filterChain.doFilter(request, response);
} catch (Exception e) {
if (e.getCause() instanceof NeedLoginException) {
needLoginHandle(req, rep, (NeedLoginException) e.getCause());
} else if (e instanceof ReportAccountException) {
needReportHandle(req, rep, (ReportAccountException) e);
} else if (e.getCause() instanceof ReportAccountException) {
needReportHandle(req, rep,
(ReportAccountException) e.getCause());
} else {
throw new ServletException(e.getMessage(), e);
}
}
}
/**
* 需要登录处理
*
* @param request
* @param response
* @param e
* @throws IOException
*/
private void needLoginHandle(HttpServletRequest request,
HttpServletResponse response, NeedLoginException e)
throws IOException {
if (isAjaxRequest(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else if (isIOSRequest(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
if (RunType.APP.equals(e.getRunType())) {
String returnLink = URLEncoder.encode(
HttpRequestUtil.getRemoteUrl(request), Constants.UTF8);
response.sendRedirect("/app/login?returnLink=" + returnLink);
} else {
String redirectURI = "/login";
String turnTo = HttpRequestUtil.getRemoteUrl(request);
if (StringUtils.isNotEmpty(turnTo)) {
redirectURI = redirectURI + "?turnTo=" + turnTo;
}
response.sendRedirect(redirectURI);
}
}
}
private void needReportHandle(HttpServletRequest request,
HttpServletResponse response, ReportAccountException e)
throws IOException {
if (isAjaxRequest(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
response.sendRedirect("/login/error/shield?shieldTime="
+ e.getShieldTime());
}
}
/**
* @return 是否ajax请求
*/
private boolean isAjaxRequest(HttpServletRequest request) {
String requestedWith = request.getHeader("x-requested-with");
if (StringUtils.equals(requestedWith, "XMLHttpRequest")) {
return true;
}
return false;
}
private boolean isIOSRequest(HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
if (StringUtils.isEmpty(userAgent)) {
return false;
}
return userAgent.contains("iPhone OS") || userAgent.contains("iPad OS");
}
}
| UTF-8 | Java | 5,192 | java | CheckLoginFilter.java | Java | [
{
"context": "\r\n\r\n\tpublic static final String LOGIN_USER_KEY = \"loginUser\";\r\n\tpublic static final String IS_FROM_QQ_PLU",
"end": 1166,
"score": 0.6727568507194519,
"start": 1161,
"tag": "KEY",
"value": "login"
}
] | null | [] | package com.juzhai.core.web.filter;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.juzhai.core.Constants;
import com.juzhai.core.exception.NeedLoginException;
import com.juzhai.core.exception.NeedLoginException.RunType;
import com.juzhai.core.web.session.LoginSessionManager;
import com.juzhai.core.web.session.UserContext;
import com.juzhai.core.web.util.HttpRequestUtil;
import com.juzhai.passport.exception.ReportAccountException;
import com.juzhai.passport.service.ILoginService;
import com.juzhai.passport.service.IProfileService;
@Component
public class CheckLoginFilter implements Filter {
public static final String LOGIN_USER_KEY = "loginUser";
public static final String IS_FROM_QQ_PLUS = "isQplus";
@Autowired
private LoginSessionManager loginSessionManager;
@Autowired
private ILoginService loginService;
@Autowired
private IProfileService profileService;
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse rep = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
try {
UserContext context = loginSessionManager.getUserContext(req);
req.setAttribute("context", context);
if (!context.hasLogin()) {
loginService.persistentAutoLogin(req, rep);
// context = loginSessionManager.getUserContext(req);
}
context = (UserContext) req.getAttribute("context");
// else if (context.hasLogin()) {
// loginService.isShield(context.getUid(), req, rep);
// }
if (context.hasLogin()) {
loginService.isShield(context.getUid(), req, rep);
loginService.updateOnlineState(context.getUid());
// 获取登录用户信息
req.setAttribute(LOGIN_USER_KEY,
profileService.getProfileCacheByUid(context.getUid()));
}
// 判断是否来自q+
// if (null == req.getSession().getAttribute(IS_FROM_QQ_PLUS)) {
String userAgent = context.getUserAgentPermanentCode();
req.setAttribute(
IS_FROM_QQ_PLUS,
StringUtils.isEmpty(userAgent) ? false : userAgent
.contains("Qplus"));
// }
filterChain.doFilter(request, response);
} catch (Exception e) {
if (e.getCause() instanceof NeedLoginException) {
needLoginHandle(req, rep, (NeedLoginException) e.getCause());
} else if (e instanceof ReportAccountException) {
needReportHandle(req, rep, (ReportAccountException) e);
} else if (e.getCause() instanceof ReportAccountException) {
needReportHandle(req, rep,
(ReportAccountException) e.getCause());
} else {
throw new ServletException(e.getMessage(), e);
}
}
}
/**
* 需要登录处理
*
* @param request
* @param response
* @param e
* @throws IOException
*/
private void needLoginHandle(HttpServletRequest request,
HttpServletResponse response, NeedLoginException e)
throws IOException {
if (isAjaxRequest(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else if (isIOSRequest(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
if (RunType.APP.equals(e.getRunType())) {
String returnLink = URLEncoder.encode(
HttpRequestUtil.getRemoteUrl(request), Constants.UTF8);
response.sendRedirect("/app/login?returnLink=" + returnLink);
} else {
String redirectURI = "/login";
String turnTo = HttpRequestUtil.getRemoteUrl(request);
if (StringUtils.isNotEmpty(turnTo)) {
redirectURI = redirectURI + "?turnTo=" + turnTo;
}
response.sendRedirect(redirectURI);
}
}
}
private void needReportHandle(HttpServletRequest request,
HttpServletResponse response, ReportAccountException e)
throws IOException {
if (isAjaxRequest(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
response.sendRedirect("/login/error/shield?shieldTime="
+ e.getShieldTime());
}
}
/**
* @return 是否ajax请求
*/
private boolean isAjaxRequest(HttpServletRequest request) {
String requestedWith = request.getHeader("x-requested-with");
if (StringUtils.equals(requestedWith, "XMLHttpRequest")) {
return true;
}
return false;
}
private boolean isIOSRequest(HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
if (StringUtils.isEmpty(userAgent)) {
return false;
}
return userAgent.contains("iPhone OS") || userAgent.contains("iPad OS");
}
}
| 5,192 | 0.723173 | 0.722978 | 156 | 30.97436 | 22.936352 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.455128 | false | false | 13 |
3660b1bdbd0015b04f45119770bfd551576f5b0f | 1,365,799,638,899 | 0e0343f1ceacde0b67d7cbf6b0b81d08473265ab | /aurora_ide/aurora.ide.prototype.consultant.product/src/aurora/ide/prototype/consultant/view/wizard/FunctionFSDDescPage.java | 145a3f7436b41a0b36120073ac3938f6c365522f | [] | no_license | Chajunghun/aurora-project | https://github.com/Chajunghun/aurora-project | 33d5f89e9f21c49d01d3d09d32102d3c496df851 | d4d39861446ea941929780505987dbaf9e3b7a8d | refs/heads/master | 2021-01-01T05:39:36.339000 | 2015-03-24T07:41:45 | 2015-03-24T07:41:45 | 33,435,911 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aurora.ide.prototype.consultant.view.wizard;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import uncertain.composite.CompositeMap;
import aurora.ide.prototype.consultant.product.fsd.FunctionDesc;
import aurora.ide.prototype.consultant.product.fsd.wizard.ApplyControl;
import aurora.ide.prototype.consultant.product.fsd.wizard.AuthorControl;
import aurora.ide.prototype.consultant.product.fsd.wizard.TitleControl;
import aurora.ide.swt.util.GridLayoutUtil;
import aurora.ide.swt.util.UWizardPage;
public class FunctionFSDDescPage extends UWizardPage {
public static final String[] properties = new String[] {
FunctionDesc.doc_title, FunctionDesc.fun_code,
FunctionDesc.fun_name, FunctionDesc.writer, FunctionDesc.c_date,
FunctionDesc.u_date, FunctionDesc.no, FunctionDesc.ver,
FunctionDesc.c_manager, FunctionDesc.dept, FunctionDesc.h_manager };
protected FunctionFSDDescPage(String pageName, String title,
ImageDescriptor titleImage, CompositeMap input) {
super(pageName);
this.setTitle(title);
this.setImageDescriptor(titleImage);
new TitleControl(this.getModel()).loadFromMap(input);
new AuthorControl(this.getModel()).loadFromMap(input);
new ApplyControl(this.getModel()).loadFromMap(input);
}
protected String[] getModelPropertyKeys() {
return properties;
}
@Override
protected String verifyModelProperty(String key, Object val) {
if(properties[0].equals(key)){
if(val == null || "".equals(val)){ //$NON-NLS-1$
return Messages.FunctionFSDDescPage_1;
}
}
return null;
}
@Override
protected Composite createPageControl(Composite control) {
// root.setLayout(GridLayoutUtil.COLUMN_LAYOUT_1);
//
// Composite parent = WidgetFactory.composite(root);
Composite parent = new Composite(control, SWT.NONE);
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
parent.setLayout(GridLayoutUtil.COLUMN_LAYOUT_1);
createTitleControl(parent);
new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL)
.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
createAuthorControl(parent);
new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL)
.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
createApplyControl(parent);
return parent;
}
protected void createApplyControl(Composite parent) {
new ApplyControl(this.getModel()).createApplyControl(parent);
}
protected void createAuthorControl(Composite parent) {
new AuthorControl(this.getModel()).createAuthorControl(parent);
}
protected void createTitleControl(Composite parent) {
new TitleControl(this.getModel()).createTitleControl(parent);
}
protected void saveTOMap(CompositeMap map) {
new TitleControl(this.getModel()).saveToMap(map);
new AuthorControl(this.getModel()).saveToMap(map);
new ApplyControl(this.getModel()).saveToMap(map);
}
}
| UTF-8 | Java | 2,960 | java | FunctionFSDDescPage.java | Java | [] | null | [] | package aurora.ide.prototype.consultant.view.wizard;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import uncertain.composite.CompositeMap;
import aurora.ide.prototype.consultant.product.fsd.FunctionDesc;
import aurora.ide.prototype.consultant.product.fsd.wizard.ApplyControl;
import aurora.ide.prototype.consultant.product.fsd.wizard.AuthorControl;
import aurora.ide.prototype.consultant.product.fsd.wizard.TitleControl;
import aurora.ide.swt.util.GridLayoutUtil;
import aurora.ide.swt.util.UWizardPage;
public class FunctionFSDDescPage extends UWizardPage {
public static final String[] properties = new String[] {
FunctionDesc.doc_title, FunctionDesc.fun_code,
FunctionDesc.fun_name, FunctionDesc.writer, FunctionDesc.c_date,
FunctionDesc.u_date, FunctionDesc.no, FunctionDesc.ver,
FunctionDesc.c_manager, FunctionDesc.dept, FunctionDesc.h_manager };
protected FunctionFSDDescPage(String pageName, String title,
ImageDescriptor titleImage, CompositeMap input) {
super(pageName);
this.setTitle(title);
this.setImageDescriptor(titleImage);
new TitleControl(this.getModel()).loadFromMap(input);
new AuthorControl(this.getModel()).loadFromMap(input);
new ApplyControl(this.getModel()).loadFromMap(input);
}
protected String[] getModelPropertyKeys() {
return properties;
}
@Override
protected String verifyModelProperty(String key, Object val) {
if(properties[0].equals(key)){
if(val == null || "".equals(val)){ //$NON-NLS-1$
return Messages.FunctionFSDDescPage_1;
}
}
return null;
}
@Override
protected Composite createPageControl(Composite control) {
// root.setLayout(GridLayoutUtil.COLUMN_LAYOUT_1);
//
// Composite parent = WidgetFactory.composite(root);
Composite parent = new Composite(control, SWT.NONE);
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
parent.setLayout(GridLayoutUtil.COLUMN_LAYOUT_1);
createTitleControl(parent);
new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL)
.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
createAuthorControl(parent);
new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL)
.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
createApplyControl(parent);
return parent;
}
protected void createApplyControl(Composite parent) {
new ApplyControl(this.getModel()).createApplyControl(parent);
}
protected void createAuthorControl(Composite parent) {
new AuthorControl(this.getModel()).createAuthorControl(parent);
}
protected void createTitleControl(Composite parent) {
new TitleControl(this.getModel()).createTitleControl(parent);
}
protected void saveTOMap(CompositeMap map) {
new TitleControl(this.getModel()).saveToMap(map);
new AuthorControl(this.getModel()).saveToMap(map);
new ApplyControl(this.getModel()).saveToMap(map);
}
}
| 2,960 | 0.778716 | 0.777027 | 85 | 33.823528 | 24.886177 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.988235 | false | false | 13 |
22880a1281728d765fa358bea45ea6b0196557dd | 10,780,367,960,713 | 46fea422f231b095fd201fc939d5292bf49f7bac | /src/main/java/com/xiao/test1.java | 6a79b27fd1bc876f3e033572f567ecc4cf765ff8 | [] | no_license | XL340823/githubtet03 | https://github.com/XL340823/githubtet03 | 0dc14500b0e4aacdc84027c89a528b9c3703b0bd | fd33c3ccb68322d4bf44d42d148cf4a93e99bf50 | refs/heads/master | 2023-04-27T21:00:23.097000 | 2021-05-08T08:27:11 | 2021-05-08T08:27:11 | 365,449,492 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xiao;
public class test1 {
public static void main(String[] args) {
System.out.println("111");
System.out.println("push test");
System.out.println("push test1");
System.out.println("pull test");
System.out.println("gitee test");
System.out.println("gitee pull test");
}
} | UTF-8 | Java | 340 | java | test1.java | Java | [] | null | [] | package com.xiao;
public class test1 {
public static void main(String[] args) {
System.out.println("111");
System.out.println("push test");
System.out.println("push test1");
System.out.println("pull test");
System.out.println("gitee test");
System.out.println("gitee pull test");
}
} | 340 | 0.605882 | 0.591176 | 12 | 27.416666 | 16.992441 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 13 |
0fa9652e71188c6b0865d3e96a5df7a5addfacb5 | 17,712,445,128,984 | 2070fb4b67d8c79dca49605c9a9c6ce839d9023d | /que2.java | 344da72a8688cadd19c22f7dd41b4db56542bca8 | [] | no_license | parmar1399/dsass5 | https://github.com/parmar1399/dsass5 | a0965302bed63285cda8aa0fba9b05e4aa8b1525 | d98ac65aa67853aff8f069f1bdc1c4b12230f38e | refs/heads/master | 2020-04-08T04:09:35.571000 | 2018-11-25T06:40:45 | 2018-11-25T06:40:45 | 159,005,315 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class node
{
int data;
node next;
public node(int data)
{
this.data=data;
this.next=null;
}
}
class Stack
{
node head;
Stack()
{
this.head=null;
}
public void push (int data)
{
node temp=new node(data);
temp.next=this.head;
this.head=temp;
}
public int pop()
{
if (this.head==null)
{
return -1;
}
else
{
int temp=this.head.data;
this.head=this.head.next;
return temp;
}
}
public int peek()
{
if (this.head==null)
{
return -1;
}
return this.head.data;
}
public void print()
{
node temp=this.head;
while (temp!=null)
{
if (temp!=null)
{
System.out.print(temp.data+" ");
temp=temp.next;
}
}
System.out.println();
}
}
class Queue
{
Stack st1;
Stack st2;
Queue()
{
this.st1=new Stack();
this.st2=new Stack();
}
public void push(int data)
{
this.st1.push(data);
}
public int pop()
{
int temp=0;
while ((temp=this.st1.pop())!=-1)
{
this.st2.push(temp);
}
temp=st2.pop();
int temp2=0;
while ((temp2=this.st2.pop())!=-1)
{
this.st1.push(temp2);
}
return temp;
}
public int peek()
{
int temp=0;
while ((temp=this.st1.pop())!=-1)
{
this.st2.push(temp);
}
temp=st2.peek();
int temp2=0;
while ((temp2=this.st2.pop())!=-1)
{
this.st1.push(temp2);
}
return temp;
}
}
class que2
{
public static void main(String[] args)
{
Queue st=new Queue();
st.push(1);
st.push(2);
System.out.println(st.pop());
System.out.println(st.peek());
System.out.println(st.pop());
System.out.println(st.pop());
}
}
| UTF-8 | Java | 1,774 | java | que2.java | Java | [] | null | [] | class node
{
int data;
node next;
public node(int data)
{
this.data=data;
this.next=null;
}
}
class Stack
{
node head;
Stack()
{
this.head=null;
}
public void push (int data)
{
node temp=new node(data);
temp.next=this.head;
this.head=temp;
}
public int pop()
{
if (this.head==null)
{
return -1;
}
else
{
int temp=this.head.data;
this.head=this.head.next;
return temp;
}
}
public int peek()
{
if (this.head==null)
{
return -1;
}
return this.head.data;
}
public void print()
{
node temp=this.head;
while (temp!=null)
{
if (temp!=null)
{
System.out.print(temp.data+" ");
temp=temp.next;
}
}
System.out.println();
}
}
class Queue
{
Stack st1;
Stack st2;
Queue()
{
this.st1=new Stack();
this.st2=new Stack();
}
public void push(int data)
{
this.st1.push(data);
}
public int pop()
{
int temp=0;
while ((temp=this.st1.pop())!=-1)
{
this.st2.push(temp);
}
temp=st2.pop();
int temp2=0;
while ((temp2=this.st2.pop())!=-1)
{
this.st1.push(temp2);
}
return temp;
}
public int peek()
{
int temp=0;
while ((temp=this.st1.pop())!=-1)
{
this.st2.push(temp);
}
temp=st2.peek();
int temp2=0;
while ((temp2=this.st2.pop())!=-1)
{
this.st1.push(temp2);
}
return temp;
}
}
class que2
{
public static void main(String[] args)
{
Queue st=new Queue();
st.push(1);
st.push(2);
System.out.println(st.pop());
System.out.println(st.peek());
System.out.println(st.pop());
System.out.println(st.pop());
}
}
| 1,774 | 0.509583 | 0.490417 | 118 | 13.983051 | 11.26114 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.364407 | false | false | 13 |
81650128e05094fa44acfde69d5fab397af6594e | 25,804,163,568,603 | 7a487f05633873b9a7812f4ada520c950ffb2e34 | /src/main/java/net/amritha/flightTracking/Flight.java | 803b5b2e60d659e90c084876359f414f666c26c4 | [] | no_license | sshenoy80/QuoateBot | https://github.com/sshenoy80/QuoateBot | 140e34e93fc5372551bdb84d2bad63de5b92884c | 8f85c62e29345f362d218375981544f3721634ea | HEAD | 2018-07-11T01:55:51.915000 | 2018-06-01T07:39:31 | 2018-06-01T07:39:31 | 133,780,842 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.amritha.flightTracking;
public class Flight extends Object {
private int passengers;
private int seats;
//Integer wrapperInt=3;
public Flight() {
this.seats=150;
this.passengers=0;
}
public int getPassengers() {
return passengers;
}
public int getSeats() {
return seats;
}
public Flight(int passengers) {
this.seats=150;
this.passengers=passengers;
}
public Flight(int passengers,int seats) {
this.seats=seats;
this.passengers=passengers;
}
public int add1Passenger() {
if(passengers<seats){
passengers+=1;
}
return passengers;
}
public boolean addAnotherFlightPassengers(Flight flight) {
int total = passengers + flight.passengers;
if (total<=seats){
passengers=total;
return true;
}
else {
return false;
}
}
public Flight addOtherPassgerFlight(Flight f2) throws InvalidFlightException {
if(f2.passengers==777){
throw new InvalidFlightException("there is wrong flight");
}
Flight createdFlight=new Flight();
createdFlight.passengers=this.passengers+f2.passengers;
return createdFlight;
}
@Override
public String toString() {
if (passengers>0) {
return "Flight{" +
"passengers=" + passengers +
", seats=" + seats +
'}';
}
return "passengers not > 0";
}
}
| UTF-8 | Java | 1,590 | java | Flight.java | Java | [] | null | [] | package net.amritha.flightTracking;
public class Flight extends Object {
private int passengers;
private int seats;
//Integer wrapperInt=3;
public Flight() {
this.seats=150;
this.passengers=0;
}
public int getPassengers() {
return passengers;
}
public int getSeats() {
return seats;
}
public Flight(int passengers) {
this.seats=150;
this.passengers=passengers;
}
public Flight(int passengers,int seats) {
this.seats=seats;
this.passengers=passengers;
}
public int add1Passenger() {
if(passengers<seats){
passengers+=1;
}
return passengers;
}
public boolean addAnotherFlightPassengers(Flight flight) {
int total = passengers + flight.passengers;
if (total<=seats){
passengers=total;
return true;
}
else {
return false;
}
}
public Flight addOtherPassgerFlight(Flight f2) throws InvalidFlightException {
if(f2.passengers==777){
throw new InvalidFlightException("there is wrong flight");
}
Flight createdFlight=new Flight();
createdFlight.passengers=this.passengers+f2.passengers;
return createdFlight;
}
@Override
public String toString() {
if (passengers>0) {
return "Flight{" +
"passengers=" + passengers +
", seats=" + seats +
'}';
}
return "passengers not > 0";
}
}
| 1,590 | 0.557862 | 0.546541 | 69 | 22.043478 | 18.314827 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.376812 | false | false | 13 |
e1ca64a40cc3d246ca67ee750f049bff34ab6684 | 807,453,917,405 | 67541a19d6806faac77e31363dfa381ece293a05 | /src/main/java/com/coretheorylife/modules/shop/service/TOrderLineService.java | 9e27e3456e92bb8346a4a16df4937bdc392819de | [] | no_license | AllenJuy/coretheorylife | https://github.com/AllenJuy/coretheorylife | 562176560b53da9cd427dba56a4ec8b009ee18db | 269e6f08ba7386b3ef3509c07aa86221e7c9be90 | refs/heads/master | 2021-03-04T16:46:53.085000 | 2020-03-17T16:21:27 | 2020-03-17T16:21:27 | 246,049,739 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.coretheorylife.modules.shop.service;
import com.coretheorylife.modules.common.service.BaseService;
import com.coretheorylife.modules.shop.entity.TOrderLine;
import com.coretheorylife.modules.shop.entity.TOrderLineExample;
import java.util.List;
public interface TOrderLineService extends BaseService<TOrderLine, TOrderLineExample> {
List<TOrderLine> queryListByOrderId(Long orderId);
}
| UTF-8 | Java | 406 | java | TOrderLineService.java | Java | [] | null | [] | package com.coretheorylife.modules.shop.service;
import com.coretheorylife.modules.common.service.BaseService;
import com.coretheorylife.modules.shop.entity.TOrderLine;
import com.coretheorylife.modules.shop.entity.TOrderLineExample;
import java.util.List;
public interface TOrderLineService extends BaseService<TOrderLine, TOrderLineExample> {
List<TOrderLine> queryListByOrderId(Long orderId);
}
| 406 | 0.839902 | 0.839902 | 12 | 32.833332 | 30.827026 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 13 |
dd832901b57473f6521eeb1e1e3e4fdf99a8e5a2 | 15,169,824,545,178 | c7bc146a007c3d11a498e61a0986cdaed32f6276 | /app/src/main/java/kr/co/axioms/base/Const.java | f7888230e6319f7eef4d86e0c4f8ff9582f0b090 | [] | no_license | Axioms2018/Axioms | https://github.com/Axioms2018/Axioms | 862e2d62dd2687202ef9109ffc3705129e4f471b | 62ab22e656048f92a7519459e0fe971d94f7ce32 | refs/heads/master | 2020-03-28T01:08:22.848000 | 2018-09-06T07:49:21 | 2018-09-06T07:49:21 | 147,479,998 | 0 | 1 | null | false | 2018-09-06T07:41:46 | 2018-09-05T07:45:14 | 2018-09-05T08:38:59 | 2018-09-06T07:41:46 | 198,793 | 0 | 1 | 2 | Java | false | null | package kr.co.axioms.base;
import android.os.Environment;
/**
* Created by 김민정 on 2018-04-03.
*/
public class Const {
public static final String PACKAGENAME = "kr.co.axioms";
public static final String APPNAME = "Axiom";
public static final String APKFILENAME = "axiom";
public static final String RESOURCE = "android.resource://" + GlobalApplication.getInstance().getPackageName();
public static final String FILE_TYPE_ZIP = ".zip";
public static final String APPID = "1"; //앱아이디
public static final int VRSN = 1; //본학습
public static final String SAVE_USER_INFO = "SAVE_USER_INFO";
public static final String SAVE_STUDY_STEP = "SAVE_STUDY_STEP";
public static final String SAVE_STUDY_QUST = "SAVE_STUDY_QUST";
public final static int RESULT_APK_INSTALL = 1002;
public final static String STUDY_GB_REPORT = "106004";
/** 로그인시 설정 **/
public static final String USER_TEST = "$test_"; //비로그인
public static final String USER_INIT = "$init_"; //처음 접속 시
/** 학습시 진행 값 **/
public static final float LESSON_PRCESS_NONE = 0; //미진행
public static final float LESSON_PRCESS_COMPLETE = 100; //완료
/** 특수문자 **/
public final static String GUBUN_SPACE = " ";
public final static String GUBUN_SEMI_COLON = ";";
public final static String GUBUN_NEW_LINE = "\n";
public final static String GUBUN_SEMI_SHARP = "#";
public final static String GUBUN_SEMI_PERCENT = "%";
/** 인텐트 공통 **/
public class IntentKeys {
public final static String INTENT_DOUBLE_LOGIN = "double_login";
}
//final public static String STT_RESOURCE_PATH = android.os.Environment.getExternalStorageDirectory().getPath() + "/STTEng/";
final public static String STT_RESOURCE_PATH = "data/data/" + GlobalApplication.getInstance().getPackageName() + "/files/STTEng/";
public static final String DATA_PATH = "data/data/" + GlobalApplication.getInstance().getPackageName() + "/files/";
public static final String PATH_ADULT_AXIOMS = "/MouMou/";
public static final String EXTERNAL_PATH_MOUMOU = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_ADULT_AXIOMS;
}
| UTF-8 | Java | 2,346 | java | Const.java | Java | [
{
"context": "\nimport android.os.Environment;\n\n/**\n * Created by 김민정 on 2018-04-03.\n */\n\npublic class Const {\n publ",
"end": 81,
"score": 0.9998188614845276,
"start": 78,
"tag": "NAME",
"value": "김민정"
}
] | null | [] | package kr.co.axioms.base;
import android.os.Environment;
/**
* Created by 김민정 on 2018-04-03.
*/
public class Const {
public static final String PACKAGENAME = "kr.co.axioms";
public static final String APPNAME = "Axiom";
public static final String APKFILENAME = "axiom";
public static final String RESOURCE = "android.resource://" + GlobalApplication.getInstance().getPackageName();
public static final String FILE_TYPE_ZIP = ".zip";
public static final String APPID = "1"; //앱아이디
public static final int VRSN = 1; //본학습
public static final String SAVE_USER_INFO = "SAVE_USER_INFO";
public static final String SAVE_STUDY_STEP = "SAVE_STUDY_STEP";
public static final String SAVE_STUDY_QUST = "SAVE_STUDY_QUST";
public final static int RESULT_APK_INSTALL = 1002;
public final static String STUDY_GB_REPORT = "106004";
/** 로그인시 설정 **/
public static final String USER_TEST = "$test_"; //비로그인
public static final String USER_INIT = "$init_"; //처음 접속 시
/** 학습시 진행 값 **/
public static final float LESSON_PRCESS_NONE = 0; //미진행
public static final float LESSON_PRCESS_COMPLETE = 100; //완료
/** 특수문자 **/
public final static String GUBUN_SPACE = " ";
public final static String GUBUN_SEMI_COLON = ";";
public final static String GUBUN_NEW_LINE = "\n";
public final static String GUBUN_SEMI_SHARP = "#";
public final static String GUBUN_SEMI_PERCENT = "%";
/** 인텐트 공통 **/
public class IntentKeys {
public final static String INTENT_DOUBLE_LOGIN = "double_login";
}
//final public static String STT_RESOURCE_PATH = android.os.Environment.getExternalStorageDirectory().getPath() + "/STTEng/";
final public static String STT_RESOURCE_PATH = "data/data/" + GlobalApplication.getInstance().getPackageName() + "/files/STTEng/";
public static final String DATA_PATH = "data/data/" + GlobalApplication.getInstance().getPackageName() + "/files/";
public static final String PATH_ADULT_AXIOMS = "/MouMou/";
public static final String EXTERNAL_PATH_MOUMOU = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_ADULT_AXIOMS;
}
| 2,346 | 0.662677 | 0.652039 | 53 | 41.566036 | 38.324585 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566038 | false | false | 13 |
c03b7604e00589ce457671eba57c4dd07748b65b | 21,096,879,418,870 | 50e6d0e764cc08ca94ef29713f67565114d6cb0a | /Eclipse Projects/Solynchron/net.sf.swtbot.finder/src/net/sf/swtbot/widgets/SWTBotStyledText.java | 766dec2566f92a0282fccc903fd08fb617b94407 | [
"Apache-2.0"
] | permissive | plamkata/TestProjects | https://github.com/plamkata/TestProjects | 638b6000b435d87a6cc767e9b0f34ddb12f9b748 | c137d926f0f4aa785334f58505d1cc64846b2a6f | refs/heads/master | 2021-01-17T06:27:48.307000 | 2013-07-04T12:14:33 | 2013-07-04T12:14:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright 2007 SWTBot, http://swtbot.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package net.sf.swtbot.widgets;
import net.sf.swtbot.finder.Finder;
import net.sf.swtbot.finder.UIThreadRunnable.ObjectResult;
import net.sf.swtbot.finder.UIThreadRunnable.StringResult;
import net.sf.swtbot.finder.UIThreadRunnable.VoidResult;
import net.sf.swtbot.utils.Position;
import net.sf.swtbot.utils.SWTUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.Bullet;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.StyledTextContent;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Widget;
/**
* @author Ketan Padegaonkar <KetanPadegaonkar [at] gmail [dot] com>
* @version $Id: SWTBotStyledText.java 804 2008-06-28 14:56:44Z kpadegaonkar $
*/
public class SWTBotStyledText extends AbstractLabelSWTBot {
private static final int TYPE_INTERVAL = 50;
/**
* @param finder the finder used to find controls.
* @param text the text on the control.
* @throws WidgetNotFoundException if the widget is not found.
*/
public SWTBotStyledText(Finder finder, String text) throws WidgetNotFoundException {
super(finder, text);
}
/**
* Constructs a new instance of this object.
*
* @param styledText the widget.
* @throws WidgetNotFoundException if the widget is <code>null</code> or widget has been disposed.
*/
public SWTBotStyledText(Widget styledText) throws WidgetNotFoundException {
super(styledText);
}
protected Class nextWidgetType() {
return StyledText.class;
}
/**
* Sets the text into the styled text.
*
* @param text the text to set.
*/
public void setText(final String text) {
checkEnabled();
asyncExec(new VoidResult() {
public void run() {
getControl().setText(text);
}
});
}
/**
* Gets the control.
*
* @return The {@link StyledText}.
*/
private StyledText getControl() {
return (StyledText) widget;
}
/**
* Notifies of the keyboard event.
* <p>
* FIXME need some work for CTRL|SHIFT + 1 the 1 is to be sent as '!' in this case.
* </p>
*
* @param modificationKey the modification key.
* @param c the character.
* @see Event#character
* @see Event#stateMask
*/
public void notifyKeyboardEvent(int modificationKey, char c) {
setFocus();
notifyKeyboardEvent(modificationKey, c, 0);
}
/**
* Notifies of keyboard event.
*
* @param modificationKey the modification key.
* @param c the character.
* @param keyCode the keycode.
* @see Event#keyCode
* @see Event#character
* @see Event#stateMask
*/
public void notifyKeyboardEvent(int modificationKey, char c, int keyCode) {
if (log.isDebugEnabled())
log.debug("Enquing keyboard notification: " + toString(modificationKey, c));
checkEnabled();
notify(SWT.KeyDown, keyEvent(modificationKey, c, keyCode));
notify(SWT.KeyUp, keyEvent(modificationKey, c, keyCode));
}
/**
* Converts the given data to a string.
*
* @param modificationKey The modification key.
* @param c The character.
* @return The string.
*/
private String toString(int modificationKey, char c) {
String mod = "";
if ((modificationKey & SWT.CTRL) != 0)
mod += "SWT.CTRL + ";
if ((modificationKey & SWT.SHIFT) != 0)
mod += "SWT.SHIFT + ";
int lastPlus = mod.lastIndexOf(" + ");
if (lastPlus == (mod.length() - 3))
mod = mod.substring(0, mod.length() - 3) + " + ";
mod = mod + c;
return mod;
}
/**
* Gets the key event.
*
* @param c the character.
* @param modificationKey the modification key.
* @return a key event with the specified keys.
* @see Event#character
* @see Event#stateMask
*/
protected Event keyEvent(int modificationKey, char c) {
return keyEvent(modificationKey, c, c);
}
/**
* Gets the key event.
*
* @param c the character.
* @param modificationKey the modification key.
* @param keyCode the keycode.
* @return a key event with the specified keys.
* @see Event#keyCode
* @see Event#character
* @see Event#stateMask
*/
protected Event keyEvent(int modificationKey, char c, int keyCode) {
Event keyEvent = createEvent();
keyEvent.stateMask = modificationKey;
keyEvent.character = c;
keyEvent.keyCode = keyCode;
return keyEvent;
}
/**
* Sets the caret at the specified location.
*
* @param line the line numnber.
* @param column the column number.
*/
public void navigateTo(final int line, final int column) {
if (log.isDebugEnabled())
log.debug("Enquing navigation to location " + line + ", " + column + " in " + SWTUtils.toString(widget));
checkEnabled();
setFocus();
asyncExec(new VoidResult() {
public void run() {
if (log.isDebugEnabled())
log.debug("Navigating to location " + line + ", " + column + " in " + widget);
getControl().setSelection(offset(line, column));
}
});
}
/**
* Gets the current position of the cursor.
*
* @return the position of the cursor in the styled text.
*/
public Position cursorPosition() {
return (Position) syncExec(new ObjectResult() {
public Object run() {
getControl().setFocus();
int offset = getControl().getSelectionRange().x;
int lineNumber = getControl().getContent().getLineAtOffset(offset);
int offsetAtLine = getControl().getContent().getOffsetAtLine(lineNumber);
int columnNumber = offset - offsetAtLine;
return new Position(lineNumber, columnNumber);
}
});
}
/**
* Types the text at the given location.
*
* @param line the line number.
* @param column the column number.
* @param text the text to be typed at the specified location
* @since 1.0
*/
public void typeText(int line, int column, String text) {
navigateTo(line, column);
typeText(text);
}
/**
* Inserts text at the given location.
*
* @param line the line number.
* @param column the column number.
* @param text the text to be inserted at the specified location
*/
public void insertText(int line, int column, String text) {
navigateTo(line, column);
insertText(text);
}
/**
* Inserts text at the end.
* <p>
* FIXME handle line endings
* </p>
*
* @param text the text to be inserted at the location of the caret.
*/
public void insertText(final String text) {
checkEnabled();
syncExec(new VoidResult() {
public void run() {
getControl().insert(text);
}
});
}
/**
* Types the text.
* <p>
* FIXME handle line endings
* </p>
*
* @param text the text to be typed at the location of the caret.
* @since 1.0
*/
public void typeText(final String text) {
typeText(text, TYPE_INTERVAL);
}
/**
* Types the text.
* <p>
* FIXME handle line endings
* </p>
*
* @param text the text to be typed at the location of the caret.
* @param interval the interval between consecutive key strokes.
* @since 1.0
*/
public void typeText(final String text, int interval) {
if (log.isDebugEnabled())
log.debug("Inserting text:" + text + " into styledtext" + SWTUtils.toString(widget));
setFocus();
for (int i = 0; i < text.length(); i++) {
notifyKeyboardEvent(SWT.NONE, text.charAt(i));
sleep(interval);
}
}
/**
* Gets the style for the given line.
*
* @param line the line number.
* @param column the column number.
* @return the {@link StyleRange} at the specified location
*/
public StyleRange getStyle(final int line, final int column) {
return (StyleRange) syncExec(new ObjectResult() {
public Object run() {
return getControl().getStyleRangeAtOffset(offset(line, column));
}
});
}
/**
* Gets the offset.
*
* @param line the line number.
* @param column the column number.
* @return the character offset at the specified location in the styledtext.
* @see StyledTextContent#getOffsetAtLine(int)
*/
protected int offset(final int line, final int column) {
return getControl().getContent().getOffsetAtLine(line) + column;
}
/**
* Selects the range.
*
* @param line the line number.
* @param column the column number.
* @param length the length of the selection.
*/
public void selectRange(final int line, final int column, final int length) {
checkEnabled();
asyncExec(new VoidResult() {
public void run() {
int offset = offset(line, column);
getControl().setSelection(offset, offset + length);
}
});
notify(SWT.Selection);
}
/**
* Gets the current selection text.
*
* @return the selection in the styled text
*/
public String getSelection() {
return syncExec(new StringResult() {
public String run() {
return getControl().getSelectionText();
}
});
}
/**
* Gets the style information.
*
* @param line the line number.
* @param column the column number.
* @param length the length.
* @return the styles in the specified range.
* @see StyledText#getStyleRanges(int, int)
*/
public StyleRange[] getStyles(final int line, final int column, final int length) {
return (StyleRange[]) syncExec(new ObjectResult() {
public Object run() {
return getControl().getStyleRanges(offset(line, column), length);
}
});
}
/**
* Gets the text on the current line.
*
* @return the text on the current line, without the line delimiters.
* @see SWTBotStyledText#getTextOnLine(int)
*/
public String getTextOnCurrentLine() {
final Position currentPosition = cursorPosition();
final int line = currentPosition.line;
return getTextOnLine(line);
}
/**
* Gets the text on the line.
* <p>
* TODO: throw exception if the line is out of range.
* </p>
*
* @param line the line number.
* @return the text on the given line number, without the line delimiters.
*/
public String getTextOnLine(final int line) {
return syncExec(new StringResult() {
public String run() {
return getControl().getContent().getLine(line);
}
});
}
/**
* Checks if this has a bullet on the current line.
*
* @return <code>true</code> if the styledText has a bullet on the given line, <code>false</code> otherwise.
* @see StyledText#getLineBullet(int)
*/
public boolean hasBulletOnCurrentLine() {
return hasBulletOnLine(cursorPosition().line);
}
/**
* Gets if this has a bullet on the specific line.
*
* @param line the line number.
* @return <code>true</code> if the styledText has a bullet on the given line, <code>false</code> otherwise.
* @see StyledText#getLineBullet(int)
*/
public boolean hasBulletOnLine(final int line) {
return getBulletOnLine(line) != null;
}
/**
* Gets the bullet on the current line.
*
* @return the bullet on the current line.
* @see StyledText#getLineBullet(int)
*/
public Bullet getBulletOnCurrentLine() {
return getBulletOnLine(cursorPosition().line);
}
/**
* Gets the bullet on the given line.
*
* @param line the line number.
* @return the bullet on the given line.
* @see StyledText#getLineBullet(int)
*/
public Bullet getBulletOnLine(final int line) {
return (Bullet) syncExec(new ObjectResult() {
public Object run() {
return getControl().getLineBullet(line);
}
});
}
/**
* Selects the text on the specified line.
*
* @param line the line number.
* @since 1.1
*/
public void selectLine(int line) {
selectRange(line, 0, getTextOnLine(line).length());
}
/**
* Selects the text on the current line.
*
* @since 1.1
*/
public void selectCurrentLine() {
selectLine(cursorPosition().line);
}
}
| UTF-8 | Java | 12,160 | java | SWTBotStyledText.java | Java | [
{
"context": "rt org.eclipse.swt.widgets.Widget;\n\n/**\n * @author Ketan Padegaonkar <KetanPadegaonkar [at] gmail [dot] com>\n * ",
"end": 1395,
"score": 0.9999002814292908,
"start": 1378,
"tag": "NAME",
"value": "Ketan Padegaonkar"
}
] | null | [] | /*******************************************************************************
* Copyright 2007 SWTBot, http://swtbot.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package net.sf.swtbot.widgets;
import net.sf.swtbot.finder.Finder;
import net.sf.swtbot.finder.UIThreadRunnable.ObjectResult;
import net.sf.swtbot.finder.UIThreadRunnable.StringResult;
import net.sf.swtbot.finder.UIThreadRunnable.VoidResult;
import net.sf.swtbot.utils.Position;
import net.sf.swtbot.utils.SWTUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.Bullet;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.StyledTextContent;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Widget;
/**
* @author <NAME> <KetanPadegaonkar [at] gmail [dot] com>
* @version $Id: SWTBotStyledText.java 804 2008-06-28 14:56:44Z kpadegaonkar $
*/
public class SWTBotStyledText extends AbstractLabelSWTBot {
private static final int TYPE_INTERVAL = 50;
/**
* @param finder the finder used to find controls.
* @param text the text on the control.
* @throws WidgetNotFoundException if the widget is not found.
*/
public SWTBotStyledText(Finder finder, String text) throws WidgetNotFoundException {
super(finder, text);
}
/**
* Constructs a new instance of this object.
*
* @param styledText the widget.
* @throws WidgetNotFoundException if the widget is <code>null</code> or widget has been disposed.
*/
public SWTBotStyledText(Widget styledText) throws WidgetNotFoundException {
super(styledText);
}
protected Class nextWidgetType() {
return StyledText.class;
}
/**
* Sets the text into the styled text.
*
* @param text the text to set.
*/
public void setText(final String text) {
checkEnabled();
asyncExec(new VoidResult() {
public void run() {
getControl().setText(text);
}
});
}
/**
* Gets the control.
*
* @return The {@link StyledText}.
*/
private StyledText getControl() {
return (StyledText) widget;
}
/**
* Notifies of the keyboard event.
* <p>
* FIXME need some work for CTRL|SHIFT + 1 the 1 is to be sent as '!' in this case.
* </p>
*
* @param modificationKey the modification key.
* @param c the character.
* @see Event#character
* @see Event#stateMask
*/
public void notifyKeyboardEvent(int modificationKey, char c) {
setFocus();
notifyKeyboardEvent(modificationKey, c, 0);
}
/**
* Notifies of keyboard event.
*
* @param modificationKey the modification key.
* @param c the character.
* @param keyCode the keycode.
* @see Event#keyCode
* @see Event#character
* @see Event#stateMask
*/
public void notifyKeyboardEvent(int modificationKey, char c, int keyCode) {
if (log.isDebugEnabled())
log.debug("Enquing keyboard notification: " + toString(modificationKey, c));
checkEnabled();
notify(SWT.KeyDown, keyEvent(modificationKey, c, keyCode));
notify(SWT.KeyUp, keyEvent(modificationKey, c, keyCode));
}
/**
* Converts the given data to a string.
*
* @param modificationKey The modification key.
* @param c The character.
* @return The string.
*/
private String toString(int modificationKey, char c) {
String mod = "";
if ((modificationKey & SWT.CTRL) != 0)
mod += "SWT.CTRL + ";
if ((modificationKey & SWT.SHIFT) != 0)
mod += "SWT.SHIFT + ";
int lastPlus = mod.lastIndexOf(" + ");
if (lastPlus == (mod.length() - 3))
mod = mod.substring(0, mod.length() - 3) + " + ";
mod = mod + c;
return mod;
}
/**
* Gets the key event.
*
* @param c the character.
* @param modificationKey the modification key.
* @return a key event with the specified keys.
* @see Event#character
* @see Event#stateMask
*/
protected Event keyEvent(int modificationKey, char c) {
return keyEvent(modificationKey, c, c);
}
/**
* Gets the key event.
*
* @param c the character.
* @param modificationKey the modification key.
* @param keyCode the keycode.
* @return a key event with the specified keys.
* @see Event#keyCode
* @see Event#character
* @see Event#stateMask
*/
protected Event keyEvent(int modificationKey, char c, int keyCode) {
Event keyEvent = createEvent();
keyEvent.stateMask = modificationKey;
keyEvent.character = c;
keyEvent.keyCode = keyCode;
return keyEvent;
}
/**
* Sets the caret at the specified location.
*
* @param line the line numnber.
* @param column the column number.
*/
public void navigateTo(final int line, final int column) {
if (log.isDebugEnabled())
log.debug("Enquing navigation to location " + line + ", " + column + " in " + SWTUtils.toString(widget));
checkEnabled();
setFocus();
asyncExec(new VoidResult() {
public void run() {
if (log.isDebugEnabled())
log.debug("Navigating to location " + line + ", " + column + " in " + widget);
getControl().setSelection(offset(line, column));
}
});
}
/**
* Gets the current position of the cursor.
*
* @return the position of the cursor in the styled text.
*/
public Position cursorPosition() {
return (Position) syncExec(new ObjectResult() {
public Object run() {
getControl().setFocus();
int offset = getControl().getSelectionRange().x;
int lineNumber = getControl().getContent().getLineAtOffset(offset);
int offsetAtLine = getControl().getContent().getOffsetAtLine(lineNumber);
int columnNumber = offset - offsetAtLine;
return new Position(lineNumber, columnNumber);
}
});
}
/**
* Types the text at the given location.
*
* @param line the line number.
* @param column the column number.
* @param text the text to be typed at the specified location
* @since 1.0
*/
public void typeText(int line, int column, String text) {
navigateTo(line, column);
typeText(text);
}
/**
* Inserts text at the given location.
*
* @param line the line number.
* @param column the column number.
* @param text the text to be inserted at the specified location
*/
public void insertText(int line, int column, String text) {
navigateTo(line, column);
insertText(text);
}
/**
* Inserts text at the end.
* <p>
* FIXME handle line endings
* </p>
*
* @param text the text to be inserted at the location of the caret.
*/
public void insertText(final String text) {
checkEnabled();
syncExec(new VoidResult() {
public void run() {
getControl().insert(text);
}
});
}
/**
* Types the text.
* <p>
* FIXME handle line endings
* </p>
*
* @param text the text to be typed at the location of the caret.
* @since 1.0
*/
public void typeText(final String text) {
typeText(text, TYPE_INTERVAL);
}
/**
* Types the text.
* <p>
* FIXME handle line endings
* </p>
*
* @param text the text to be typed at the location of the caret.
* @param interval the interval between consecutive key strokes.
* @since 1.0
*/
public void typeText(final String text, int interval) {
if (log.isDebugEnabled())
log.debug("Inserting text:" + text + " into styledtext" + SWTUtils.toString(widget));
setFocus();
for (int i = 0; i < text.length(); i++) {
notifyKeyboardEvent(SWT.NONE, text.charAt(i));
sleep(interval);
}
}
/**
* Gets the style for the given line.
*
* @param line the line number.
* @param column the column number.
* @return the {@link StyleRange} at the specified location
*/
public StyleRange getStyle(final int line, final int column) {
return (StyleRange) syncExec(new ObjectResult() {
public Object run() {
return getControl().getStyleRangeAtOffset(offset(line, column));
}
});
}
/**
* Gets the offset.
*
* @param line the line number.
* @param column the column number.
* @return the character offset at the specified location in the styledtext.
* @see StyledTextContent#getOffsetAtLine(int)
*/
protected int offset(final int line, final int column) {
return getControl().getContent().getOffsetAtLine(line) + column;
}
/**
* Selects the range.
*
* @param line the line number.
* @param column the column number.
* @param length the length of the selection.
*/
public void selectRange(final int line, final int column, final int length) {
checkEnabled();
asyncExec(new VoidResult() {
public void run() {
int offset = offset(line, column);
getControl().setSelection(offset, offset + length);
}
});
notify(SWT.Selection);
}
/**
* Gets the current selection text.
*
* @return the selection in the styled text
*/
public String getSelection() {
return syncExec(new StringResult() {
public String run() {
return getControl().getSelectionText();
}
});
}
/**
* Gets the style information.
*
* @param line the line number.
* @param column the column number.
* @param length the length.
* @return the styles in the specified range.
* @see StyledText#getStyleRanges(int, int)
*/
public StyleRange[] getStyles(final int line, final int column, final int length) {
return (StyleRange[]) syncExec(new ObjectResult() {
public Object run() {
return getControl().getStyleRanges(offset(line, column), length);
}
});
}
/**
* Gets the text on the current line.
*
* @return the text on the current line, without the line delimiters.
* @see SWTBotStyledText#getTextOnLine(int)
*/
public String getTextOnCurrentLine() {
final Position currentPosition = cursorPosition();
final int line = currentPosition.line;
return getTextOnLine(line);
}
/**
* Gets the text on the line.
* <p>
* TODO: throw exception if the line is out of range.
* </p>
*
* @param line the line number.
* @return the text on the given line number, without the line delimiters.
*/
public String getTextOnLine(final int line) {
return syncExec(new StringResult() {
public String run() {
return getControl().getContent().getLine(line);
}
});
}
/**
* Checks if this has a bullet on the current line.
*
* @return <code>true</code> if the styledText has a bullet on the given line, <code>false</code> otherwise.
* @see StyledText#getLineBullet(int)
*/
public boolean hasBulletOnCurrentLine() {
return hasBulletOnLine(cursorPosition().line);
}
/**
* Gets if this has a bullet on the specific line.
*
* @param line the line number.
* @return <code>true</code> if the styledText has a bullet on the given line, <code>false</code> otherwise.
* @see StyledText#getLineBullet(int)
*/
public boolean hasBulletOnLine(final int line) {
return getBulletOnLine(line) != null;
}
/**
* Gets the bullet on the current line.
*
* @return the bullet on the current line.
* @see StyledText#getLineBullet(int)
*/
public Bullet getBulletOnCurrentLine() {
return getBulletOnLine(cursorPosition().line);
}
/**
* Gets the bullet on the given line.
*
* @param line the line number.
* @return the bullet on the given line.
* @see StyledText#getLineBullet(int)
*/
public Bullet getBulletOnLine(final int line) {
return (Bullet) syncExec(new ObjectResult() {
public Object run() {
return getControl().getLineBullet(line);
}
});
}
/**
* Selects the text on the specified line.
*
* @param line the line number.
* @since 1.1
*/
public void selectLine(int line) {
selectRange(line, 0, getTextOnLine(line).length());
}
/**
* Selects the text on the current line.
*
* @since 1.1
*/
public void selectCurrentLine() {
selectLine(cursorPosition().line);
}
}
| 12,149 | 0.668832 | 0.664967 | 455 | 25.725275 | 23.844398 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.582418 | false | false | 13 |
aaecdf42878666cf63a210ad2b0893a60786b9e8 | 26,379,689,182,544 | d09fe4e45a6420c5f228224a773eb5fab8344c5b | /JavaWeb/EJBExercise/src/bg/jwd/servlets/HomeServlet.java | d8bd6b7d3c39947324e1a7996a9918085a3a4f71 | [
"MIT"
] | permissive | KaPrimov/JavaEECourses | https://github.com/KaPrimov/JavaEECourses | 9b6b8feb2a46ac11ff90f23654f9d2c3839cafba | b19e0fc530565c2922fbf08357fdf00828017f37 | refs/heads/master | 2018-11-28T12:26:51.298000 | 2018-09-17T11:26:15 | 2018-09-17T11:26:15 | 108,261,829 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bg.jwd.servlets;
import java.io.IOException;
import java.math.BigDecimal;
import javax.ejb.EJB;
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 bg.jwd.ejbs.api.BankTransaction;
/**
* Servlet implementation class HomeServlet
*/
@WebServlet("/Home")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private BankTransaction bankTransaction;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
BigDecimal lastAmount = bankTransaction.getLastUserAmount();
request.setAttribute("amount", lastAmount);
httpRequest.getRequestDispatcher("/page/form.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mode = request.getParameter("operation");
BigDecimal amount = new BigDecimal(request.getParameter("transactionAmount"));
String client = request.getParameter("client");
if (mode.toLowerCase().trim().equals("deposit")) {
this.bankTransaction.deposit(client, amount);
} else if (mode.toLowerCase().trim().equals("withdraw")) {
this.bankTransaction.withdraw(client, amount);
}
this.doGet(request, response);
}
}
| UTF-8 | Java | 1,714 | java | HomeServlet.java | Java | [] | null | [] | package bg.jwd.servlets;
import java.io.IOException;
import java.math.BigDecimal;
import javax.ejb.EJB;
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 bg.jwd.ejbs.api.BankTransaction;
/**
* Servlet implementation class HomeServlet
*/
@WebServlet("/Home")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private BankTransaction bankTransaction;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
BigDecimal lastAmount = bankTransaction.getLastUserAmount();
request.setAttribute("amount", lastAmount);
httpRequest.getRequestDispatcher("/page/form.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mode = request.getParameter("operation");
BigDecimal amount = new BigDecimal(request.getParameter("transactionAmount"));
String client = request.getParameter("client");
if (mode.toLowerCase().trim().equals("deposit")) {
this.bankTransaction.deposit(client, amount);
} else if (mode.toLowerCase().trim().equals("withdraw")) {
this.bankTransaction.withdraw(client, amount);
}
this.doGet(request, response);
}
}
| 1,714 | 0.783547 | 0.782964 | 51 | 32.607841 | 31.105185 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.509804 | false | false | 13 |
d19c46550028f6f54305b6acf800fc969d3d7a42 | 25,580,825,275,167 | fab96025ef998ab4997dd347c69a36a7b655b134 | /Retail_Chinese_data/Retail_AvgCostPricePerUnit/src/MapClass.java | 8a4f691d95bfc68f1d5b3cd6f195a38506ef63a4 | [] | no_license | arvindpe/MapReduceCode | https://github.com/arvindpe/MapReduceCode | 98bef696191473a2144ecaa0c00d28a839b56eea | 47c6690e3327ac7b6fde46d0be468316e700a793 | refs/heads/master | 2021-06-13T01:18:58.026000 | 2017-03-23T05:25:44 | 2017-03-23T05:25:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class MapClass extends Mapper<LongWritable, Text,Text, Text>
{
public void map(LongWritable key, Text value, Context context ) throws IOException, InterruptedException
{
String record = value.toString();
String[] parts = record.split(";");
String product_id=parts[5];
String qty=parts[6];
String cost=parts[7];
context.write(new Text(product_id),new Text(qty+","+cost));
}
}
| UTF-8 | Java | 570 | java | MapClass.java | Java | [] | null | [] | import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class MapClass extends Mapper<LongWritable, Text,Text, Text>
{
public void map(LongWritable key, Text value, Context context ) throws IOException, InterruptedException
{
String record = value.toString();
String[] parts = record.split(";");
String product_id=parts[5];
String qty=parts[6];
String cost=parts[7];
context.write(new Text(product_id),new Text(qty+","+cost));
}
}
| 570 | 0.712281 | 0.707018 | 23 | 23.782608 | 27.150076 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.217391 | false | false | 13 |
257b0c1afe4b45f5ccb05e30247c6400c474b4c8 | 30,193,620,143,398 | 357babaef8454c0962b0ebb8d540dd5432a13dc8 | /prototype/commons/src/main/java/com/xxxx/it/go/commons/response/ui/gen/NavElementType.java | 628dbb3be70baf1889cc64611548ccfa3ea8dd1b | [] | no_license | hpang123/Sandbox | https://github.com/hpang123/Sandbox | da48abcb5cd0e13f4eb0f40b09f0511c8e1961e4 | cd76ca34f8946ff8f3494bef11fc405ae353afa0 | refs/heads/master | 2018-07-19T17:06:01.383000 | 2018-07-13T02:36:28 | 2018-07-13T02:36:28 | 14,911,466 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference
// Implementation, vhudson-jaxb-ri-2.1-661
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.07.02 at 10:04:39 AM EDT
//
package com.xxxx.it.go.commons.response.ui.gen;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for navElementType complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="navElementType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="landingTypeCode" type="{}landingEnum" minOccurs="0"/>
* <element name="stateCode" type="{}StateEnum" minOccurs="0"/>
* <element name="flags" type="{}FlagEnum"/>
* <element name="sortOrder" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="displayText" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="isDefault" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="imageUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="uri" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="relativeUriPath" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="viewType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="returnDataType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="info" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="navElements" type="{}navElementsType" minOccurs="0"/>
* </sequence>
* <attribute name="pcCode" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "navElementType", propOrder = {"landingTypeCode", "stateCode", "flags", "sortOrder", "displayText", "isDefault",
"imageUrl", "uri", "relativeUriPath", "viewType", "returnDataType", "info", "navElements"})
public class NavElementType {
protected LandingEnum landingTypeCode;
protected StateEnum stateCode;
@XmlElement(required = true)
protected FlagEnum flags;
protected int sortOrder;
@XmlElement(required = true)
protected String displayText;
protected boolean isDefault;
protected String imageUrl;
protected String uri;
protected String relativeUriPath;
protected String viewType;
protected String returnDataType;
protected String info;
protected NavElementsType navElements;
@XmlAttribute(required = true)
protected String pcCode;
/**
* Gets the value of the landingTypeCode property.
*
* @return possible object is {@link LandingEnum }
*
*/
public LandingEnum getLandingTypeCode() {
return landingTypeCode;
}
/**
* Sets the value of the landingTypeCode property.
*
* @param value allowed object is {@link LandingEnum }
*
*/
public void setLandingTypeCode(LandingEnum value) {
this.landingTypeCode = value;
}
/**
* Gets the value of the stateCode property.
*
* @return possible object is {@link StateEnum }
*
*/
public StateEnum getStateCode() {
return stateCode;
}
/**
* Sets the value of the stateCode property.
*
* @param value allowed object is {@link StateEnum }
*
*/
public void setStateCode(StateEnum value) {
this.stateCode = value;
}
/**
* Gets the value of the flags property.
*
* @return possible object is {@link FlagEnum }
*
*/
public FlagEnum getFlags() {
return flags;
}
/**
* Sets the value of the flags property.
*
* @param value allowed object is {@link FlagEnum }
*
*/
public void setFlags(FlagEnum value) {
this.flags = value;
}
/**
* Gets the value of the sortOrder property.
*
*/
public int getSortOrder() {
return sortOrder;
}
/**
* Sets the value of the sortOrder property.
*
*/
public void setSortOrder(int value) {
this.sortOrder = value;
}
/**
* Gets the value of the displayText property.
*
* @return possible object is {@link String }
*
*/
public String getDisplayText() {
return displayText;
}
/**
* Sets the value of the displayText property.
*
* @param value allowed object is {@link String }
*
*/
public void setDisplayText(String value) {
this.displayText = value;
}
/**
* Gets the value of the isDefault property.
*
*/
public boolean isIsDefault() {
return isDefault;
}
/**
* Sets the value of the isDefault property.
*
*/
public void setIsDefault(boolean value) {
this.isDefault = value;
}
/**
* Gets the value of the imageUrl property.
*
* @return possible object is {@link String }
*
*/
public String getImageUrl() {
return imageUrl;
}
/**
* Sets the value of the imageUrl property.
*
* @param value allowed object is {@link String }
*
*/
public void setImageUrl(String value) {
this.imageUrl = value;
}
/**
* Gets the value of the uri property.
*
* @return possible object is {@link String }
*
*/
public String getUri() {
return uri;
}
/**
* Sets the value of the uri property.
*
* @param value allowed object is {@link String }
*
*/
public void setUri(String value) {
this.uri = value;
}
/**
* Gets the value of the relativeUriPath property.
*
* @return possible object is {@link String }
*
*/
public String getRelativeUriPath() {
return relativeUriPath;
}
/**
* Sets the value of the relativeUriPath property.
*
* @param value allowed object is {@link String }
*
*/
public void setRelativeUriPath(String value) {
this.relativeUriPath = value;
}
/**
* Gets the value of the viewType property.
*
* @return possible object is {@link String }
*
*/
public String getViewType() {
return viewType;
}
/**
* Sets the value of the viewType property.
*
* @param value allowed object is {@link String }
*
*/
public void setViewType(String value) {
this.viewType = value;
}
/**
* Gets the value of the returnDataType property.
*
* @return possible object is {@link String }
*
*/
public String getReturnDataType() {
return returnDataType;
}
/**
* Sets the value of the returnDataType property.
*
* @param value allowed object is {@link String }
*
*/
public void setReturnDataType(String value) {
this.returnDataType = value;
}
/**
* Gets the value of the info property.
*
* @return possible object is {@link String }
*
*/
public String getInfo() {
return info;
}
/**
* Sets the value of the info property.
*
* @param value allowed object is {@link String }
*
*/
public void setInfo(String value) {
this.info = value;
}
/**
* Gets the value of the navElements property.
*
* @return possible object is {@link NavElementsType }
*
*/
public NavElementsType getNavElements() {
return navElements;
}
/**
* Sets the value of the navElements property.
*
* @param value allowed object is {@link NavElementsType }
*
*/
public void setNavElements(NavElementsType value) {
this.navElements = value;
}
/**
* Gets the value of the pcCode property.
*
* @return possible object is {@link String }
*
*/
public String getPcCode() {
return pcCode;
}
/**
* Sets the value of the pcCode property.
*
* @param value allowed object is {@link String }
*
*/
public void setPcCode(String value) {
this.pcCode = value;
}
}
| UTF-8 | Java | 9,078 | java | NavElementType.java | Java | [] | null | [] | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference
// Implementation, vhudson-jaxb-ri-2.1-661
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.07.02 at 10:04:39 AM EDT
//
package com.xxxx.it.go.commons.response.ui.gen;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for navElementType complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="navElementType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="landingTypeCode" type="{}landingEnum" minOccurs="0"/>
* <element name="stateCode" type="{}StateEnum" minOccurs="0"/>
* <element name="flags" type="{}FlagEnum"/>
* <element name="sortOrder" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="displayText" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="isDefault" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="imageUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="uri" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="relativeUriPath" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="viewType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="returnDataType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="info" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="navElements" type="{}navElementsType" minOccurs="0"/>
* </sequence>
* <attribute name="pcCode" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "navElementType", propOrder = {"landingTypeCode", "stateCode", "flags", "sortOrder", "displayText", "isDefault",
"imageUrl", "uri", "relativeUriPath", "viewType", "returnDataType", "info", "navElements"})
public class NavElementType {
protected LandingEnum landingTypeCode;
protected StateEnum stateCode;
@XmlElement(required = true)
protected FlagEnum flags;
protected int sortOrder;
@XmlElement(required = true)
protected String displayText;
protected boolean isDefault;
protected String imageUrl;
protected String uri;
protected String relativeUriPath;
protected String viewType;
protected String returnDataType;
protected String info;
protected NavElementsType navElements;
@XmlAttribute(required = true)
protected String pcCode;
/**
* Gets the value of the landingTypeCode property.
*
* @return possible object is {@link LandingEnum }
*
*/
public LandingEnum getLandingTypeCode() {
return landingTypeCode;
}
/**
* Sets the value of the landingTypeCode property.
*
* @param value allowed object is {@link LandingEnum }
*
*/
public void setLandingTypeCode(LandingEnum value) {
this.landingTypeCode = value;
}
/**
* Gets the value of the stateCode property.
*
* @return possible object is {@link StateEnum }
*
*/
public StateEnum getStateCode() {
return stateCode;
}
/**
* Sets the value of the stateCode property.
*
* @param value allowed object is {@link StateEnum }
*
*/
public void setStateCode(StateEnum value) {
this.stateCode = value;
}
/**
* Gets the value of the flags property.
*
* @return possible object is {@link FlagEnum }
*
*/
public FlagEnum getFlags() {
return flags;
}
/**
* Sets the value of the flags property.
*
* @param value allowed object is {@link FlagEnum }
*
*/
public void setFlags(FlagEnum value) {
this.flags = value;
}
/**
* Gets the value of the sortOrder property.
*
*/
public int getSortOrder() {
return sortOrder;
}
/**
* Sets the value of the sortOrder property.
*
*/
public void setSortOrder(int value) {
this.sortOrder = value;
}
/**
* Gets the value of the displayText property.
*
* @return possible object is {@link String }
*
*/
public String getDisplayText() {
return displayText;
}
/**
* Sets the value of the displayText property.
*
* @param value allowed object is {@link String }
*
*/
public void setDisplayText(String value) {
this.displayText = value;
}
/**
* Gets the value of the isDefault property.
*
*/
public boolean isIsDefault() {
return isDefault;
}
/**
* Sets the value of the isDefault property.
*
*/
public void setIsDefault(boolean value) {
this.isDefault = value;
}
/**
* Gets the value of the imageUrl property.
*
* @return possible object is {@link String }
*
*/
public String getImageUrl() {
return imageUrl;
}
/**
* Sets the value of the imageUrl property.
*
* @param value allowed object is {@link String }
*
*/
public void setImageUrl(String value) {
this.imageUrl = value;
}
/**
* Gets the value of the uri property.
*
* @return possible object is {@link String }
*
*/
public String getUri() {
return uri;
}
/**
* Sets the value of the uri property.
*
* @param value allowed object is {@link String }
*
*/
public void setUri(String value) {
this.uri = value;
}
/**
* Gets the value of the relativeUriPath property.
*
* @return possible object is {@link String }
*
*/
public String getRelativeUriPath() {
return relativeUriPath;
}
/**
* Sets the value of the relativeUriPath property.
*
* @param value allowed object is {@link String }
*
*/
public void setRelativeUriPath(String value) {
this.relativeUriPath = value;
}
/**
* Gets the value of the viewType property.
*
* @return possible object is {@link String }
*
*/
public String getViewType() {
return viewType;
}
/**
* Sets the value of the viewType property.
*
* @param value allowed object is {@link String }
*
*/
public void setViewType(String value) {
this.viewType = value;
}
/**
* Gets the value of the returnDataType property.
*
* @return possible object is {@link String }
*
*/
public String getReturnDataType() {
return returnDataType;
}
/**
* Sets the value of the returnDataType property.
*
* @param value allowed object is {@link String }
*
*/
public void setReturnDataType(String value) {
this.returnDataType = value;
}
/**
* Gets the value of the info property.
*
* @return possible object is {@link String }
*
*/
public String getInfo() {
return info;
}
/**
* Sets the value of the info property.
*
* @param value allowed object is {@link String }
*
*/
public void setInfo(String value) {
this.info = value;
}
/**
* Gets the value of the navElements property.
*
* @return possible object is {@link NavElementsType }
*
*/
public NavElementsType getNavElements() {
return navElements;
}
/**
* Sets the value of the navElements property.
*
* @param value allowed object is {@link NavElementsType }
*
*/
public void setNavElements(NavElementsType value) {
this.navElements = value;
}
/**
* Gets the value of the pcCode property.
*
* @return possible object is {@link String }
*
*/
public String getPcCode() {
return pcCode;
}
/**
* Sets the value of the pcCode property.
*
* @param value allowed object is {@link String }
*
*/
public void setPcCode(String value) {
this.pcCode = value;
}
}
| 9,078 | 0.592311 | 0.583168 | 353 | 24.716713 | 24.793634 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.252125 | false | false | 13 |
98f76a28c290a8f943e313d0bedd0f9aa1442b07 | 27,152,783,295,166 | c4a62b4d6479985868a5e9983d56dbcaead72fdb | /src/main/java/com/wujincheng/mrpccommon/filter/Filter.java | 1f773837b7a13d84ef879d6763595dca182ceff0 | [] | no_license | wujincheng2333/mrpc-common | https://github.com/wujincheng2333/mrpc-common | 1f59f2009d9e8bcb5b0b715397a3bfd18b6e2d3a | 716f8f3b146ca4f4fe925f546d7db666bc2fb455 | refs/heads/master | 2023-02-16T17:48:54.435000 | 2021-01-20T02:56:10 | 2021-01-20T02:56:10 | 325,482,413 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wujincheng.mrpccommon.filter;
import com.wujincheng.mrpccommon.invoke.Invocation;
import com.wujincheng.mrpccommon.invoke.MyInvoker;
public interface Filter {
Object invoke(MyInvoker invoker, Invocation invocation);
}
| UTF-8 | Java | 237 | java | Filter.java | Java | [] | null | [] | package com.wujincheng.mrpccommon.filter;
import com.wujincheng.mrpccommon.invoke.Invocation;
import com.wujincheng.mrpccommon.invoke.MyInvoker;
public interface Filter {
Object invoke(MyInvoker invoker, Invocation invocation);
}
| 237 | 0.818565 | 0.818565 | 9 | 25.333334 | 24.110855 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 13 |
493943336f49b568d0ef9ed88d07ee05c8264092 | 20,160,576,488,793 | 83e7d1b0bf608146e07c688c8788b655b8616546 | /src/main/java/com/krishDev/Tasks/services/UserService.java | eefcb7a03ed80b416bfa23e6b4044297350cf41e | [] | no_license | mksphaninder/task-manager | https://github.com/mksphaninder/task-manager | 2f453f7968c17713b9c00a8184d2af4f603f3e95 | c195602648c5f1e29ecb68f1f793799e8f6e845a | refs/heads/master | 2022-12-24T22:07:03.477000 | 2020-08-03T00:28:34 | 2020-08-03T00:28:34 | 280,974,575 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.krishDev.Tasks.services;
import java.util.List;
import java.util.Optional;
import com.krishDev.Tasks.models.User;
import com.krishDev.Tasks.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public boolean userExists(String email) {
User user = userRepository.findByEmail(email);
return user == null ? false: true;
}
} | UTF-8 | Java | 551 | java | UserService.java | Java | [] | null | [] | package com.krishDev.Tasks.services;
import java.util.List;
import java.util.Optional;
import com.krishDev.Tasks.models.User;
import com.krishDev.Tasks.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public boolean userExists(String email) {
User user = userRepository.findByEmail(email);
return user == null ? false: true;
}
} | 551 | 0.753176 | 0.753176 | 23 | 23 | 20.926373 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 13 |
eebb6b358b8578726d66452422f18f61b44778d8 | 21,036,749,872,292 | 2e48499218e48e80700fba43dcf557093d616cad | /client/src/main/java/com/xilidou/config/RpcConfig.java | 065da80bd083e23cb13afa1b2c024472b90b952e | [] | no_license | diaozxin007/DouRpc | https://github.com/diaozxin007/DouRpc | 7e268dab2d9aaaaa395ea78018a7c563805335dc | f9943048dfc47ff7a981c9c658c143b63aaa21d9 | refs/heads/master | 2023-04-07T09:59:07.624000 | 2020-07-30T03:34:11 | 2020-07-30T03:34:11 | 150,297,319 | 56 | 26 | null | false | 2023-03-31T14:51:02 | 2018-09-25T16:36:27 | 2023-03-23T08:27:55 | 2023-03-31T14:50:59 | 45 | 46 | 20 | 1 | Java | false | false | package com.xilidou.config;
import com.xilidou.annotation.RpcInterface;
import com.xilidou.proxy.ProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.ReflectionUtils;
import java.util.Map;
import java.util.Set;
/**
* @author zhengxin
*/
@Configuration
@Slf4j
public class RpcConfig implements ApplicationContextAware,InitializingBean {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
Reflections reflections = new Reflections("com.xilidou");
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RpcInterface.class);
for (Class<?> aClass : typesAnnotatedWith) {
beanFactory.registerSingleton(aClass.getSimpleName(),ProxyFactory.create(aClass));
}
log.info("afterPropertiesSet is {}",typesAnnotatedWith);
}
}
| UTF-8 | Java | 2,009 | java | RpcConfig.java | Java | [
{
"context": "va.util.Map;\nimport java.util.Set;\n\n/**\n * @author zhengxin\n */\n@Configuration\n@Slf4j\npublic class RpcConfig ",
"end": 1153,
"score": 0.9930862784385681,
"start": 1145,
"tag": "USERNAME",
"value": "zhengxin"
}
] | null | [] | package com.xilidou.config;
import com.xilidou.annotation.RpcInterface;
import com.xilidou.proxy.ProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.ReflectionUtils;
import java.util.Map;
import java.util.Set;
/**
* @author zhengxin
*/
@Configuration
@Slf4j
public class RpcConfig implements ApplicationContextAware,InitializingBean {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
Reflections reflections = new Reflections("com.xilidou");
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(RpcInterface.class);
for (Class<?> aClass : typesAnnotatedWith) {
beanFactory.registerSingleton(aClass.getSimpleName(),ProxyFactory.create(aClass));
}
log.info("afterPropertiesSet is {}",typesAnnotatedWith);
}
}
| 2,009 | 0.845694 | 0.844201 | 49 | 40 | 31.895876 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.122449 | false | false | 13 |
1792eec2ec71801a4cb98c91570e52c25b93603f | 30,159,260,409,285 | 6d2c6d944178a98a0cf8df568b9fd41d208a9a39 | /Utilities/src/main/java/syne/regularize/timesheet/RegularizeTimesheet.java | bb579bc025aca25412242038cc6641c9abf7fb9a | [] | no_license | siddharthshirodkar/zuul-gateway | https://github.com/siddharthshirodkar/zuul-gateway | 4556957e1a1e927c74a9073cb6f42e011c4ebb3d | 66fa8fe96a20bd6ad4728624d2487a92215d1a7b | refs/heads/master | 2021-06-26T11:46:02.319000 | 2020-01-10T07:56:12 | 2020-01-10T07:56:12 | 233,030,500 | 0 | 0 | null | false | 2021-06-15T16:03:20 | 2020-01-10T11:11:51 | 2020-01-10T11:12:38 | 2021-06-15T16:03:19 | 4,192 | 0 | 0 | 2 | Java | false | false | package syne.regularize.timesheet;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
public class RegularizeTimesheet {
private static enum BROWSER_TYPE {FIREFOX, CHROME, INTERNET_EXPLORER};
private static HashMap<BROWSER_TYPE, String> browserToDriverNameMap = new HashMap<BROWSER_TYPE, String>();
static
{
browserToDriverNameMap.put(BROWSER_TYPE.FIREFOX, "gecko");
browserToDriverNameMap.put(BROWSER_TYPE.CHROME, "chrome");
}
//Select the type of browser to be used
private static final BROWSER_TYPE BROWSER = BROWSER_TYPE.CHROME;
//Selenium specific constants
//private static final String BASE_HOME_DIR = "C:/Users/siddharth.s/";
//private static final String DRIVER_PATH = BASE_HOME_DIR + "eclipse-workspace/artifacts/driverss/";
private static final String BASE_HOME_DIR = System.getProperty("user.dir");
private static final String DRIVER_PATH = BASE_HOME_DIR + "/resources/";
private static final String DRIVER_PROPERTY_NAME = "webdriver."+browserToDriverNameMap.get(BROWSER)+".driver";
private static final String DRIVER_EXE_NAME = browserToDriverNameMap.get(BROWSER)+"driver.exe";
private static final String SELENIUM_LOGGER_CLASS = "org.openqa.selenium";
//EAG Portal URLs
private static final String EAG_HOMEPAGE_URL = "https://eag.synechron.com/SYNE.UI/";
private static final String REGULARIZATION_LIST_PAGE_URL = EAG_HOMEPAGE_URL +"/Attendance/Common/Home/Index#/applications/AttendanceRegularization/List";
//EAG Portal Page Titles
private static final String TITLE_EAG_HOMEPAGE = "Enterprise Application Portal";
private static final String TITLE_SYNETIME_APPLICATIONS_PAGE = "Applications | Attendance System";
private static final String TITLE_SYNETIME_REGULARIZATION_PAGE = "Attendance Regularization | Attendance System";
private static final String TITLE_SYNETIME_REGULARIZATION_LIST_PAGE = "Attendance Regularization List | Attendance System";
private static final String TITLE_SYNETIME_ATTENDENCE_HOME = "Home | Attendance System";
private static final String BTN_APPLY_TXT = "Apply";
// Reason Code constants
private static final String REASON_CARD_SUBMITTED_TO_ADMIN = "Card submitted to Admin"+Keys.ENTER;
private static final String REASON_TRAINING = "T"+Keys.ENTER;
private static final String ATTRIBUTE_VALUE = "value";
private static final String DATE_FORMAT = "dd MMM, yyyy";
//EAG Login details
public String EAG_USERNAME = "siddharth.s";
public String EAG_PASSWORD = "qAzxsw@123";
private static final String REASON_FOR_REG = REASON_CARD_SUBMITTED_TO_ADMIN;
private static final String[] VALID_INPUT_ARGS = new String[] {"-user","-pass","-headless"};
//Configuration
private static final long SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS = 3000;
private static final long SLEEP_TO_AVOID_CLICK_INTERCEPT = 1000;
private static final int MAX_WEEKS_IN_A_MONTH = 5;
//Logs Configuration
private static final String LOG_DIR = BASE_HOME_DIR + "/logs/selenium/";
private static final String LOG_FILE_NAME = "DriverLog";
private static final String LOG_FILE_EXTENSION = ".txt";
private static final String LOG_NAME_DATE_FORMAT = "yyyyMMdd_HH_mm_ss";
private static final String SCREENSHOT_DIR = BASE_HOME_DIR + "/screenshots/";
private static final String SCREENSHOT_PREFIX = "Regularization_";
private static final boolean IS_HEADLESS = true;
private WebDriver webDriver;
public static void main(String[] args) throws Exception {
System.out.println("Started.. Browser Type - "+BROWSER);
long startTime = System.currentTimeMillis();
RegularizeTimesheet regularizeTimesheet = new RegularizeTimesheet();
regularizeTimesheet.handleArgs(args);
regularizeTimesheet.regularize();
System.out.println("Finished..");
System.out.println("Time taken = "+(System.currentTimeMillis() - startTime)/1000+" secs");
}
private void regularize() throws Exception {
openBrowser();
loginToEag();
handleDiscrepencies();
verify();
saveScreenshot();
closeBrowser();
}
private void handleArgs(String[] inputArgs) {
ArrayList<String> validInputArgsList = new ArrayList<String>(Arrays.asList(VALID_INPUT_ARGS));
HashMap<String, String> argToFieldMap = getInputArgToFieldMap();
for(int i=0;i<inputArgs.length;i++)
{
if(validInputArgsList.contains(inputArgs[i]))
{
try {
Field fld = this.getClass().getField(argToFieldMap.get(inputArgs[i]));
fld.setAccessible(true);
fld.set(this, inputArgs[++i]);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
System.out.println(inputArgs[i]+" - Not a valid arguement");
i++;
}
}
}
private void handleDiscrepencies() throws InterruptedException, ParseException, IOException{
String cssSelDecrepencyCountLink = ".attendenceDiscrepancy > span:nth-child(2)";
//WebDriverWait wait = new WebDriverWait(webDriver,3);
//wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssSelDecrepencyCountLink)));
int descrepenciesCount = Integer.valueOf(webDriver.findElement(By.cssSelector(cssSelDecrepencyCountLink)).getText());
System.out.println("Discrepencies Count == "+descrepenciesCount);
if(descrepenciesCount == 0)
{
System.out.println("No Attendence Discrepencies to be handled..");
return;
}
String cssSelRegLink = ".listing-table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(6) > a:nth-child(2)";
String cssSelInTime08hrFromDropDown = ".ui_tpicker_hour_slider > select:nth-child(1) > option:nth-child(9)";
String cssSelInTime10hrFromDropDown = ".ui_tpicker_hour_slider > select:nth-child(1) > option:nth-child(11)";
String cssSelInTime00minFromDropDown = ".ui_tpicker_minute_slider > select:nth-child(1) > option:nth-child(1)";
String cssSelOutTime16hrFromDropDown = ".ui_tpicker_hour_slider > select:nth-child(1) > option:nth-child(17)";
String cssSelOutTime18hrFromDropDown = ".ui_tpicker_hour_slider > select:nth-child(1) > option:nth-child(19)";
String cssSelOutTime00minFromDropDown = ".ui_tpicker_minute_slider > select:nth-child(1) > option:nth-child(1)";
String cssSelInandOutTimeDoneBtn = ".ui-datepicker-close";
String cssSelInTimeHrDropDown = cssSelInTime10hrFromDropDown;
String cssSelOutTimeHrFromDropDown = cssSelOutTime18hrFromDropDown;
if(REASON_FOR_REG.equalsIgnoreCase(REASON_TRAINING))
{
cssSelInTimeHrDropDown = cssSelInTime08hrFromDropDown;
cssSelOutTimeHrFromDropDown = cssSelOutTime16hrFromDropDown;
}
String cssSelApplyBtn = "input.buttons:nth-child(3)";
String idCalInDate = "InDate";
String idCalOutDate = "OutDate";
String idReasonDropDown = "Remarks";
String idInTimeDropDown = "fromPicker";
String idOutTimeDropDown = "Text1";
String startTextForWarningToIgnore = "You have already applied";
String containsTextForRetry = "Datatype size excedded";
String cssSelForToastMessage = ".toast-message";
String cssSelForLinkToRegPage = "#applicationHost > div > div > section > aside > div:nth-child(2) > div > aside.homeRightBlock > div.rightBlockLeftSection > div:nth-child(1) > span";
if(descrepenciesCount > 0)
{
webDriver.findElement(By.cssSelector(cssSelDecrepencyCountLink)).click();
waitForPageToLoad(TITLE_SYNETIME_APPLICATIONS_PAGE);
ArrayList<Date> discrepancyDatesList = populateListOfDiscrepencyDates();
for(Date discrepencyDate : discrepancyDatesList)
{
if(webDriver.getTitle().equalsIgnoreCase(TITLE_SYNETIME_ATTENDENCE_HOME))
webDriver.findElement(By.cssSelector(cssSelForLinkToRegPage)).click();
waitForPageToLoad(TITLE_SYNETIME_APPLICATIONS_PAGE);
webDriver.findElement(By.cssSelector(cssSelRegLink)).click();
waitForPageToLoad(TITLE_SYNETIME_REGULARIZATION_PAGE);
webDriver.findElement(By.id(idReasonDropDown)).click();
webDriver.findElement(By.id(idReasonDropDown)).sendKeys(REASON_FOR_REG);
webDriver.findElement(By.id(idInTimeDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelInTimeHrDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelInTime00minFromDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelInandOutTimeDoneBtn)).click();
Thread.sleep(SLEEP_TO_AVOID_CLICK_INTERCEPT);
webDriver.findElement(By.id(idOutTimeDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelOutTimeHrFromDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelOutTime00minFromDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelInandOutTimeDoneBtn)).click();
Thread.sleep(SLEEP_TO_AVOID_CLICK_INTERCEPT);
setDateDropDown(discrepencyDate, idCalInDate);
Thread.sleep(SLEEP_TO_AVOID_CLICK_INTERCEPT);
setDateDropDown(discrepencyDate, idCalOutDate);
WebElement applyBtn = webDriver.findElement(By.cssSelector(cssSelApplyBtn));
if(applyBtn.getAttribute(ATTRIBUTE_VALUE).equalsIgnoreCase(BTN_APPLY_TXT))
{
applyBtn.click();
Thread.sleep(SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS);
try
{
if(webDriver.findElement(By.cssSelector(cssSelForToastMessage)).getText().contains(containsTextForRetry))
{
applyBtn.click();
Thread.sleep(SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS);
}
if(webDriver.findElement(By.cssSelector(cssSelForToastMessage)).getText().startsWith(startTextForWarningToIgnore))
continue;
}
catch(NoSuchElementException nse)
{
continue;
}
}
descrepenciesCount--;
}
}
System.out.println("Handled All discrepencies");
}
private void setDateDropDown(Date discrepencyDate, String idDate) {
boolean selectedMonth = false, selectedYear = false;
Calendar cal = Calendar.getInstance();
cal.setTime(discrepencyDate);
webDriver.findElement(By.id(idDate)).click();
//List<WebElement> monthRows = webDriver.findElements(By.cssSelector("[class='ui-datepicker-month'] option"));
List<WebElement> monthRows = webDriver.findElements(By.cssSelector(".ui-datepicker-month > option"));
for(WebElement monthRow : monthRows)
{
if(monthRow.isSelected() && Integer.valueOf(monthRow.getAttribute(ATTRIBUTE_VALUE)) == cal.get(Calendar.MONTH))
selectedMonth = true;
}
List<WebElement> yearRows = webDriver.findElements(By.cssSelector(".ui-datepicker-year option"));
for(WebElement yearRow : yearRows)
{
if(yearRow.isSelected() && Integer.valueOf(yearRow.getAttribute(ATTRIBUTE_VALUE)) == cal.get(Calendar.YEAR))
selectedYear = true;
}
if(!selectedMonth)
{
WebElement monthRow = null;
if(idDate.equalsIgnoreCase("OutDate"))
monthRow = webDriver.findElement(By.cssSelector(".ui-datepicker-month > option:nth-child(1)"));
else
monthRow = webDriver.findElement(By.cssSelector(".ui-datepicker-month > option:nth-child("+(cal.get(Calendar.MONTH)+1)+")"));
monthRow.click();
}
if(!selectedYear)
{
for(WebElement yearRow : yearRows)
{
if(Integer.valueOf(yearRow.getAttribute(ATTRIBUTE_VALUE)) == cal.get(Calendar.YEAR))
{
selectedYear = true;
yearRow.click();
break;
}
}
}
for(int i=1;i<=MAX_WEEKS_IN_A_MONTH;i++)
{
String cssSelDayofMonth = ".ui-datepicker-calendar > tbody:nth-child(2) > tr:nth-child("+i+") > td:nth-child("+cal.get(Calendar.DAY_OF_WEEK)+") > a:nth-child(1)";
try
{
String dayOfMonthText = webDriver.findElement(By.cssSelector(cssSelDayofMonth)).getText();
if(dayOfMonthText != null && !dayOfMonthText.trim().equalsIgnoreCase("") && Integer.valueOf(dayOfMonthText) == cal.get(Calendar.DAY_OF_MONTH))
webDriver.findElement(By.cssSelector(cssSelDayofMonth)).click();
}
catch(NoSuchElementException nse)
{
continue;
}
}
}
private ArrayList<Date> populateListOfDiscrepencyDates() throws ParseException {
ArrayList<Date> discrepancyDatesList = new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String cssSelListingTableRows = "[class='listing-table'] tr";
int discrepencyRowsCount = webDriver.findElements(By.cssSelector(cssSelListingTableRows)).size();
for(int i=2; i<=discrepencyRowsCount; i++)
{
String cssSelDescrepencyDate = ".listing-table > tbody:nth-child(1) > tr:nth-child("+i+") > td:nth-child(1)";
WebElement discrepencyDateColumn = webDriver.findElement(By.cssSelector(cssSelDescrepencyDate));
Date date = sdf.parse(discrepencyDateColumn.getText());
discrepancyDatesList.add(date);
}
return discrepancyDatesList;
}
private void loginToEag() throws InterruptedException, WebDriverException, IOException
{
String idUserName = "UserName";
String idPassword = "Password";
String classNameSignInBtn = "signInBtn";
webDriver.findElement(By.id(idUserName)).clear();
webDriver.findElement(By.id(idUserName)).sendKeys(EAG_USERNAME);
webDriver.findElement(By.id(idPassword)).clear();
webDriver.findElement(By.id(idPassword)).sendKeys(EAG_PASSWORD);
webDriver.findElement(By.className(classNameSignInBtn)).click();
checkForInvalidLogin();
waitForPageToLoad(TITLE_EAG_HOMEPAGE);
System.out.println("Login Successful : user - "+EAG_USERNAME);
}
private void checkForInvalidLogin() throws InterruptedException, WebDriverException, IOException{
Thread.sleep(SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS);
String cssSelForInvalidLoginText = "body > div.container.newLogOn > form > div > div.loginaccess > span";
String INVALID_LOGIN_MESSAGE = "Invalid Username / Password. Please try again";
try
{
if(webDriver.getTitle().equalsIgnoreCase(TITLE_EAG_HOMEPAGE) &&
INVALID_LOGIN_MESSAGE.equalsIgnoreCase(webDriver.findElement(By.cssSelector(cssSelForInvalidLoginText)).getText()))
{
System.out.println("Invalid login details : user - "+EAG_USERNAME+", pass - "+EAG_PASSWORD);
//Desktop.getDesktop().open(((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE));
Thread.sleep(1000);
System.exit(-1);
}
}
catch(NoSuchElementException nse)
{}
}
private void waitForPageToLoad(String pageTitle) throws InterruptedException
{
while(true)
{
if(webDriver.getTitle().equalsIgnoreCase(pageTitle))
return;
Thread.sleep(SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS);
}
}
private void openBrowser()
{
SimpleDateFormat logFileNameDateFormat = new SimpleDateFormat(LOG_NAME_DATE_FORMAT);
Logger.getLogger(SELENIUM_LOGGER_CLASS).setLevel(Level.OFF);
System.setProperty(DRIVER_PROPERTY_NAME, DRIVER_PATH+DRIVER_EXE_NAME);
switch(BROWSER)
{
case FIREFOX :
{
FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--disable-logging");
firefoxBinary.addCommandLineOptions("--headless");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,
LOG_DIR+BROWSER+"_"+LOG_FILE_NAME+"_"+logFileNameDateFormat.format(new Date())+LOG_FILE_EXTENSION);
webDriver = new FirefoxDriver(firefoxOptions);
break;
}
case CHROME :
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(IS_HEADLESS);
chromeOptions.addArguments("--start-maximized");
System.setProperty("webdriver.chrome.silentOutput", "true");
//System.setProperty("webdriver.chrome.logfile", LOG_DIR+ BROWSER+"_"+LOG_FILE_NAME+"_"+logFileNameDateFormat.format(new Date())+LOG_FILE_EXTENSION);
//System.setProperty("webdriver.chrome.verboseLogging", "true");
webDriver = new ChromeDriver(chromeOptions);
break;
}
default:
{
System.err.println("Currently Browser Type: <"+BROWSER+"> is not supported..");
System.exit(-1);
}
}
//webDriver.manage().window().maximize();
webDriver.get(EAG_HOMEPAGE_URL);
}
private void verify() throws InterruptedException, IOException{
webDriver.get(REGULARIZATION_LIST_PAGE_URL);
waitForPageToLoad(TITLE_SYNETIME_REGULARIZATION_LIST_PAGE);
//Desktop.getDesktop().open(((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE));
}
private void closeBrowser() {
webDriver.close();
}
private HashMap<String, String> getInputArgToFieldMap()
{
HashMap<String, String> argToFieldMap = new HashMap<String, String>();
argToFieldMap.put(VALID_INPUT_ARGS[0], "EAG_USERNAME");
argToFieldMap.put(VALID_INPUT_ARGS[1], "EAG_PASSWORD");
argToFieldMap.put(VALID_INPUT_ARGS[2], "IS_HEADLESS");
//argToFieldMap.put("-browser", "BROWSER");
return argToFieldMap;
}
private void saveScreenshot() throws Exception
{
SimpleDateFormat sdf = new SimpleDateFormat(LOG_NAME_DATE_FORMAT);
File screenshotFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
Path destScreenshotPath = Paths.get(SCREENSHOT_DIR+SCREENSHOT_PREFIX+sdf.format(new Date())+screenshotFile.getName().substring(screenshotFile.getName().lastIndexOf(".")));
Path srcScreenshotPath = screenshotFile.toPath();
if(!new File(SCREENSHOT_DIR).exists())
new File(SCREENSHOT_DIR).mkdirs();
Files.copy(srcScreenshotPath, destScreenshotPath, StandardCopyOption.REPLACE_EXISTING);
}
}
| UTF-8 | Java | 18,529 | java | RegularizeTimesheet.java | Java | [
{
"context": "EAG Login details\r\n\tpublic String EAG_USERNAME = \"siddharth.s\";\r\n\tpublic String EAG_PASSWORD = \"qAzxsw@123\";\r\n\t",
"end": 3511,
"score": 0.9996729493141174,
"start": 3500,
"tag": "USERNAME",
"value": "siddharth.s"
},
{
"context": " = \"siddharth.s\";\r\n\tpublic String EAG_PASSWORD = \"qAzxsw@123\";\r\n\tprivate static final String REASON_FOR_REG = ",
"end": 3556,
"score": 0.9993623495101929,
"start": 3546,
"tag": "PASSWORD",
"value": "qAzxsw@123"
},
{
"context": "xception, IOException\r\n\t{\r\n\t\tString idUserName = \"UserName\";\r\n\t\tString idPassword = \"Password\";\r\n\t\tString cl",
"end": 13881,
"score": 0.9995235204696655,
"start": 13873,
"tag": "USERNAME",
"value": "UserName"
},
{
"context": " idUserName = \"UserName\";\r\n\t\tString idPassword = \"Password\";\r\n\t\tString classNameSignInBtn = \"signInBtn\";\r\n\t\t",
"end": 13916,
"score": 0.9989045858383179,
"start": 13908,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "webDriver.findElement(By.id(idUserName)).sendKeys(EAG_USERNAME);\r\n\t\twebDriver.findElement(By.id(idPassword)).cle",
"end": 14081,
"score": 0.832133412361145,
"start": 14069,
"tag": "USERNAME",
"value": "EAG_USERNAME"
},
{
"context": "webDriver.findElement(By.id(idPassword)).sendKeys(EAG_PASSWORD);\r\n\t\twebDriver.findElement(By.className(className",
"end": 14202,
"score": 0.9871460199356079,
"start": 14190,
"tag": "PASSWORD",
"value": "EAG_PASSWORD"
},
{
"context": "login details : user - \"+EAG_USERNAME+\", pass - \"+EAG_PASSWORD);\r\n\t\t\t\t//Desktop.getDesktop().open(((TakesScreens",
"end": 15065,
"score": 0.9047627449035645,
"start": 15053,
"tag": "PASSWORD",
"value": "EAG_PASSWORD"
},
{
"context": "ng>();\r\n\t\targToFieldMap.put(VALID_INPUT_ARGS[0], \"EAG_USERNAME\");\r\n\t\targToFieldMap.put(VALID_INPUT_ARGS[1], \"EAG",
"end": 17694,
"score": 0.9934265613555908,
"start": 17682,
"tag": "USERNAME",
"value": "EAG_USERNAME"
},
{
"context": "AME\");\r\n\t\targToFieldMap.put(VALID_INPUT_ARGS[1], \"EAG_PASSWORD\");\r\n\t\targToFieldMap.put(VALID_INPUT_ARGS[",
"end": 17745,
"score": 0.8750965595245361,
"start": 17741,
"tag": "USERNAME",
"value": "EAG_"
}
] | null | [] | package syne.regularize.timesheet;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
public class RegularizeTimesheet {
private static enum BROWSER_TYPE {FIREFOX, CHROME, INTERNET_EXPLORER};
private static HashMap<BROWSER_TYPE, String> browserToDriverNameMap = new HashMap<BROWSER_TYPE, String>();
static
{
browserToDriverNameMap.put(BROWSER_TYPE.FIREFOX, "gecko");
browserToDriverNameMap.put(BROWSER_TYPE.CHROME, "chrome");
}
//Select the type of browser to be used
private static final BROWSER_TYPE BROWSER = BROWSER_TYPE.CHROME;
//Selenium specific constants
//private static final String BASE_HOME_DIR = "C:/Users/siddharth.s/";
//private static final String DRIVER_PATH = BASE_HOME_DIR + "eclipse-workspace/artifacts/driverss/";
private static final String BASE_HOME_DIR = System.getProperty("user.dir");
private static final String DRIVER_PATH = BASE_HOME_DIR + "/resources/";
private static final String DRIVER_PROPERTY_NAME = "webdriver."+browserToDriverNameMap.get(BROWSER)+".driver";
private static final String DRIVER_EXE_NAME = browserToDriverNameMap.get(BROWSER)+"driver.exe";
private static final String SELENIUM_LOGGER_CLASS = "org.openqa.selenium";
//EAG Portal URLs
private static final String EAG_HOMEPAGE_URL = "https://eag.synechron.com/SYNE.UI/";
private static final String REGULARIZATION_LIST_PAGE_URL = EAG_HOMEPAGE_URL +"/Attendance/Common/Home/Index#/applications/AttendanceRegularization/List";
//EAG Portal Page Titles
private static final String TITLE_EAG_HOMEPAGE = "Enterprise Application Portal";
private static final String TITLE_SYNETIME_APPLICATIONS_PAGE = "Applications | Attendance System";
private static final String TITLE_SYNETIME_REGULARIZATION_PAGE = "Attendance Regularization | Attendance System";
private static final String TITLE_SYNETIME_REGULARIZATION_LIST_PAGE = "Attendance Regularization List | Attendance System";
private static final String TITLE_SYNETIME_ATTENDENCE_HOME = "Home | Attendance System";
private static final String BTN_APPLY_TXT = "Apply";
// Reason Code constants
private static final String REASON_CARD_SUBMITTED_TO_ADMIN = "Card submitted to Admin"+Keys.ENTER;
private static final String REASON_TRAINING = "T"+Keys.ENTER;
private static final String ATTRIBUTE_VALUE = "value";
private static final String DATE_FORMAT = "dd MMM, yyyy";
//EAG Login details
public String EAG_USERNAME = "siddharth.s";
public String EAG_PASSWORD = "<PASSWORD>";
private static final String REASON_FOR_REG = REASON_CARD_SUBMITTED_TO_ADMIN;
private static final String[] VALID_INPUT_ARGS = new String[] {"-user","-pass","-headless"};
//Configuration
private static final long SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS = 3000;
private static final long SLEEP_TO_AVOID_CLICK_INTERCEPT = 1000;
private static final int MAX_WEEKS_IN_A_MONTH = 5;
//Logs Configuration
private static final String LOG_DIR = BASE_HOME_DIR + "/logs/selenium/";
private static final String LOG_FILE_NAME = "DriverLog";
private static final String LOG_FILE_EXTENSION = ".txt";
private static final String LOG_NAME_DATE_FORMAT = "yyyyMMdd_HH_mm_ss";
private static final String SCREENSHOT_DIR = BASE_HOME_DIR + "/screenshots/";
private static final String SCREENSHOT_PREFIX = "Regularization_";
private static final boolean IS_HEADLESS = true;
private WebDriver webDriver;
public static void main(String[] args) throws Exception {
System.out.println("Started.. Browser Type - "+BROWSER);
long startTime = System.currentTimeMillis();
RegularizeTimesheet regularizeTimesheet = new RegularizeTimesheet();
regularizeTimesheet.handleArgs(args);
regularizeTimesheet.regularize();
System.out.println("Finished..");
System.out.println("Time taken = "+(System.currentTimeMillis() - startTime)/1000+" secs");
}
private void regularize() throws Exception {
openBrowser();
loginToEag();
handleDiscrepencies();
verify();
saveScreenshot();
closeBrowser();
}
private void handleArgs(String[] inputArgs) {
ArrayList<String> validInputArgsList = new ArrayList<String>(Arrays.asList(VALID_INPUT_ARGS));
HashMap<String, String> argToFieldMap = getInputArgToFieldMap();
for(int i=0;i<inputArgs.length;i++)
{
if(validInputArgsList.contains(inputArgs[i]))
{
try {
Field fld = this.getClass().getField(argToFieldMap.get(inputArgs[i]));
fld.setAccessible(true);
fld.set(this, inputArgs[++i]);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
System.out.println(inputArgs[i]+" - Not a valid arguement");
i++;
}
}
}
private void handleDiscrepencies() throws InterruptedException, ParseException, IOException{
String cssSelDecrepencyCountLink = ".attendenceDiscrepancy > span:nth-child(2)";
//WebDriverWait wait = new WebDriverWait(webDriver,3);
//wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssSelDecrepencyCountLink)));
int descrepenciesCount = Integer.valueOf(webDriver.findElement(By.cssSelector(cssSelDecrepencyCountLink)).getText());
System.out.println("Discrepencies Count == "+descrepenciesCount);
if(descrepenciesCount == 0)
{
System.out.println("No Attendence Discrepencies to be handled..");
return;
}
String cssSelRegLink = ".listing-table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(6) > a:nth-child(2)";
String cssSelInTime08hrFromDropDown = ".ui_tpicker_hour_slider > select:nth-child(1) > option:nth-child(9)";
String cssSelInTime10hrFromDropDown = ".ui_tpicker_hour_slider > select:nth-child(1) > option:nth-child(11)";
String cssSelInTime00minFromDropDown = ".ui_tpicker_minute_slider > select:nth-child(1) > option:nth-child(1)";
String cssSelOutTime16hrFromDropDown = ".ui_tpicker_hour_slider > select:nth-child(1) > option:nth-child(17)";
String cssSelOutTime18hrFromDropDown = ".ui_tpicker_hour_slider > select:nth-child(1) > option:nth-child(19)";
String cssSelOutTime00minFromDropDown = ".ui_tpicker_minute_slider > select:nth-child(1) > option:nth-child(1)";
String cssSelInandOutTimeDoneBtn = ".ui-datepicker-close";
String cssSelInTimeHrDropDown = cssSelInTime10hrFromDropDown;
String cssSelOutTimeHrFromDropDown = cssSelOutTime18hrFromDropDown;
if(REASON_FOR_REG.equalsIgnoreCase(REASON_TRAINING))
{
cssSelInTimeHrDropDown = cssSelInTime08hrFromDropDown;
cssSelOutTimeHrFromDropDown = cssSelOutTime16hrFromDropDown;
}
String cssSelApplyBtn = "input.buttons:nth-child(3)";
String idCalInDate = "InDate";
String idCalOutDate = "OutDate";
String idReasonDropDown = "Remarks";
String idInTimeDropDown = "fromPicker";
String idOutTimeDropDown = "Text1";
String startTextForWarningToIgnore = "You have already applied";
String containsTextForRetry = "Datatype size excedded";
String cssSelForToastMessage = ".toast-message";
String cssSelForLinkToRegPage = "#applicationHost > div > div > section > aside > div:nth-child(2) > div > aside.homeRightBlock > div.rightBlockLeftSection > div:nth-child(1) > span";
if(descrepenciesCount > 0)
{
webDriver.findElement(By.cssSelector(cssSelDecrepencyCountLink)).click();
waitForPageToLoad(TITLE_SYNETIME_APPLICATIONS_PAGE);
ArrayList<Date> discrepancyDatesList = populateListOfDiscrepencyDates();
for(Date discrepencyDate : discrepancyDatesList)
{
if(webDriver.getTitle().equalsIgnoreCase(TITLE_SYNETIME_ATTENDENCE_HOME))
webDriver.findElement(By.cssSelector(cssSelForLinkToRegPage)).click();
waitForPageToLoad(TITLE_SYNETIME_APPLICATIONS_PAGE);
webDriver.findElement(By.cssSelector(cssSelRegLink)).click();
waitForPageToLoad(TITLE_SYNETIME_REGULARIZATION_PAGE);
webDriver.findElement(By.id(idReasonDropDown)).click();
webDriver.findElement(By.id(idReasonDropDown)).sendKeys(REASON_FOR_REG);
webDriver.findElement(By.id(idInTimeDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelInTimeHrDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelInTime00minFromDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelInandOutTimeDoneBtn)).click();
Thread.sleep(SLEEP_TO_AVOID_CLICK_INTERCEPT);
webDriver.findElement(By.id(idOutTimeDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelOutTimeHrFromDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelOutTime00minFromDropDown)).click();
webDriver.findElement(By.cssSelector(cssSelInandOutTimeDoneBtn)).click();
Thread.sleep(SLEEP_TO_AVOID_CLICK_INTERCEPT);
setDateDropDown(discrepencyDate, idCalInDate);
Thread.sleep(SLEEP_TO_AVOID_CLICK_INTERCEPT);
setDateDropDown(discrepencyDate, idCalOutDate);
WebElement applyBtn = webDriver.findElement(By.cssSelector(cssSelApplyBtn));
if(applyBtn.getAttribute(ATTRIBUTE_VALUE).equalsIgnoreCase(BTN_APPLY_TXT))
{
applyBtn.click();
Thread.sleep(SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS);
try
{
if(webDriver.findElement(By.cssSelector(cssSelForToastMessage)).getText().contains(containsTextForRetry))
{
applyBtn.click();
Thread.sleep(SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS);
}
if(webDriver.findElement(By.cssSelector(cssSelForToastMessage)).getText().startsWith(startTextForWarningToIgnore))
continue;
}
catch(NoSuchElementException nse)
{
continue;
}
}
descrepenciesCount--;
}
}
System.out.println("Handled All discrepencies");
}
private void setDateDropDown(Date discrepencyDate, String idDate) {
boolean selectedMonth = false, selectedYear = false;
Calendar cal = Calendar.getInstance();
cal.setTime(discrepencyDate);
webDriver.findElement(By.id(idDate)).click();
//List<WebElement> monthRows = webDriver.findElements(By.cssSelector("[class='ui-datepicker-month'] option"));
List<WebElement> monthRows = webDriver.findElements(By.cssSelector(".ui-datepicker-month > option"));
for(WebElement monthRow : monthRows)
{
if(monthRow.isSelected() && Integer.valueOf(monthRow.getAttribute(ATTRIBUTE_VALUE)) == cal.get(Calendar.MONTH))
selectedMonth = true;
}
List<WebElement> yearRows = webDriver.findElements(By.cssSelector(".ui-datepicker-year option"));
for(WebElement yearRow : yearRows)
{
if(yearRow.isSelected() && Integer.valueOf(yearRow.getAttribute(ATTRIBUTE_VALUE)) == cal.get(Calendar.YEAR))
selectedYear = true;
}
if(!selectedMonth)
{
WebElement monthRow = null;
if(idDate.equalsIgnoreCase("OutDate"))
monthRow = webDriver.findElement(By.cssSelector(".ui-datepicker-month > option:nth-child(1)"));
else
monthRow = webDriver.findElement(By.cssSelector(".ui-datepicker-month > option:nth-child("+(cal.get(Calendar.MONTH)+1)+")"));
monthRow.click();
}
if(!selectedYear)
{
for(WebElement yearRow : yearRows)
{
if(Integer.valueOf(yearRow.getAttribute(ATTRIBUTE_VALUE)) == cal.get(Calendar.YEAR))
{
selectedYear = true;
yearRow.click();
break;
}
}
}
for(int i=1;i<=MAX_WEEKS_IN_A_MONTH;i++)
{
String cssSelDayofMonth = ".ui-datepicker-calendar > tbody:nth-child(2) > tr:nth-child("+i+") > td:nth-child("+cal.get(Calendar.DAY_OF_WEEK)+") > a:nth-child(1)";
try
{
String dayOfMonthText = webDriver.findElement(By.cssSelector(cssSelDayofMonth)).getText();
if(dayOfMonthText != null && !dayOfMonthText.trim().equalsIgnoreCase("") && Integer.valueOf(dayOfMonthText) == cal.get(Calendar.DAY_OF_MONTH))
webDriver.findElement(By.cssSelector(cssSelDayofMonth)).click();
}
catch(NoSuchElementException nse)
{
continue;
}
}
}
private ArrayList<Date> populateListOfDiscrepencyDates() throws ParseException {
ArrayList<Date> discrepancyDatesList = new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String cssSelListingTableRows = "[class='listing-table'] tr";
int discrepencyRowsCount = webDriver.findElements(By.cssSelector(cssSelListingTableRows)).size();
for(int i=2; i<=discrepencyRowsCount; i++)
{
String cssSelDescrepencyDate = ".listing-table > tbody:nth-child(1) > tr:nth-child("+i+") > td:nth-child(1)";
WebElement discrepencyDateColumn = webDriver.findElement(By.cssSelector(cssSelDescrepencyDate));
Date date = sdf.parse(discrepencyDateColumn.getText());
discrepancyDatesList.add(date);
}
return discrepancyDatesList;
}
private void loginToEag() throws InterruptedException, WebDriverException, IOException
{
String idUserName = "UserName";
String idPassword = "<PASSWORD>";
String classNameSignInBtn = "signInBtn";
webDriver.findElement(By.id(idUserName)).clear();
webDriver.findElement(By.id(idUserName)).sendKeys(EAG_USERNAME);
webDriver.findElement(By.id(idPassword)).clear();
webDriver.findElement(By.id(idPassword)).sendKeys(<PASSWORD>);
webDriver.findElement(By.className(classNameSignInBtn)).click();
checkForInvalidLogin();
waitForPageToLoad(TITLE_EAG_HOMEPAGE);
System.out.println("Login Successful : user - "+EAG_USERNAME);
}
private void checkForInvalidLogin() throws InterruptedException, WebDriverException, IOException{
Thread.sleep(SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS);
String cssSelForInvalidLoginText = "body > div.container.newLogOn > form > div > div.loginaccess > span";
String INVALID_LOGIN_MESSAGE = "Invalid Username / Password. Please try again";
try
{
if(webDriver.getTitle().equalsIgnoreCase(TITLE_EAG_HOMEPAGE) &&
INVALID_LOGIN_MESSAGE.equalsIgnoreCase(webDriver.findElement(By.cssSelector(cssSelForInvalidLoginText)).getText()))
{
System.out.println("Invalid login details : user - "+EAG_USERNAME+", pass - "+<PASSWORD>);
//Desktop.getDesktop().open(((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE));
Thread.sleep(1000);
System.exit(-1);
}
}
catch(NoSuchElementException nse)
{}
}
private void waitForPageToLoad(String pageTitle) throws InterruptedException
{
while(true)
{
if(webDriver.getTitle().equalsIgnoreCase(pageTitle))
return;
Thread.sleep(SLEEP_TIME_BETWEEN_PAGE_LOAD_CHECKS);
}
}
private void openBrowser()
{
SimpleDateFormat logFileNameDateFormat = new SimpleDateFormat(LOG_NAME_DATE_FORMAT);
Logger.getLogger(SELENIUM_LOGGER_CLASS).setLevel(Level.OFF);
System.setProperty(DRIVER_PROPERTY_NAME, DRIVER_PATH+DRIVER_EXE_NAME);
switch(BROWSER)
{
case FIREFOX :
{
FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--disable-logging");
firefoxBinary.addCommandLineOptions("--headless");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,
LOG_DIR+BROWSER+"_"+LOG_FILE_NAME+"_"+logFileNameDateFormat.format(new Date())+LOG_FILE_EXTENSION);
webDriver = new FirefoxDriver(firefoxOptions);
break;
}
case CHROME :
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(IS_HEADLESS);
chromeOptions.addArguments("--start-maximized");
System.setProperty("webdriver.chrome.silentOutput", "true");
//System.setProperty("webdriver.chrome.logfile", LOG_DIR+ BROWSER+"_"+LOG_FILE_NAME+"_"+logFileNameDateFormat.format(new Date())+LOG_FILE_EXTENSION);
//System.setProperty("webdriver.chrome.verboseLogging", "true");
webDriver = new ChromeDriver(chromeOptions);
break;
}
default:
{
System.err.println("Currently Browser Type: <"+BROWSER+"> is not supported..");
System.exit(-1);
}
}
//webDriver.manage().window().maximize();
webDriver.get(EAG_HOMEPAGE_URL);
}
private void verify() throws InterruptedException, IOException{
webDriver.get(REGULARIZATION_LIST_PAGE_URL);
waitForPageToLoad(TITLE_SYNETIME_REGULARIZATION_LIST_PAGE);
//Desktop.getDesktop().open(((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE));
}
private void closeBrowser() {
webDriver.close();
}
private HashMap<String, String> getInputArgToFieldMap()
{
HashMap<String, String> argToFieldMap = new HashMap<String, String>();
argToFieldMap.put(VALID_INPUT_ARGS[0], "EAG_USERNAME");
argToFieldMap.put(VALID_INPUT_ARGS[1], "EAG_PASSWORD");
argToFieldMap.put(VALID_INPUT_ARGS[2], "IS_HEADLESS");
//argToFieldMap.put("-browser", "BROWSER");
return argToFieldMap;
}
private void saveScreenshot() throws Exception
{
SimpleDateFormat sdf = new SimpleDateFormat(LOG_NAME_DATE_FORMAT);
File screenshotFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
Path destScreenshotPath = Paths.get(SCREENSHOT_DIR+SCREENSHOT_PREFIX+sdf.format(new Date())+screenshotFile.getName().substring(screenshotFile.getName().lastIndexOf(".")));
Path srcScreenshotPath = screenshotFile.toPath();
if(!new File(SCREENSHOT_DIR).exists())
new File(SCREENSHOT_DIR).mkdirs();
Files.copy(srcScreenshotPath, destScreenshotPath, StandardCopyOption.REPLACE_EXISTING);
}
}
| 18,527 | 0.725835 | 0.721248 | 445 | 39.638203 | 36.742615 | 185 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.820225 | false | false | 13 |
d6f5d3b2428a80a20ae86b5b6df937a19778bdbc | 19,069,654,839,774 | 781df6f9e3b057f30cadbe06237fe2635367566a | /notebook/src/main/java/com/arbardhan/notebook/dao/AttachedDocument.java | 5bc90fdd42119ebf161a3521d68ea7f12627128c | [] | no_license | arbardhan/notebook | https://github.com/arbardhan/notebook | 79cd2400d8a211181813dbb4bad969827970735c | 27121ab97817177e5ed1cdd3feaeadab0d6c81e6 | refs/heads/master | 2020-04-23T06:21:09.201000 | 2019-03-13T18:44:45 | 2019-03-13T18:44:45 | 170,970,382 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.arbardhan.notebook.dao;
import java.io.Serializable;
import java.util.UUID;
import org.springframework.stereotype.Repository;
@Repository
public class AttachedDocument implements Serializable {
/**
*
*/
private static final long serialVersionUID = 615466027190510636L;
private UUID documentid;
private String documentContents;
private String documentName;
private UUID notebookContentid;
private UUID ownerid;
private UUID notebookVersion;
private String latestNotebookName;
private UUID latestNotebookVersion;
private String latestDocumentName;
private UUID latestDocumentId;
private UUID documentCreateTime;
public UUID getDocumentid() {
return documentid;
}
public void setDocumentid(UUID documentid) {
this.documentid = documentid;
}
public String getDocumentContents() {
return documentContents;
}
public void setDocumentContents(String documentContents) {
this.documentContents = documentContents;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
public UUID getNotebookContentid() {
return notebookContentid;
}
public void setNotebookContentid(UUID notebookContentid) {
this.notebookContentid = notebookContentid;
}
public UUID getOwnerid() {
return ownerid;
}
public void setOwnerid(UUID ownerid) {
this.ownerid = ownerid;
}
public UUID getNotebookVersion() {
return notebookVersion;
}
public void setNotebookVersion(UUID notebookVersion) {
this.notebookVersion = notebookVersion;
}
public String getLatestNotebookName() {
return latestNotebookName;
}
public void setLatestNotebookName(String latestNotebookName) {
this.latestNotebookName = latestNotebookName;
}
public UUID getLatestNotebookVersion() {
return latestNotebookVersion;
}
public void setLatestNotebookVersion(UUID latestNotebookVersion) {
this.latestNotebookVersion = latestNotebookVersion;
}
public String getLatestDocumentName() {
return latestDocumentName;
}
public void setLatestDocumentName(String latestDocumentName) {
this.latestDocumentName = latestDocumentName;
}
public UUID getLatestDocumentId() {
return latestDocumentId;
}
public void setLatestDocumentId(UUID latestDocumentId) {
this.latestDocumentId = latestDocumentId;
}
public UUID getDocumentCreateTime() {
return documentCreateTime;
}
public void setDocumentCreateTime(UUID documentCreateTime) {
this.documentCreateTime = documentCreateTime;
}
}
| UTF-8 | Java | 2,518 | java | AttachedDocument.java | Java | [] | null | [] | package com.arbardhan.notebook.dao;
import java.io.Serializable;
import java.util.UUID;
import org.springframework.stereotype.Repository;
@Repository
public class AttachedDocument implements Serializable {
/**
*
*/
private static final long serialVersionUID = 615466027190510636L;
private UUID documentid;
private String documentContents;
private String documentName;
private UUID notebookContentid;
private UUID ownerid;
private UUID notebookVersion;
private String latestNotebookName;
private UUID latestNotebookVersion;
private String latestDocumentName;
private UUID latestDocumentId;
private UUID documentCreateTime;
public UUID getDocumentid() {
return documentid;
}
public void setDocumentid(UUID documentid) {
this.documentid = documentid;
}
public String getDocumentContents() {
return documentContents;
}
public void setDocumentContents(String documentContents) {
this.documentContents = documentContents;
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
public UUID getNotebookContentid() {
return notebookContentid;
}
public void setNotebookContentid(UUID notebookContentid) {
this.notebookContentid = notebookContentid;
}
public UUID getOwnerid() {
return ownerid;
}
public void setOwnerid(UUID ownerid) {
this.ownerid = ownerid;
}
public UUID getNotebookVersion() {
return notebookVersion;
}
public void setNotebookVersion(UUID notebookVersion) {
this.notebookVersion = notebookVersion;
}
public String getLatestNotebookName() {
return latestNotebookName;
}
public void setLatestNotebookName(String latestNotebookName) {
this.latestNotebookName = latestNotebookName;
}
public UUID getLatestNotebookVersion() {
return latestNotebookVersion;
}
public void setLatestNotebookVersion(UUID latestNotebookVersion) {
this.latestNotebookVersion = latestNotebookVersion;
}
public String getLatestDocumentName() {
return latestDocumentName;
}
public void setLatestDocumentName(String latestDocumentName) {
this.latestDocumentName = latestDocumentName;
}
public UUID getLatestDocumentId() {
return latestDocumentId;
}
public void setLatestDocumentId(UUID latestDocumentId) {
this.latestDocumentId = latestDocumentId;
}
public UUID getDocumentCreateTime() {
return documentCreateTime;
}
public void setDocumentCreateTime(UUID documentCreateTime) {
this.documentCreateTime = documentCreateTime;
}
}
| 2,518 | 0.791501 | 0.784353 | 97 | 24.958763 | 20.228548 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.525773 | false | false | 13 |
c428ae162310e715d5657024db5e78e4f5a95dbe | 35,356,170,787,493 | b7428a4b39b1000a64c0d9ebd8fc4e3322693542 | /src/main/java/com/bertazoli/charity/server/guice/ServerModule.java | d4e931f137e24a95471d0f8eba735276a8eb7e21 | [] | no_license | yawenc/Charity | https://github.com/yawenc/Charity | 655dc836e13ecf2025a5111bbe70ef0247ccd5d2 | 6183e4266f7875ce4da56e1e4b4e13297181c7cc | refs/heads/master | 2020-12-25T08:50:28.086000 | 2014-05-24T12:36:55 | 2014-05-24T12:36:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bertazoli.charity.server.guice;
import com.bertazoli.charity.server.action.validator.AdminActionValidator;
import com.bertazoli.charity.server.action.validator.LoggedInActionValidator;
import com.bertazoli.charity.server.handlers.CharitySearchHandler;
import com.bertazoli.charity.server.handlers.LoginHandler;
import com.bertazoli.charity.server.handlers.LogoutHandler;
import com.bertazoli.charity.server.handlers.OracleHandler;
import com.bertazoli.charity.server.handlers.SearchUsernameHandler;
import com.bertazoli.charity.server.handlers.SignupHandler;
import com.bertazoli.charity.server.handlers.admin.RunDrawHandler;
import com.bertazoli.charity.server.handlers.donate.FetchTotalDonationsHandler;
import com.bertazoli.charity.server.handlers.donate.SetExpressChecktoutHandler;
import com.bertazoli.charity.server.handlers.user.FetchUserFromSessionHandler;
import com.bertazoli.charity.server.handlers.user.SearchMyDonationsHandler;
import com.bertazoli.charity.shared.action.CharitySearchAction;
import com.bertazoli.charity.shared.action.LoginAction;
import com.bertazoli.charity.shared.action.LogoutAction;
import com.bertazoli.charity.shared.action.OracleAction;
import com.bertazoli.charity.shared.action.SearchUsernameAction;
import com.bertazoli.charity.shared.action.SignupAction;
import com.bertazoli.charity.shared.action.admin.RunDrawAction;
import com.bertazoli.charity.shared.action.donate.FetchTotalDonationsAction;
import com.bertazoli.charity.shared.action.donate.SetExpressChecktoutAction;
import com.bertazoli.charity.shared.action.user.FetchUserFromSessionAction;
import com.bertazoli.charity.shared.action.user.SearchMyDonationsAction;
import com.gwtplatform.dispatch.rpc.server.guice.HandlerModule;
public class ServerModule extends HandlerModule {
@Override
protected void configureHandlers() {
bindHandler(SignupAction.class, SignupHandler.class);
bindHandler(LoginAction.class, LoginHandler.class);
bindHandler(LogoutAction.class, LogoutHandler.class);
bindHandler(OracleAction.class, OracleHandler.class);
bindHandler(SearchUsernameAction.class, SearchUsernameHandler.class);
bindHandler(FetchUserFromSessionAction.class, FetchUserFromSessionHandler.class);
bindHandler(FetchTotalDonationsAction.class, FetchTotalDonationsHandler.class);
bindHandler(CharitySearchAction.class, CharitySearchHandler.class, LoggedInActionValidator.class);
bindHandler(SetExpressChecktoutAction.class, SetExpressChecktoutHandler.class, LoggedInActionValidator.class);
bindHandler(SearchMyDonationsAction.class, SearchMyDonationsHandler.class, LoggedInActionValidator.class);
bindHandler(RunDrawAction.class, RunDrawHandler.class, AdminActionValidator.class);
}
}
| UTF-8 | Java | 2,789 | java | ServerModule.java | Java | [] | null | [] | package com.bertazoli.charity.server.guice;
import com.bertazoli.charity.server.action.validator.AdminActionValidator;
import com.bertazoli.charity.server.action.validator.LoggedInActionValidator;
import com.bertazoli.charity.server.handlers.CharitySearchHandler;
import com.bertazoli.charity.server.handlers.LoginHandler;
import com.bertazoli.charity.server.handlers.LogoutHandler;
import com.bertazoli.charity.server.handlers.OracleHandler;
import com.bertazoli.charity.server.handlers.SearchUsernameHandler;
import com.bertazoli.charity.server.handlers.SignupHandler;
import com.bertazoli.charity.server.handlers.admin.RunDrawHandler;
import com.bertazoli.charity.server.handlers.donate.FetchTotalDonationsHandler;
import com.bertazoli.charity.server.handlers.donate.SetExpressChecktoutHandler;
import com.bertazoli.charity.server.handlers.user.FetchUserFromSessionHandler;
import com.bertazoli.charity.server.handlers.user.SearchMyDonationsHandler;
import com.bertazoli.charity.shared.action.CharitySearchAction;
import com.bertazoli.charity.shared.action.LoginAction;
import com.bertazoli.charity.shared.action.LogoutAction;
import com.bertazoli.charity.shared.action.OracleAction;
import com.bertazoli.charity.shared.action.SearchUsernameAction;
import com.bertazoli.charity.shared.action.SignupAction;
import com.bertazoli.charity.shared.action.admin.RunDrawAction;
import com.bertazoli.charity.shared.action.donate.FetchTotalDonationsAction;
import com.bertazoli.charity.shared.action.donate.SetExpressChecktoutAction;
import com.bertazoli.charity.shared.action.user.FetchUserFromSessionAction;
import com.bertazoli.charity.shared.action.user.SearchMyDonationsAction;
import com.gwtplatform.dispatch.rpc.server.guice.HandlerModule;
public class ServerModule extends HandlerModule {
@Override
protected void configureHandlers() {
bindHandler(SignupAction.class, SignupHandler.class);
bindHandler(LoginAction.class, LoginHandler.class);
bindHandler(LogoutAction.class, LogoutHandler.class);
bindHandler(OracleAction.class, OracleHandler.class);
bindHandler(SearchUsernameAction.class, SearchUsernameHandler.class);
bindHandler(FetchUserFromSessionAction.class, FetchUserFromSessionHandler.class);
bindHandler(FetchTotalDonationsAction.class, FetchTotalDonationsHandler.class);
bindHandler(CharitySearchAction.class, CharitySearchHandler.class, LoggedInActionValidator.class);
bindHandler(SetExpressChecktoutAction.class, SetExpressChecktoutHandler.class, LoggedInActionValidator.class);
bindHandler(SearchMyDonationsAction.class, SearchMyDonationsHandler.class, LoggedInActionValidator.class);
bindHandler(RunDrawAction.class, RunDrawHandler.class, AdminActionValidator.class);
}
}
| 2,789 | 0.841879 | 0.841879 | 45 | 60.977779 | 27.599911 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.2 | false | false | 13 |
f81a1d47633a4b5e3a0cb68466425753ddedfc65 | 33,045,478,418,171 | 53f7c613df9074c88a6cd057c64c28d4a57472ca | /src/balls/controller/Controller.java | 662caa4c146f1ef9484e8df306316b90348bb887 | [
"MIT"
] | permissive | ria8246/Java2_VirtualPhysicsLab | https://github.com/ria8246/Java2_VirtualPhysicsLab | c8e14d62e7633cde5330a37ee925a8f7c7b00502 | 8092a1d78d056c740c5a2ec0247a62121dd767ab | refs/heads/master | 2021-01-10T05:07:55.259000 | 2015-12-07T11:51:15 | 2015-12-07T11:51:15 | 45,296,203 | 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 balls.controller;
import balls.model.Model;
import balls.view.View;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseEvent;
/**
*
* @author n0g3
*/
public class Controller {
//ball states
private final int START = 0;
private final int FREE_FALL = 1;
private final int ON_GROUND = 2;
private final int REBOUND = 3;
private Model model;
private View view;
private Slider gravitySlider;
private Slider elaSlider;
private Slider xSlider;
private Button startButton;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
initItems();
initEventHandlers();
}
private void initEventHandlers() {
//gravitySlider
gravitySlider.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
setModelGravity();
view.getGravityValueLabel().setText(String.valueOf((int) gravitySlider.getValue()));
}
});
//startButton
startButton.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
view.startAnim((double)model.getxChange(),0,(double)model.getGravity(),(double)model.getElasticity());
// Thread t = new Thread() {
// @Override
// public void run() {
// //view.startAnim(0,0.2,2,1);
// while (true) {
// view.drawBall(model.getX(), model.getY() + model.getVelocity(), model.getRadius());
// switch (model.getState()) {
// case START:
// model.setState(FREE_FALL);
// break;
// }
// System.out.println("vel: " + model.getVelocity());
// model.setTime(model.getTime() + 0.1f);
// computeVelocity();
//
// }
//
//
// }
// };
// t.setDaemon(true);
// t.start();
}
});
}
private void initItems() {
//sliders
gravitySlider = view.getGravitySlider();
model.setGravity((float) gravitySlider.getValue());
elaSlider = view.getElaSlider();
model.setElasticity((float)elaSlider.getValue());
xSlider = view.getxSlider();
model.setxChange((float)xSlider.getValue());
//button
startButton = view.getButton();
}
public Controller() {
}
public void setModelGravity() {
model.setGravity((float) gravitySlider.getValue());
}
public float computeAcceleration() {
return (model.getDistance() / (getModel().getTime() * getModel().getTime()));
}
public float computeDistance() {
return ((float) (model.getGravity() / 2) * (getModel().getTime() * getModel().getTime()));
}
public float computeDeceleration(float acceleration) {
return ((float) acceleration / 2);
}
public void computeVelocity() {
float tempAcc = 0, tempVel = 0;
switch (model.getState()) {
case START:
model.setVelocity(0);
model.setAcceleration(0);
break;
case FREE_FALL:
model.setAcceleration(model.getGravity());
model.setVelocity(model.getVelocity() + model.getAcceleration() * model.getTime());
break;
case ON_GROUND:
tempAcc = model.getAcceleration();
tempVel = model.getVelocity();
model.setAcceleration(0);
model.setVelocity(0);
break;
case REBOUND:
model.setAcceleration(computeDeceleration(tempAcc));
model.setVelocity(tempVel * model.getAcceleration() - model.getGravity());
}
}
/**
* @return the model
*/
public Model getModel() {
return model;
}
/**
* @param model the model to set
*/
public void setModel(Model model) {
this.model = model;
}
/**
* @return the view
*/
public View getView() {
return view;
}
/**
* @param view the view to set
*/
public void setView(View view) {
this.view = view;
}
}
| UTF-8 | Java | 5,258 | java | Controller.java | Java | [
{
"context": "afx.scene.input.MouseEvent;\r\n\r\n/**\r\n *\r\n * @author n0g3\r\n */\r\npublic class Controller {\r\n\r\n //ball state",
"end": 566,
"score": 0.9982606768608093,
"start": 562,
"tag": "USERNAME",
"value": "n0g3"
}
] | 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 balls.controller;
import balls.model.Model;
import balls.view.View;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseEvent;
/**
*
* @author n0g3
*/
public class Controller {
//ball states
private final int START = 0;
private final int FREE_FALL = 1;
private final int ON_GROUND = 2;
private final int REBOUND = 3;
private Model model;
private View view;
private Slider gravitySlider;
private Slider elaSlider;
private Slider xSlider;
private Button startButton;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
initItems();
initEventHandlers();
}
private void initEventHandlers() {
//gravitySlider
gravitySlider.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
setModelGravity();
view.getGravityValueLabel().setText(String.valueOf((int) gravitySlider.getValue()));
}
});
//startButton
startButton.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
view.startAnim((double)model.getxChange(),0,(double)model.getGravity(),(double)model.getElasticity());
// Thread t = new Thread() {
// @Override
// public void run() {
// //view.startAnim(0,0.2,2,1);
// while (true) {
// view.drawBall(model.getX(), model.getY() + model.getVelocity(), model.getRadius());
// switch (model.getState()) {
// case START:
// model.setState(FREE_FALL);
// break;
// }
// System.out.println("vel: " + model.getVelocity());
// model.setTime(model.getTime() + 0.1f);
// computeVelocity();
//
// }
//
//
// }
// };
// t.setDaemon(true);
// t.start();
}
});
}
private void initItems() {
//sliders
gravitySlider = view.getGravitySlider();
model.setGravity((float) gravitySlider.getValue());
elaSlider = view.getElaSlider();
model.setElasticity((float)elaSlider.getValue());
xSlider = view.getxSlider();
model.setxChange((float)xSlider.getValue());
//button
startButton = view.getButton();
}
public Controller() {
}
public void setModelGravity() {
model.setGravity((float) gravitySlider.getValue());
}
public float computeAcceleration() {
return (model.getDistance() / (getModel().getTime() * getModel().getTime()));
}
public float computeDistance() {
return ((float) (model.getGravity() / 2) * (getModel().getTime() * getModel().getTime()));
}
public float computeDeceleration(float acceleration) {
return ((float) acceleration / 2);
}
public void computeVelocity() {
float tempAcc = 0, tempVel = 0;
switch (model.getState()) {
case START:
model.setVelocity(0);
model.setAcceleration(0);
break;
case FREE_FALL:
model.setAcceleration(model.getGravity());
model.setVelocity(model.getVelocity() + model.getAcceleration() * model.getTime());
break;
case ON_GROUND:
tempAcc = model.getAcceleration();
tempVel = model.getVelocity();
model.setAcceleration(0);
model.setVelocity(0);
break;
case REBOUND:
model.setAcceleration(computeDeceleration(tempAcc));
model.setVelocity(tempVel * model.getAcceleration() - model.getGravity());
}
}
/**
* @return the model
*/
public Model getModel() {
return model;
}
/**
* @param model the model to set
*/
public void setModel(Model model) {
this.model = model;
}
/**
* @return the view
*/
public View getView() {
return view;
}
/**
* @param view the view to set
*/
public void setView(View view) {
this.view = view;
}
}
| 5,258 | 0.514454 | 0.51027 | 175 | 28.045713 | 24.775984 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false | 13 |
3e64ec69bce4deb5648e16ec7a86b7d03b77508b | 37,245,956,394,747 | d621862a8f0d5cf1d9cdc52593372b8ecc3c563f | /src/main/java/com/mokiwi/dao/LoginRecordDao.java | 47037a94963977b2c6f9501c581502bd753454be | [] | no_license | zddzdd/ICPWms | https://github.com/zddzdd/ICPWms | c748a9c67f317e50cc2c8ebe9faa78d28403803d | cec3002cf8c773172ebbb19c0a39f4dd19c9c738 | refs/heads/master | 2018-12-25T02:02:47.134000 | 2018-10-18T03:16:04 | 2018-10-18T03:16:04 | 153,556,683 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mokiwi.dao;
import com.mokiwi.entity.LoginRecord;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* Created by Administrator on 2018/10/16 0016.
*/
public interface LoginRecordDao extends CrudRepository<LoginRecord,Long>{
List<LoginRecord> findAllByUsernameContaining(String adminuser);
List<LoginRecord> findAllByLoginipContaining(String loginip);
List<LoginRecord> findAllByLoginstatesContaining(String state);
}
| UTF-8 | Java | 484 | java | LoginRecordDao.java | Java | [
{
"context": "sitory;\n\nimport java.util.List;\n\n/**\n * Created by Administrator on 2018/10/16 0016.\n */\npublic interface LoginRec",
"end": 178,
"score": 0.5586840510368347,
"start": 165,
"tag": "USERNAME",
"value": "Administrator"
}
] | null | [] | package com.mokiwi.dao;
import com.mokiwi.entity.LoginRecord;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* Created by Administrator on 2018/10/16 0016.
*/
public interface LoginRecordDao extends CrudRepository<LoginRecord,Long>{
List<LoginRecord> findAllByUsernameContaining(String adminuser);
List<LoginRecord> findAllByLoginipContaining(String loginip);
List<LoginRecord> findAllByLoginstatesContaining(String state);
}
| 484 | 0.803719 | 0.778926 | 17 | 27.470589 | 28.504112 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 13 |
abcb0232b20a3ef3a16b44ea2be2ccedc11e7568 | 24,026,047,057,033 | 3f66d35addb25c8d2b1a1776057c82211c7ede5e | /src/com/company/Subscription.java | 7b9737e4aa85b3b39818fdd26525a5ef8e7ab828 | [] | no_license | oliverbskau/DolphinSwim | https://github.com/oliverbskau/DolphinSwim | f1801a102f9dc04f48b270cc7bc57e0682a7e9e3 | c3fb68f5faf4769608a8ad225da82955a40ffad6 | refs/heads/master | 2023-01-29T19:13:22.772000 | 2020-12-04T12:42:12 | 2020-12-04T12:42:12 | 315,291,075 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @author Rasmus
*/
public class Subscription {
//navigate in the class with a switch
public void subscriptionNavigation(ArrayList<Clubmember> members) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nKontigenter");
System.out.println("------------------");
System.out.println("1. Tilbage til menu\n2. Se medlemmers status\n3. Se totalet af kontigenter\n4. Betal kontigent");
System.out.print("Vælg: ");
int choice = scanner.nextInt();
switch (choice) {
case 1: //Tilbage til menu
break;
case 2: //Se medlemmer status
subscriptionStatus(members);
break;
case 3: //Se totalet af kontigenter
System.out.println("Totalet af alle kontigenter: " + getTotalOfSubscriptions(members));
break;
case 4: //Betal kontigent
paySubscription(members);
break;
default: //Fejl i indtastning
System.err.println("Fejl! du indtastede ikke det korrekte tal, vender tilbage til menu");
break;
}
}
//Defines what the monthly subscribssionprice is according to the agegroup you belong
public double calculateTotalOfSubcriptions(int age, String memberType) {
double totalOfPrice = 0;
if(memberType == "Aktiv"){
if (age < 18) {
totalOfPrice = 1000;
} else if (age > 18 && age < 60) {
totalOfPrice = 1600;
} else if (age > 60) {
totalOfPrice = 1600 * 0.75;
}
} else { //Membertype = Passiv
totalOfPrice = 500;
}
return totalOfPrice;
}
//Get the total price of subcriptions
public double getTotalOfSubscriptions(ArrayList<Clubmember> members) {
double total = 0;
for (int i = 0; i < members.size(); i++) {
total += members.get(i).getSubscriptionPrice();
}
System.out.println("\nDen totale indtjening er: " + total);
return total;
}
//Sets the hasPayed variable to yes, if a member has payed
public void paySubscription(ArrayList<Clubmember> members) {
Scanner scanner = new Scanner(System.in);
new Register().printAllOfList(members);
System.out.println("\nSkriv tallet foran navnet på den person som skal betale kontigent og tryk enter");
System.out.print("Vælg: ");
int choice = scanner.nextInt()-1;
members.get(choice).setHasPayed("Ja");
}
public void subscriptionStatus(ArrayList<Clubmember> members){
for (int i =0; i < members.size(); i ++){
System.out.println("Navn: " + members.get(i).getName() + ", Betalt kontigent: "
+ members.get(i).getHasPayed() + ", Pris: " + members.get(i).getSubscriptionPrice() + " Kr.");
}
}
}
| UTF-8 | Java | 3,039 | java | Subscription.java | Java | [
{
"context": "rayList;\nimport java.util.Scanner;\n\n/**\n * @author Rasmus\n */\npublic class Subscription {\n\n //navigate i",
"end": 98,
"score": 0.9997847080230713,
"start": 92,
"tag": "NAME",
"value": "Rasmus"
}
] | null | [] | package com.company;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @author Rasmus
*/
public class Subscription {
//navigate in the class with a switch
public void subscriptionNavigation(ArrayList<Clubmember> members) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nKontigenter");
System.out.println("------------------");
System.out.println("1. Tilbage til menu\n2. Se medlemmers status\n3. Se totalet af kontigenter\n4. Betal kontigent");
System.out.print("Vælg: ");
int choice = scanner.nextInt();
switch (choice) {
case 1: //Tilbage til menu
break;
case 2: //Se medlemmer status
subscriptionStatus(members);
break;
case 3: //Se totalet af kontigenter
System.out.println("Totalet af alle kontigenter: " + getTotalOfSubscriptions(members));
break;
case 4: //Betal kontigent
paySubscription(members);
break;
default: //Fejl i indtastning
System.err.println("Fejl! du indtastede ikke det korrekte tal, vender tilbage til menu");
break;
}
}
//Defines what the monthly subscribssionprice is according to the agegroup you belong
public double calculateTotalOfSubcriptions(int age, String memberType) {
double totalOfPrice = 0;
if(memberType == "Aktiv"){
if (age < 18) {
totalOfPrice = 1000;
} else if (age > 18 && age < 60) {
totalOfPrice = 1600;
} else if (age > 60) {
totalOfPrice = 1600 * 0.75;
}
} else { //Membertype = Passiv
totalOfPrice = 500;
}
return totalOfPrice;
}
//Get the total price of subcriptions
public double getTotalOfSubscriptions(ArrayList<Clubmember> members) {
double total = 0;
for (int i = 0; i < members.size(); i++) {
total += members.get(i).getSubscriptionPrice();
}
System.out.println("\nDen totale indtjening er: " + total);
return total;
}
//Sets the hasPayed variable to yes, if a member has payed
public void paySubscription(ArrayList<Clubmember> members) {
Scanner scanner = new Scanner(System.in);
new Register().printAllOfList(members);
System.out.println("\nSkriv tallet foran navnet på den person som skal betale kontigent og tryk enter");
System.out.print("Vælg: ");
int choice = scanner.nextInt()-1;
members.get(choice).setHasPayed("Ja");
}
public void subscriptionStatus(ArrayList<Clubmember> members){
for (int i =0; i < members.size(); i ++){
System.out.println("Navn: " + members.get(i).getName() + ", Betalt kontigent: "
+ members.get(i).getHasPayed() + ", Pris: " + members.get(i).getSubscriptionPrice() + " Kr.");
}
}
}
| 3,039 | 0.575758 | 0.562912 | 91 | 32.362637 | 29.8279 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483516 | false | false | 13 |
8cf481d1aab54a9319a056cf1710e94e3c878a49 | 34,892,314,339,707 | c14c7c0c26d4f918699540443b02b9e8a1b13d3b | /app/src/main/java/com/example/braintrainer/PlayAgainActivity.java | f94f7439753776d674f95f5c926899227d574380 | [] | no_license | Asmat-dev/BrainTrainer | https://github.com/Asmat-dev/BrainTrainer | 39cf0ffb24550095df3eef57f45cc68e7ce56121 | a18d7095b1226e27cc1cf7972a0f7c28bd94dc33 | refs/heads/master | 2022-12-11T10:00:14.379000 | 2020-09-06T12:22:32 | 2020-09-06T12:22:32 | 289,476,343 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.braintrainer;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Objects;
public class PlayAgainActivity extends AppCompatActivity {
public void playAgain(View v) {
again();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_again);
Objects.requireNonNull(getSupportActionBar()).hide();
Bundle b = getIntent().getExtras();
assert b != null;
String obtainedScore = b.getString("obtained");
String totalScore = b.getString("total");
TextView obtainedScoreTextView, totalScoreTextView;
obtainedScoreTextView = findViewById(R.id.obtainedScoreid);
totalScoreTextView = findViewById(R.id.totalScoreid);
obtainedScoreTextView.setText(obtainedScore);
totalScoreTextView.setText(totalScore);
}
public void again() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
| UTF-8 | Java | 1,224 | java | PlayAgainActivity.java | Java | [] | null | [] | package com.example.braintrainer;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Objects;
public class PlayAgainActivity extends AppCompatActivity {
public void playAgain(View v) {
again();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_again);
Objects.requireNonNull(getSupportActionBar()).hide();
Bundle b = getIntent().getExtras();
assert b != null;
String obtainedScore = b.getString("obtained");
String totalScore = b.getString("total");
TextView obtainedScoreTextView, totalScoreTextView;
obtainedScoreTextView = findViewById(R.id.obtainedScoreid);
totalScoreTextView = findViewById(R.id.totalScoreid);
obtainedScoreTextView.setText(obtainedScore);
totalScoreTextView.setText(totalScore);
}
public void again() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
| 1,224 | 0.700163 | 0.700163 | 45 | 26.200001 | 23.882677 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 13 |
f0fe14e2951d55a22b319441ee2ac59c85388b3e | 36,704,790,512,690 | 0fac63d0f8eedfb5b7b95dbec81c2081d7a621ee | /service-share/mall-srv/src/main/java/com/lawu/eshop/mall/srv/domain/SuggestionDO.java | 38e5a1b9115bf29073308712689d6e7ec030f0d4 | [] | no_license | moutainhigh/server-3 | https://github.com/moutainhigh/server-3 | 4385ffcee5587d1c1b91f7eb541a7128fbc7ec0f | 3845625b954e3e025b3e0896a1c08fe5ecc46753 | refs/heads/master | 2022-12-28T06:10:56.826000 | 2019-06-04T08:45:03 | 2019-06-04T08:45:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lawu.eshop.mall.srv.domain;
import java.io.Serializable;
import java.util.Date;
public class SuggestionDO implements Serializable {
/**
*
* 主键
* suggestion.id
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Integer id;
/**
*
* 用户编号
* suggestion.user_num
*
* @mbg.generated 2017-03-23 17:01:47
*/
private String userNum;
/**
*
* 建议内容
* suggestion.content
*
* @mbg.generated 2017-03-23 17:01:47
*/
private String content;
/**
*
* 用户类型,1是商家,2是会员
* suggestion.user_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Byte userType;
/**
*
* 客户端类型,1是android,2是ios
* suggestion.client_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Byte clientType;
/**
*
* 修改时间
* suggestion.gmt_modified
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Date gmtModified;
/**
*
* 创建时间
* suggestion.gmt_create
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Date gmtCreate;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table suggestion
*
* @mbg.generated 2017-03-23 17:01:47
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.id
*
* @return the value of suggestion.id
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.id
*
* @param id the value for suggestion.id
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.user_num
*
* @return the value of suggestion.user_num
*
* @mbg.generated 2017-03-23 17:01:47
*/
public String getUserNum() {
return userNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.user_num
*
* @param userNum the value for suggestion.user_num
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setUserNum(String userNum) {
this.userNum = userNum == null ? null : userNum.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.content
*
* @return the value of suggestion.content
*
* @mbg.generated 2017-03-23 17:01:47
*/
public String getContent() {
return content;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.content
*
* @param content the value for suggestion.content
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.user_type
*
* @return the value of suggestion.user_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Byte getUserType() {
return userType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.user_type
*
* @param userType the value for suggestion.user_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setUserType(Byte userType) {
this.userType = userType;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.client_type
*
* @return the value of suggestion.client_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Byte getClientType() {
return clientType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.client_type
*
* @param clientType the value for suggestion.client_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setClientType(Byte clientType) {
this.clientType = clientType;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.gmt_modified
*
* @return the value of suggestion.gmt_modified
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Date getGmtModified() {
return gmtModified;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.gmt_modified
*
* @param gmtModified the value for suggestion.gmt_modified
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.gmt_create
*
* @return the value of suggestion.gmt_create
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Date getGmtCreate() {
return gmtCreate;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.gmt_create
*
* @param gmtCreate the value for suggestion.gmt_create
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
} | UTF-8 | Java | 6,204 | java | SuggestionDO.java | Java | [] | null | [] | package com.lawu.eshop.mall.srv.domain;
import java.io.Serializable;
import java.util.Date;
public class SuggestionDO implements Serializable {
/**
*
* 主键
* suggestion.id
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Integer id;
/**
*
* 用户编号
* suggestion.user_num
*
* @mbg.generated 2017-03-23 17:01:47
*/
private String userNum;
/**
*
* 建议内容
* suggestion.content
*
* @mbg.generated 2017-03-23 17:01:47
*/
private String content;
/**
*
* 用户类型,1是商家,2是会员
* suggestion.user_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Byte userType;
/**
*
* 客户端类型,1是android,2是ios
* suggestion.client_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Byte clientType;
/**
*
* 修改时间
* suggestion.gmt_modified
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Date gmtModified;
/**
*
* 创建时间
* suggestion.gmt_create
*
* @mbg.generated 2017-03-23 17:01:47
*/
private Date gmtCreate;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table suggestion
*
* @mbg.generated 2017-03-23 17:01:47
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.id
*
* @return the value of suggestion.id
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.id
*
* @param id the value for suggestion.id
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.user_num
*
* @return the value of suggestion.user_num
*
* @mbg.generated 2017-03-23 17:01:47
*/
public String getUserNum() {
return userNum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.user_num
*
* @param userNum the value for suggestion.user_num
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setUserNum(String userNum) {
this.userNum = userNum == null ? null : userNum.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.content
*
* @return the value of suggestion.content
*
* @mbg.generated 2017-03-23 17:01:47
*/
public String getContent() {
return content;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.content
*
* @param content the value for suggestion.content
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.user_type
*
* @return the value of suggestion.user_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Byte getUserType() {
return userType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.user_type
*
* @param userType the value for suggestion.user_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setUserType(Byte userType) {
this.userType = userType;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.client_type
*
* @return the value of suggestion.client_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Byte getClientType() {
return clientType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.client_type
*
* @param clientType the value for suggestion.client_type
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setClientType(Byte clientType) {
this.clientType = clientType;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.gmt_modified
*
* @return the value of suggestion.gmt_modified
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Date getGmtModified() {
return gmtModified;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.gmt_modified
*
* @param gmtModified the value for suggestion.gmt_modified
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column suggestion.gmt_create
*
* @return the value of suggestion.gmt_create
*
* @mbg.generated 2017-03-23 17:01:47
*/
public Date getGmtCreate() {
return gmtCreate;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column suggestion.gmt_create
*
* @param gmtCreate the value for suggestion.gmt_create
*
* @mbg.generated 2017-03-23 17:01:47
*/
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
} | 6,204 | 0.606268 | 0.555175 | 245 | 24.008163 | 22.949099 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.102041 | false | false | 13 |
52c053cba316a517c5d6e4e44131ad71d1ca50ca | 32,530,082,367,439 | b031e61709d0a2efe0306d33394e8f75b6b3fc37 | /watchdog-core/src/main/java/io/watchdog/security/web/verification/sms/SmsCodeVerificationService.java | 80f96584246755ae7b6df8f2818fc5b9b2182325 | [
"Apache-2.0"
] | permissive | leatomic/watchdog | https://github.com/leatomic/watchdog | 53e054137e08b3596db96bc27e27ef6aac477eef | 8310668b98b250b5044a83fab65932c79caaf7ea | refs/heads/master | 2020-05-05T00:36:28.872000 | 2019-05-21T17:49:01 | 2019-05-21T17:49:01 | 179,580,378 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.watchdog.security.web.verification.sms;
import io.watchdog.security.verification.TokenService;
import io.watchdog.security.verification.TokenServiceException;
import io.watchdog.security.web.verification.TokenRepository;
import io.watchdog.security.web.verification.VerificationService;
import lombok.Getter;
import lombok.Setter;
import java.time.Duration;
import java.util.Map;
@Getter @Setter
public class SmsCodeVerificationService extends VerificationService<SmsCodeTokenRequest, SmsCode> {
public static final String SUPPORTED_TOKEN_TYPE = "sms_code";
public static final int DEFAULT_CODE_LENGTH = 6;
public static final Duration DEFAULT_CODE_VALIDITY_DURATION = Duration.ofMinutes(15);
private String mobilePhoneParameter = "mobile_phone"; // to which mobile phone to send
public SmsCodeVerificationService( String forBusiness,
TokenService<SmsCodeTokenRequest, SmsCode> service,
TokenRepository<SmsCode> tokenRepository) {
super(SUPPORTED_TOKEN_TYPE, forBusiness,
DEFAULT_CODE_LENGTH, DEFAULT_CODE_VALIDITY_DURATION,
service, tokenRepository);
}
public SmsCodeVerificationService(TokenService<SmsCodeTokenRequest, SmsCode> service,
TokenRepository<SmsCode> tokenRepository) {
this(DEFAULT_BUSINESS, service, tokenRepository);
}
@Override
protected SmsCodeTokenRequest createRequest(int codeLength, Duration codeValidityDuration, Map<String, String[]> parameterMap) {
String mobilePhone = obtainMobilePhone(parameterMap);
return SmsCodeTokenRequest.builder()
.codeLength(codeLength)
.codeValidityDuration(codeValidityDuration)
.mobilePhone(mobilePhone).build();
}
private String obtainMobilePhone(Map<String, String[]> params) {
String[] strings = params.get(mobilePhoneParameter);
if (strings == null || strings.length < 1) {
throw new TokenServiceException("query parameter '" + mobilePhoneParameter + "' is not found");
}
return strings[0];
}
}
| UTF-8 | Java | 2,832 | java | SmsCodeVerificationService.java | Java | [] | null | [] | /*
* Copyright (c) 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.watchdog.security.web.verification.sms;
import io.watchdog.security.verification.TokenService;
import io.watchdog.security.verification.TokenServiceException;
import io.watchdog.security.web.verification.TokenRepository;
import io.watchdog.security.web.verification.VerificationService;
import lombok.Getter;
import lombok.Setter;
import java.time.Duration;
import java.util.Map;
@Getter @Setter
public class SmsCodeVerificationService extends VerificationService<SmsCodeTokenRequest, SmsCode> {
public static final String SUPPORTED_TOKEN_TYPE = "sms_code";
public static final int DEFAULT_CODE_LENGTH = 6;
public static final Duration DEFAULT_CODE_VALIDITY_DURATION = Duration.ofMinutes(15);
private String mobilePhoneParameter = "mobile_phone"; // to which mobile phone to send
public SmsCodeVerificationService( String forBusiness,
TokenService<SmsCodeTokenRequest, SmsCode> service,
TokenRepository<SmsCode> tokenRepository) {
super(SUPPORTED_TOKEN_TYPE, forBusiness,
DEFAULT_CODE_LENGTH, DEFAULT_CODE_VALIDITY_DURATION,
service, tokenRepository);
}
public SmsCodeVerificationService(TokenService<SmsCodeTokenRequest, SmsCode> service,
TokenRepository<SmsCode> tokenRepository) {
this(DEFAULT_BUSINESS, service, tokenRepository);
}
@Override
protected SmsCodeTokenRequest createRequest(int codeLength, Duration codeValidityDuration, Map<String, String[]> parameterMap) {
String mobilePhone = obtainMobilePhone(parameterMap);
return SmsCodeTokenRequest.builder()
.codeLength(codeLength)
.codeValidityDuration(codeValidityDuration)
.mobilePhone(mobilePhone).build();
}
private String obtainMobilePhone(Map<String, String[]> params) {
String[] strings = params.get(mobilePhoneParameter);
if (strings == null || strings.length < 1) {
throw new TokenServiceException("query parameter '" + mobilePhoneParameter + "' is not found");
}
return strings[0];
}
}
| 2,832 | 0.70339 | 0.698799 | 78 | 35.307693 | 34.141602 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564103 | false | false | 13 |
11406a2c7e123334839fa7ed43c83442380997da | 32,341,103,762,249 | 65c44eae02cb1933a9b07cbead942cca168b92d3 | /src/main/java/com/icms/cms/model/base/BaseAdminRole.java | ac1d8d95107593051cf2fbd4bfb7c19bdc1a9d2a | [] | no_license | hezhengwei92/icms | https://github.com/hezhengwei92/icms | efc652998fc66685d06d37b6eb303d8bfecf52c2 | 38e78f984d030d1174131ff5bc0a3810d6ea1c6d | refs/heads/master | 2021-08-23T08:43:52.466000 | 2017-12-04T10:26:16 | 2017-12-04T10:26:16 | 113,028,453 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.icms.cms.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseAdminRole<M extends BaseAdminRole<M>> extends Model<M> implements IBean {
public void setId(java.lang.Integer id) {
set("id", id);
}
public java.lang.Integer getId() {
return get("id");
}
public void setAdminId(java.lang.Integer adminId) {
set("admin_id", adminId);
}
public java.lang.Integer getAdminId() {
return get("admin_id");
}
public void setRoleId(java.lang.Integer roleId) {
set("role_id", roleId);
}
public java.lang.Integer getRoleId() {
return get("role_id");
}
}
| UTF-8 | Java | 743 | java | BaseAdminRole.java | Java | [] | null | [] | package com.icms.cms.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseAdminRole<M extends BaseAdminRole<M>> extends Model<M> implements IBean {
public void setId(java.lang.Integer id) {
set("id", id);
}
public java.lang.Integer getId() {
return get("id");
}
public void setAdminId(java.lang.Integer adminId) {
set("admin_id", adminId);
}
public java.lang.Integer getAdminId() {
return get("admin_id");
}
public void setRoleId(java.lang.Integer roleId) {
set("role_id", roleId);
}
public java.lang.Integer getRoleId() {
return get("role_id");
}
}
| 743 | 0.705249 | 0.705249 | 36 | 19.638889 | 22.591976 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.027778 | false | false | 13 |
8744cf559342d6cc5112ba07c3c53f0aa163f30f | 17,317,308,160,193 | 08aa3146ef613b09539fdcab717dc0b70047792d | /src/test/java/com/jakubfilipiak/restthymeleaf/TestPass.java | 79adc8139ecdd24745678d248eb841e6f90fd223 | [] | no_license | JakubFilipiak/Spring-Boot-REST-Security---reference-app | https://github.com/JakubFilipiak/Spring-Boot-REST-Security---reference-app | e5b08f2edefdcedc82db5d9dc8f0d5a317f81fae | c34829fb9f483d1c5c22af27b2e876e8b53e4adf | refs/heads/master | 2022-07-16T14:45:49.275000 | 2019-05-27T17:47:53 | 2019-05-27T17:47:53 | 188,886,775 | 0 | 0 | null | false | 2022-06-29T17:24:08 | 2019-05-27T17:49:37 | 2019-05-31T19:42:29 | 2022-06-29T17:24:06 | 18 | 0 | 0 | 1 | Java | false | false | package com.jakubfilipiak.restthymeleaf;
import org.junit.Test;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* Created by Jakub Filipiak on 10.05.2019.
*/
public class TestPass {
@Test
public void getPass() {
getPassHash();
}
private PasswordEncoder getPassHash() {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
System.out.println(passwordEncoder.encode("user"));
return new BCryptPasswordEncoder();
}
}
| UTF-8 | Java | 580 | java | TestPass.java | Java | [
{
"context": "rypto.password.PasswordEncoder;\n\n/**\n * Created by Jakub Filipiak on 10.05.2019.\n */\npublic class TestPass {\n\n @",
"end": 240,
"score": 0.9998908638954163,
"start": 226,
"tag": "NAME",
"value": "Jakub Filipiak"
}
] | null | [] | package com.jakubfilipiak.restthymeleaf;
import org.junit.Test;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* Created by <NAME> on 10.05.2019.
*/
public class TestPass {
@Test
public void getPass() {
getPassHash();
}
private PasswordEncoder getPassHash() {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
System.out.println(passwordEncoder.encode("user"));
return new BCryptPasswordEncoder();
}
}
| 572 | 0.725862 | 0.712069 | 22 | 25.363636 | 24.82584 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 13 |
3791a331a49f3b019da3c79debd11ee747634657 | 3,736,621,560,884 | 106c512834e8ba9d1424d0e41463fc2874b3c6cc | /src/test/java/it/unical/demacs/inf/asd/ProgettoAgile8/EsameMedicoServiceTest.java | 28c1d0cd3212ad5f33d175a06493cd1f54f18b3b | [] | no_license | packo97/ProgettoAgile8 | https://github.com/packo97/ProgettoAgile8 | 4ce5d91dd63920a5aa7047fe7975b94d54d04d5b | 244d5dd0444378a35f89440a695a502e148095fb | refs/heads/master | 2023-02-22T06:34:35.799000 | 2021-01-21T22:08:28 | 2021-01-21T22:08:28 | 318,741,469 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.unical.demacs.inf.asd.ProgettoAgile8;
import it.unical.demacs.inf.asd.ProgettoAgile8.dto.*;
import it.unical.demacs.inf.asd.ProgettoAgile8.service.AnimaleService;
import it.unical.demacs.inf.asd.ProgettoAgile8.service.DottoreService;
import it.unical.demacs.inf.asd.ProgettoAgile8.service.Esame_medicoService;
import it.unical.demacs.inf.asd.ProgettoAgile8.service.PazienteService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.security.NoSuchAlgorithmException;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsameMedicoServiceTest {
@Autowired
Esame_medicoService esame_medicoService;
@Autowired
PazienteService pazienteService;
@Autowired
DottoreService dottoreService;
@Autowired
AnimaleService animaleService;
@Test
public void testUpdate() throws NoSuchAlgorithmException {
DottoreDTO dottore = new DottoreDTO();
dottore.setCodice_fiscale("lvrtzn98c43h579z");
dottore.setCodice_identificativo("3");
dottore.setCognome("Rossi");
dottore.setEmail("testEsami@a.it");
dottore.setNome("Mario");
dottore.setNumero_telefono("212121212");
dottore.setPassword("abc");
dottore.setSalt("32");
dottoreService.addDottore(dottore);
PazienteDTO paziente = new PazienteDTO();
paziente.setCodice_fiscale("lvrtzn98c43h579z");
paziente.setCognome("Rossi");
paziente.setEmail("testEsami@a.it");
paziente.setNome("Mario");
paziente.setNumero_telefono("212121212");
paziente.setPassword("abc");
paziente.setSalt("32");
pazienteService.addPaziente(paziente);
AnimaleDTO animale= new AnimaleDTO();
animale.setNome("billy");
animale.setPaziente(pazienteService.getPazienteByEmail("testEsami@a.it"));
animaleService.addAnimale(animale);
paziente = pazienteService.getPazienteByEmail("testEsami@a.it");
DottoreDTO d=dottoreService.getDottoreByEmail("testEsami@a.it");
List<AnimaleDTO> lista= animaleService.findAllByPaziente(paziente);
try {
File myObj = new File("filename.pdf");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
FileWriter myWriter = new FileWriter("filename.pdf");
myWriter.write("Test file");
myWriter.close();
byte[] bytes = Files.readAllBytes(myObj.toPath());
esame_medicoService.uploadFile(bytes,d,lista.get(0),"test");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
@Test
public void testFindAllByAnimale() throws NoSuchAlgorithmException {
DottoreDTO dottore = new DottoreDTO();
dottore.setCodice_fiscale("lvrtzn98c43h579z");
dottore.setCodice_identificativo("3");
dottore.setCognome("Rossi");
dottore.setEmail("testEsami2@a.it");
dottore.setNome("Mario");
dottore.setNumero_telefono("212121212");
dottore.setPassword("abc");
dottore.setSalt("32");
dottoreService.addDottore(dottore);
PazienteDTO paziente = new PazienteDTO();
paziente.setCodice_fiscale("lvrtzn98c43h579z");
paziente.setCognome("Rossi");
paziente.setEmail("testEsami2@a.it");
paziente.setNome("Mario");
paziente.setNumero_telefono("212121212");
paziente.setPassword("abc");
paziente.setSalt("32");
pazienteService.addPaziente(paziente);
AnimaleDTO animale= new AnimaleDTO();
animale.setNome("billy");
animale.setPaziente(pazienteService.getPazienteByEmail("testEsami2@a.it"));
animaleService.addAnimale(animale);
paziente = pazienteService.getPazienteByEmail("testEsami2@a.it");
DottoreDTO d=dottoreService.getDottoreByEmail("testEsami2@a.it");
List<AnimaleDTO> lista= animaleService.findAllByPaziente(paziente);
try {
File myObj = new File("filename2.pdf");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
FileWriter myWriter = new FileWriter("filename2.pdf");
myWriter.write("Test file 2");
myWriter.close();
byte[] bytes = Files.readAllBytes(myObj.toPath());
esame_medicoService.uploadFile(bytes,d,lista.get(0), "test");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
Assert.assertTrue(esame_medicoService.findAllByAnimale(lista.get(0)).size()>0);
}
@Test
public void testFindAllById() throws NoSuchAlgorithmException {
DottoreDTO dottore = new DottoreDTO();
dottore.setCodice_fiscale("lvrtzn98c43h579z");
dottore.setCodice_identificativo("3");
dottore.setCognome("Rossi");
dottore.setEmail("testEsami3@a.it");
dottore.setNome("Mario");
dottore.setNumero_telefono("212121212");
dottore.setPassword("abc");
dottore.setSalt("32");
dottoreService.addDottore(dottore);
PazienteDTO paziente = new PazienteDTO();
paziente.setCodice_fiscale("lvrtzn98c43h579z");
paziente.setCognome("Rossi");
paziente.setEmail("testEsami3@a.it");
paziente.setNome("Mario");
paziente.setNumero_telefono("212121212");
paziente.setPassword("abc");
paziente.setSalt("32");
pazienteService.addPaziente(paziente);
AnimaleDTO animale= new AnimaleDTO();
animale.setNome("billy");
animale.setPaziente(pazienteService.getPazienteByEmail("testEsami3@a.it"));
animaleService.addAnimale(animale);
paziente = pazienteService.getPazienteByEmail("testEsami3@a.it");
DottoreDTO d=dottoreService.getDottoreByEmail("testEsami3@a.it");
List<AnimaleDTO> lista= animaleService.findAllByPaziente(paziente);
try {
File myObj = new File("filename2.pdf");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
FileWriter myWriter = new FileWriter("filename2.pdf");
myWriter.write("Test file 2");
myWriter.close();
byte[] bytes = Files.readAllBytes(myObj.toPath());
esame_medicoService.uploadFile(bytes,d,lista.get(0), "test");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
List<Esame_medicoDTO> esami = esame_medicoService.findAllByAnimale(lista.get(0));
Esame_medicoDTO risultato = esame_medicoService.findAllById(esami.get(0).getId());
//System.out.println(esami.get(0).getId() + " " + risultato.getId());
Assert.assertEquals(esami.get(0).getId(), risultato.getId());
}
}
| UTF-8 | Java | 7,603 | java | EsameMedicoServiceTest.java | Java | [
{
"context": "_identificativo(\"3\");\n dottore.setCognome(\"Rossi\");\n dottore.setEmail(\"testEsami@a.it\");\n ",
"end": 1392,
"score": 0.9988104701042175,
"start": 1387,
"tag": "NAME",
"value": "Rossi"
},
{
"context": "re.setCognome(\"Rossi\");\n dottore.setEmail(\"testEsami@a.it\");\n dottore.setNome(\"Mario\");\n dott",
"end": 1436,
"score": 0.9999280571937561,
"start": 1422,
"tag": "EMAIL",
"value": "testEsami@a.it"
},
{
"context": "Email(\"testEsami@a.it\");\n dottore.setNome(\"Mario\");\n dottore.setNumero_telefono(\"212121212\"",
"end": 1470,
"score": 0.9995476007461548,
"start": 1465,
"tag": "NAME",
"value": "Mario"
},
{
"context": "lefono(\"212121212\");\n dottore.setPassword(\"abc\");\n dottore.setSalt(\"32\");\n dottore",
"end": 1555,
"score": 0.9994927644729614,
"start": 1552,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "\"lvrtzn98c43h579z\");\n paziente.setCognome(\"Rossi\");\n paziente.setEmail(\"testEsami@a.it\");\n ",
"end": 1774,
"score": 0.9996208548545837,
"start": 1769,
"tag": "NAME",
"value": "Rossi"
},
{
"context": "e.setCognome(\"Rossi\");\n paziente.setEmail(\"testEsami@a.it\");\n paziente.setNome(\"Mario\");\n paz",
"end": 1819,
"score": 0.9999269843101501,
"start": 1805,
"tag": "EMAIL",
"value": "testEsami@a.it"
},
{
"context": "mail(\"testEsami@a.it\");\n paziente.setNome(\"Mario\");\n paziente.setNumero_telefono(\"212121212",
"end": 1854,
"score": 0.9996492862701416,
"start": 1849,
"tag": "NAME",
"value": "Mario"
},
{
"context": "efono(\"212121212\");\n paziente.setPassword(\"abc\");\n paziente.setSalt(\"32\");\n\n pazie",
"end": 1941,
"score": 0.999387264251709,
"start": 1938,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "imale= new AnimaleDTO();\n animale.setNome(\"billy\");\n animale.setPaziente(pazienteService.ge",
"end": 2101,
"score": 0.8919485807418823,
"start": 2096,
"tag": "NAME",
"value": "billy"
},
{
"context": "e.setPaziente(pazienteService.getPazienteByEmail(\"testEsami@a.it\"));\n animaleService.addAnimale(animale);\n\n",
"end": 2183,
"score": 0.9999269843101501,
"start": 2169,
"tag": "EMAIL",
"value": "testEsami@a.it"
},
{
"context": " paziente = pazienteService.getPazienteByEmail(\"testEsami@a.it\");\n DottoreDTO d=dottoreService.getDottore",
"end": 2302,
"score": 0.9999261498451233,
"start": 2288,
"tag": "EMAIL",
"value": "testEsami@a.it"
},
{
"context": " DottoreDTO d=dottoreService.getDottoreByEmail(\"testEsami@a.it\");\n List<AnimaleDTO> lista= animaleService",
"end": 2375,
"score": 0.9999247789382935,
"start": 2361,
"tag": "EMAIL",
"value": "testEsami@a.it"
},
{
"context": "_identificativo(\"3\");\n dottore.setCognome(\"Rossi\");\n dottore.setEmail(\"testEsami2@a.it\");\n ",
"end": 3405,
"score": 0.9997252225875854,
"start": 3400,
"tag": "NAME",
"value": "Rossi"
},
{
"context": "re.setCognome(\"Rossi\");\n dottore.setEmail(\"testEsami2@a.it\");\n dottore.setNome(\"Mario\");\n dott",
"end": 3450,
"score": 0.9999295473098755,
"start": 3435,
"tag": "EMAIL",
"value": "testEsami2@a.it"
},
{
"context": "mail(\"testEsami2@a.it\");\n dottore.setNome(\"Mario\");\n dottore.setNumero_telefono(\"212121212\"",
"end": 3484,
"score": 0.9997428059577942,
"start": 3479,
"tag": "NAME",
"value": "Mario"
},
{
"context": "lefono(\"212121212\");\n dottore.setPassword(\"abc\");\n dottore.setSalt(\"32\");\n dottore",
"end": 3569,
"score": 0.9992602467536926,
"start": 3566,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "\"lvrtzn98c43h579z\");\n paziente.setCognome(\"Rossi\");\n paziente.setEmail(\"testEsami2@a.it\");\n",
"end": 3788,
"score": 0.9962241053581238,
"start": 3783,
"tag": "NAME",
"value": "Rossi"
},
{
"context": "e.setCognome(\"Rossi\");\n paziente.setEmail(\"testEsami2@a.it\");\n paziente.setNome(\"Mario\");\n paz",
"end": 3834,
"score": 0.9999243021011353,
"start": 3819,
"tag": "EMAIL",
"value": "testEsami2@a.it"
},
{
"context": "ail(\"testEsami2@a.it\");\n paziente.setNome(\"Mario\");\n paziente.setNumero_telefono(\"212121212",
"end": 3869,
"score": 0.9996044635772705,
"start": 3864,
"tag": "NAME",
"value": "Mario"
},
{
"context": "efono(\"212121212\");\n paziente.setPassword(\"abc\");\n paziente.setSalt(\"32\");\n\n pazie",
"end": 3956,
"score": 0.9993436932563782,
"start": 3953,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "imale= new AnimaleDTO();\n animale.setNome(\"billy\");\n animale.setPaziente(pazienteService.ge",
"end": 4116,
"score": 0.8564897775650024,
"start": 4111,
"tag": "NAME",
"value": "billy"
},
{
"context": "e.setPaziente(pazienteService.getPazienteByEmail(\"testEsami2@a.it\"));\n animaleService.addAnimale(animale);\n\n",
"end": 4199,
"score": 0.9999222159385681,
"start": 4184,
"tag": "EMAIL",
"value": "testEsami2@a.it"
},
{
"context": " paziente = pazienteService.getPazienteByEmail(\"testEsami2@a.it\");\n DottoreDTO d=dottoreService.getDottore",
"end": 4319,
"score": 0.9999218583106995,
"start": 4304,
"tag": "EMAIL",
"value": "testEsami2@a.it"
},
{
"context": " DottoreDTO d=dottoreService.getDottoreByEmail(\"testEsami2@a.it\");\n List<AnimaleDTO> lista= animaleService",
"end": 4393,
"score": 0.9999207258224487,
"start": 4378,
"tag": "EMAIL",
"value": "testEsami2@a.it"
},
{
"context": "_identificativo(\"3\");\n dottore.setCognome(\"Rossi\");\n dottore.setEmail(\"testEsami3@a.it\");\n ",
"end": 5513,
"score": 0.9997026920318604,
"start": 5508,
"tag": "NAME",
"value": "Rossi"
},
{
"context": "re.setCognome(\"Rossi\");\n dottore.setEmail(\"testEsami3@a.it\");\n dottore.setNome(\"Mario\");\n dott",
"end": 5558,
"score": 0.9999290108680725,
"start": 5543,
"tag": "EMAIL",
"value": "testEsami3@a.it"
},
{
"context": "mail(\"testEsami3@a.it\");\n dottore.setNome(\"Mario\");\n dottore.setNumero_telefono(\"212121212\"",
"end": 5592,
"score": 0.9997204542160034,
"start": 5587,
"tag": "NAME",
"value": "Mario"
},
{
"context": "lefono(\"212121212\");\n dottore.setPassword(\"abc\");\n dottore.setSalt(\"32\");\n dottore",
"end": 5677,
"score": 0.999445378780365,
"start": 5674,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "\"lvrtzn98c43h579z\");\n paziente.setCognome(\"Rossi\");\n paziente.setEmail(\"testEsami3@a.it\");\n",
"end": 5896,
"score": 0.9996681213378906,
"start": 5891,
"tag": "NAME",
"value": "Rossi"
},
{
"context": "e.setCognome(\"Rossi\");\n paziente.setEmail(\"testEsami3@a.it\");\n paziente.setNome(\"Mario\");\n paz",
"end": 5942,
"score": 0.9999300241470337,
"start": 5927,
"tag": "EMAIL",
"value": "testEsami3@a.it"
},
{
"context": "ail(\"testEsami3@a.it\");\n paziente.setNome(\"Mario\");\n paziente.setNumero_telefono(\"212121212",
"end": 5977,
"score": 0.9995523691177368,
"start": 5972,
"tag": "NAME",
"value": "Mario"
},
{
"context": "efono(\"212121212\");\n paziente.setPassword(\"abc\");\n paziente.setSalt(\"32\");\n\n pazie",
"end": 6064,
"score": 0.9994447827339172,
"start": 6061,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": "te.setPassword(\"abc\");\n paziente.setSalt(\"32\");\n\n pazienteService.addPaziente(paziente)",
"end": 6096,
"score": 0.703961968421936,
"start": 6095,
"tag": "PASSWORD",
"value": "2"
},
{
"context": "e.setPaziente(pazienteService.getPazienteByEmail(\"testEsami3@a.it\"));\n animaleService.addAnimale(animale);\n\n",
"end": 6307,
"score": 0.9999297857284546,
"start": 6292,
"tag": "EMAIL",
"value": "testEsami3@a.it"
},
{
"context": " paziente = pazienteService.getPazienteByEmail(\"testEsami3@a.it\");\n DottoreDTO d=dottoreService.getDottore",
"end": 6427,
"score": 0.9999290704727173,
"start": 6412,
"tag": "EMAIL",
"value": "testEsami3@a.it"
},
{
"context": " DottoreDTO d=dottoreService.getDottoreByEmail(\"testEsami3@a.it\");\n List<AnimaleDTO> lista= animaleService",
"end": 6501,
"score": 0.9999290704727173,
"start": 6486,
"tag": "EMAIL",
"value": "testEsami3@a.it"
}
] | null | [] | package it.unical.demacs.inf.asd.ProgettoAgile8;
import it.unical.demacs.inf.asd.ProgettoAgile8.dto.*;
import it.unical.demacs.inf.asd.ProgettoAgile8.service.AnimaleService;
import it.unical.demacs.inf.asd.ProgettoAgile8.service.DottoreService;
import it.unical.demacs.inf.asd.ProgettoAgile8.service.Esame_medicoService;
import it.unical.demacs.inf.asd.ProgettoAgile8.service.PazienteService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.security.NoSuchAlgorithmException;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsameMedicoServiceTest {
@Autowired
Esame_medicoService esame_medicoService;
@Autowired
PazienteService pazienteService;
@Autowired
DottoreService dottoreService;
@Autowired
AnimaleService animaleService;
@Test
public void testUpdate() throws NoSuchAlgorithmException {
DottoreDTO dottore = new DottoreDTO();
dottore.setCodice_fiscale("lvrtzn98c43h579z");
dottore.setCodice_identificativo("3");
dottore.setCognome("Rossi");
dottore.setEmail("<EMAIL>");
dottore.setNome("Mario");
dottore.setNumero_telefono("212121212");
dottore.setPassword("abc");
dottore.setSalt("32");
dottoreService.addDottore(dottore);
PazienteDTO paziente = new PazienteDTO();
paziente.setCodice_fiscale("lvrtzn98c43h579z");
paziente.setCognome("Rossi");
paziente.setEmail("<EMAIL>");
paziente.setNome("Mario");
paziente.setNumero_telefono("212121212");
paziente.setPassword("abc");
paziente.setSalt("32");
pazienteService.addPaziente(paziente);
AnimaleDTO animale= new AnimaleDTO();
animale.setNome("billy");
animale.setPaziente(pazienteService.getPazienteByEmail("<EMAIL>"));
animaleService.addAnimale(animale);
paziente = pazienteService.getPazienteByEmail("<EMAIL>");
DottoreDTO d=dottoreService.getDottoreByEmail("<EMAIL>");
List<AnimaleDTO> lista= animaleService.findAllByPaziente(paziente);
try {
File myObj = new File("filename.pdf");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
FileWriter myWriter = new FileWriter("filename.pdf");
myWriter.write("Test file");
myWriter.close();
byte[] bytes = Files.readAllBytes(myObj.toPath());
esame_medicoService.uploadFile(bytes,d,lista.get(0),"test");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
@Test
public void testFindAllByAnimale() throws NoSuchAlgorithmException {
DottoreDTO dottore = new DottoreDTO();
dottore.setCodice_fiscale("lvrtzn98c43h579z");
dottore.setCodice_identificativo("3");
dottore.setCognome("Rossi");
dottore.setEmail("<EMAIL>");
dottore.setNome("Mario");
dottore.setNumero_telefono("212121212");
dottore.setPassword("abc");
dottore.setSalt("32");
dottoreService.addDottore(dottore);
PazienteDTO paziente = new PazienteDTO();
paziente.setCodice_fiscale("lvrtzn98c43h579z");
paziente.setCognome("Rossi");
paziente.setEmail("<EMAIL>");
paziente.setNome("Mario");
paziente.setNumero_telefono("212121212");
paziente.setPassword("abc");
paziente.setSalt("32");
pazienteService.addPaziente(paziente);
AnimaleDTO animale= new AnimaleDTO();
animale.setNome("billy");
animale.setPaziente(pazienteService.getPazienteByEmail("<EMAIL>"));
animaleService.addAnimale(animale);
paziente = pazienteService.getPazienteByEmail("<EMAIL>");
DottoreDTO d=dottoreService.getDottoreByEmail("<EMAIL>");
List<AnimaleDTO> lista= animaleService.findAllByPaziente(paziente);
try {
File myObj = new File("filename2.pdf");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
FileWriter myWriter = new FileWriter("filename2.pdf");
myWriter.write("Test file 2");
myWriter.close();
byte[] bytes = Files.readAllBytes(myObj.toPath());
esame_medicoService.uploadFile(bytes,d,lista.get(0), "test");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
Assert.assertTrue(esame_medicoService.findAllByAnimale(lista.get(0)).size()>0);
}
@Test
public void testFindAllById() throws NoSuchAlgorithmException {
DottoreDTO dottore = new DottoreDTO();
dottore.setCodice_fiscale("lvrtzn98c43h579z");
dottore.setCodice_identificativo("3");
dottore.setCognome("Rossi");
dottore.setEmail("<EMAIL>");
dottore.setNome("Mario");
dottore.setNumero_telefono("212121212");
dottore.setPassword("abc");
dottore.setSalt("32");
dottoreService.addDottore(dottore);
PazienteDTO paziente = new PazienteDTO();
paziente.setCodice_fiscale("lvrtzn98c43h579z");
paziente.setCognome("Rossi");
paziente.setEmail("<EMAIL>");
paziente.setNome("Mario");
paziente.setNumero_telefono("212121212");
paziente.setPassword("abc");
paziente.setSalt("32");
pazienteService.addPaziente(paziente);
AnimaleDTO animale= new AnimaleDTO();
animale.setNome("billy");
animale.setPaziente(pazienteService.getPazienteByEmail("<EMAIL>"));
animaleService.addAnimale(animale);
paziente = pazienteService.getPazienteByEmail("<EMAIL>");
DottoreDTO d=dottoreService.getDottoreByEmail("<EMAIL>");
List<AnimaleDTO> lista= animaleService.findAllByPaziente(paziente);
try {
File myObj = new File("filename2.pdf");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
FileWriter myWriter = new FileWriter("filename2.pdf");
myWriter.write("Test file 2");
myWriter.close();
byte[] bytes = Files.readAllBytes(myObj.toPath());
esame_medicoService.uploadFile(bytes,d,lista.get(0), "test");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
List<Esame_medicoDTO> esami = esame_medicoService.findAllByAnimale(lista.get(0));
Esame_medicoDTO risultato = esame_medicoService.findAllById(esami.get(0).getId());
//System.out.println(esami.get(0).getId() + " " + risultato.getId());
Assert.assertEquals(esami.get(0).getId(), risultato.getId());
}
}
| 7,488 | 0.65027 | 0.631461 | 194 | 38.190723 | 23.619181 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747423 | false | false | 13 |
b2c60e4626d978499b91d65e734bfbb253f1f281 | 30,983,894,095,992 | f181a87f3c371c1c9cf705ccc017b15899908893 | /Corejava/Lab6/Experiment2.java | 2b11f698d303667650be2de65564eb5c7720e6d5 | [] | no_license | ujjawaltomar1/Module1 | https://github.com/ujjawaltomar1/Module1 | de5f2b76b0a029417e10230afbbc1ae9b9936e6f | 052e0b94f6ad3fa23bb037a7559adcd7580e1066 | refs/heads/master | 2021-01-16T03:13:30.867000 | 2020-02-25T11:58:24 | 2020-02-25T11:58:24 | 242,958,016 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Lab6;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Experiment2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader file=new FileReader("c://corejava//capgemini//hello.txt");
BufferedReader reader =new BufferedReader(file);
int p=1;
String s="";
while((s=reader.readLine())!=null)
{
System.out.println(p++ + s);
}
}
}
| UTF-8 | Java | 520 | java | Experiment2.java | Java | [] | null | [] | package Lab6;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Experiment2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileReader file=new FileReader("c://corejava//capgemini//hello.txt");
BufferedReader reader =new BufferedReader(file);
int p=1;
String s="";
while((s=reader.readLine())!=null)
{
System.out.println(p++ + s);
}
}
}
| 520 | 0.721154 | 0.715385 | 22 | 22.636364 | 19.843811 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.545455 | false | false | 13 |
95f12ccf7c7d9a703f1e003de84f8bb4735b7970 | 30,983,894,095,455 | d2fe17deab32e75e29f39282666832eca49a3038 | /src/main/java/CSVExtraction.java | 89a3a0116b55261d8b79f010a2383d971d21e1ee | [] | no_license | RajatDevSharma/RepoExt | https://github.com/RajatDevSharma/RepoExt | 2bb6d364377b471d6ea5f9ea20310838a1223b0a | 8ad756e76b7903c58c7833587574555ec2f1e9a6 | refs/heads/master | 2018-09-12T05:00:27.585000 | 2018-06-05T14:24:09 | 2018-06-05T14:24:09 | 117,958,605 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import com.opencsv.CSVReaderBuilder;
public class CSVExtraction {
public static void main(String[] args) {
HashMap<String, ModelFileClass1> map1 = readFile1();
ArrayList<String> userNameList = new ArrayList<String>();
HashMap<String, ModelFileClass2> map2 = readFile2(userNameList);
// System.out.println(map1.get("aa@").getEmpID());
// System.out.println(map2.get(""));
// System.out.println(userNameList);
}
static HashMap<String, ModelFileClass1> readFile1()
{
HashMap<String, ModelFileClass1> map = new HashMap<String, ModelFileClass1>();
try {
CSVReader reader = new CSVReaderBuilder(new FileReader("csvfiles/psm_email_id_key_mapping.csv")).withSkipLines(1).build();
String[] record = null;
while ((record = reader.readNext()) != null) {
ModelFileClass1 f1 = new ModelFileClass1();
// System.out.println(record[1]);
f1.setBoLogin(record[0]);
f1.setEmpID(Integer.parseInt(record[1]));
f1.setBoEmpID(Integer.parseInt(record[2]));
// list.add(f1);
map.put(record[0],f1);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
return map;
}
static HashMap<String, ModelFileClass2> readFile2(ArrayList<String> userNameList)
{
HashMap<String, ModelFileClass2> map = new HashMap<String, ModelFileClass2>();
try {
CSVReader reader = new CSVReaderBuilder(new FileReader("csvfiles/UBS_PSM_DATA_V4.csv")).withSkipLines(1).build();
String[] record = null;
while ((record = reader.readNext()) != null) {
ModelFileClass2 f2 = new ModelFileClass2();
f2.setBoLogin(record[0]);
f2.setGitUserName(record[1]);
f2.setGitUserProfile(record[2]);
map.put(record[0], f2);
if(!record[1].equals("")) {
userNameList.add(record[1]);
}
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
return map;
}
} | UTF-8 | Java | 2,357 | java | CSVExtraction.java | Java | [] | null | [] | import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import com.opencsv.CSVReaderBuilder;
public class CSVExtraction {
public static void main(String[] args) {
HashMap<String, ModelFileClass1> map1 = readFile1();
ArrayList<String> userNameList = new ArrayList<String>();
HashMap<String, ModelFileClass2> map2 = readFile2(userNameList);
// System.out.println(map1.get("aa@").getEmpID());
// System.out.println(map2.get(""));
// System.out.println(userNameList);
}
static HashMap<String, ModelFileClass1> readFile1()
{
HashMap<String, ModelFileClass1> map = new HashMap<String, ModelFileClass1>();
try {
CSVReader reader = new CSVReaderBuilder(new FileReader("csvfiles/psm_email_id_key_mapping.csv")).withSkipLines(1).build();
String[] record = null;
while ((record = reader.readNext()) != null) {
ModelFileClass1 f1 = new ModelFileClass1();
// System.out.println(record[1]);
f1.setBoLogin(record[0]);
f1.setEmpID(Integer.parseInt(record[1]));
f1.setBoEmpID(Integer.parseInt(record[2]));
// list.add(f1);
map.put(record[0],f1);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
return map;
}
static HashMap<String, ModelFileClass2> readFile2(ArrayList<String> userNameList)
{
HashMap<String, ModelFileClass2> map = new HashMap<String, ModelFileClass2>();
try {
CSVReader reader = new CSVReaderBuilder(new FileReader("csvfiles/UBS_PSM_DATA_V4.csv")).withSkipLines(1).build();
String[] record = null;
while ((record = reader.readNext()) != null) {
ModelFileClass2 f2 = new ModelFileClass2();
f2.setBoLogin(record[0]);
f2.setGitUserName(record[1]);
f2.setGitUserProfile(record[2]);
map.put(record[0], f2);
if(!record[1].equals("")) {
userNameList.add(record[1]);
}
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
return map;
}
} | 2,357 | 0.631735 | 0.612643 | 79 | 28.848101 | 26.591181 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632911 | false | false | 13 |
e54d8c6206c9ca45300350b842eea4260c500a55 | 3,204,045,631,614 | ca0b7eb4754b7189ca4ba8dd27500ca0ed1ff7da | /Somatorio/Produtor.java | af3efa2d155834df98cf5ed8aa093115c27836ef | [
"MIT"
] | permissive | jonathan-freitas/java | https://github.com/jonathan-freitas/java | 0ecaef1f5f1e86eeb93d79b9a9405e88006be7fe | b581fe3458e9a0d9ff5a46fbaf6a9a3a2ba11a98 | refs/heads/master | 2021-09-27T12:53:09.400000 | 2018-11-08T16:50:49 | 2018-11-08T16:50:49 | 92,427,397 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Somatorio;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Created by Jonathan Freitas on 06/03/2017.
*/
public class Produtor extends Thread{
//Mantendo as referencias das variaveis
ConcurrentLinkedQueue<Integer> list = null;
Finish finish = null;
//Metodo Construtor
public Produtor(ConcurrentLinkedQueue list, Finish finish) {
this.list = list;
this.finish = finish;
}
public void run() {
//Adicionando valores na fila
for (int i = 1; i <= 10001; i++) {
list.add(i);
}
//A variavel finish ira dar o start para as threads
finish.setFinish(true);
System.out.println("Produtor terminou.");
}
} | UTF-8 | Java | 767 | java | Produtor.java | Java | [
{
"context": "rrent.ConcurrentLinkedQueue;\r\n\r\n/**\r\n * Created by Jonathan Freitas on 06/03/2017.\r\n */\r\n\r\npublic class Produtor exte",
"end": 109,
"score": 0.9998669028282166,
"start": 93,
"tag": "NAME",
"value": "Jonathan Freitas"
}
] | null | [] | package Somatorio;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Created by <NAME> on 06/03/2017.
*/
public class Produtor extends Thread{
//Mantendo as referencias das variaveis
ConcurrentLinkedQueue<Integer> list = null;
Finish finish = null;
//Metodo Construtor
public Produtor(ConcurrentLinkedQueue list, Finish finish) {
this.list = list;
this.finish = finish;
}
public void run() {
//Adicionando valores na fila
for (int i = 1; i <= 10001; i++) {
list.add(i);
}
//A variavel finish ira dar o start para as threads
finish.setFinish(true);
System.out.println("Produtor terminou.");
}
} | 757 | 0.597132 | 0.578879 | 32 | 22.03125 | 20.275423 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 13 |
c640985925d11656b824886446d821c9420a7e52 | 3,204,045,631,069 | f7dcf6b5a2ec1cbd8e17f8b8c5af0a19d7cd520b | /app/src/main/java/com/jwcnetworks/bsyoo/jwc/user/terms/TermsActivity.java | 58a81c77779eccb3244c7c3b2e11480072499dab | [] | no_license | dbqudtjd1122/MyJWC | https://github.com/dbqudtjd1122/MyJWC | 935506534c5bf1b4ee7dc5b974eedeed5f0aa68b | 6f36a5a4b9bf15edea5d2350655fda70112def64 | refs/heads/master | 2021-09-13T06:55:00.294000 | 2018-04-26T06:50:48 | 2018-04-26T06:50:48 | 109,110,060 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jwcnetworks.bsyoo.jwc.user.terms;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import com.jwcnetworks.bsyoo.jwc.R;
public class TermsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terms);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 액션바에 백그라운드 이미지 넣기
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Drawable d = getResources().getDrawable(R.drawable.actionbar);
getSupportActionBar().setBackgroundDrawable(d);
setTitle("이용약관");
Intent intent = getIntent();
int i = intent.getIntExtra("순서", 0);
// 뒤로가기 버튼
/*getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);*/
// TabLayout 초기화
TabLayout tabLayout = (TabLayout) findViewById(R.id.terms_tab_layout);
tabLayout.setBackgroundColor(Color.parseColor("#FFFFFFFF"));
tabLayout.setTabTextColors(ColorStateList.valueOf(Color.BLACK));
tabLayout.addTab(tabLayout.newTab().setText("회원가입 이용약관"));
tabLayout.addTab(tabLayout.newTab().setText("개인정보 취급방침"));
// ViewPager 초기화
final ViewPager viewPager = (ViewPager) findViewById(R.id.terms_view_pager);
// PagerAdater 생성
TermsTabPagerAdapter pagerAdapter = new TermsTabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
// PagerAdapter와 ViewPager 연결 : Fragment와 ViewPager 연결
viewPager.setAdapter(pagerAdapter);
// 탭 시작지점 정하는부분
if(i==0) {
viewPager.setCurrentItem(0);
} else {
viewPager.setCurrentItem(1);
}
// ViewPager의 OnPageChangeListener 리스너 설정 : TabLayout과 ViewPager
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
// TabSelectedListener 설정 : 화면에서 tab을 클릭할때
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem( tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem( tab.getPosition());
}
});
}
}
| UTF-8 | Java | 3,541 | java | TermsActivity.java | Java | [] | null | [] | package com.jwcnetworks.bsyoo.jwc.user.terms;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import com.jwcnetworks.bsyoo.jwc.R;
public class TermsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terms);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 액션바에 백그라운드 이미지 넣기
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Drawable d = getResources().getDrawable(R.drawable.actionbar);
getSupportActionBar().setBackgroundDrawable(d);
setTitle("이용약관");
Intent intent = getIntent();
int i = intent.getIntExtra("순서", 0);
// 뒤로가기 버튼
/*getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);*/
// TabLayout 초기화
TabLayout tabLayout = (TabLayout) findViewById(R.id.terms_tab_layout);
tabLayout.setBackgroundColor(Color.parseColor("#FFFFFFFF"));
tabLayout.setTabTextColors(ColorStateList.valueOf(Color.BLACK));
tabLayout.addTab(tabLayout.newTab().setText("회원가입 이용약관"));
tabLayout.addTab(tabLayout.newTab().setText("개인정보 취급방침"));
// ViewPager 초기화
final ViewPager viewPager = (ViewPager) findViewById(R.id.terms_view_pager);
// PagerAdater 생성
TermsTabPagerAdapter pagerAdapter = new TermsTabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
// PagerAdapter와 ViewPager 연결 : Fragment와 ViewPager 연결
viewPager.setAdapter(pagerAdapter);
// 탭 시작지점 정하는부분
if(i==0) {
viewPager.setCurrentItem(0);
} else {
viewPager.setCurrentItem(1);
}
// ViewPager의 OnPageChangeListener 리스너 설정 : TabLayout과 ViewPager
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
// TabSelectedListener 설정 : 화면에서 tab을 클릭할때
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem( tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem( tab.getPosition());
}
});
}
}
| 3,541 | 0.664097 | 0.662022 | 99 | 33.070705 | 28.53042 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434343 | false | false | 13 |
bdcd2ef959d53b4d2a514722ace481ebfb1634ad | 12,300,786,373,845 | 6d59a74529ee5af8da8a7e66b1e2e1da08ff6aa9 | /blocks.java | cda0f90436f697be5c4d3eadfe6a20e3271206ce | [] | no_license | liluc/Tetris | https://github.com/liluc/Tetris | a54fe7e0b1c0c287e932577bcd7123da0d540149 | 786404d3b2b4a6039e6aca9dcaf424a2c941bf2d | refs/heads/main | 2023-08-04T13:30:38.225000 | 2021-09-12T22:14:34 | 2021-09-12T22:14:34 | 362,964,718 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* @author Lucas Li
* A bigger unit to make the tetris.
* Some movement just related to the single block
*/
public class blocks {
private cells[] location;
private String type;
int count;
//The constructor takes two int as parameter. The ints are the starting point of the block object
//Create different blocks based on the starting point.
public blocks(String type, int x, int y){
location = new cells[4];
this.type = type;
switch (type){
case "I":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 2, y);
location[3] = new cells(x + 3, y);
break;
case "L":
location[0] = new cells(x,y);
location[1] = new cells(x, y - 1);
location[2] = new cells(x + 1, y - 1);
location[3] = new cells(x + 2, y - 1);
break;
case "iL":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 2, y);
location[3] = new cells(x + 2, y + 1);
break;
case "Z":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 1, y + 1);
location[3] = new cells(x + 2, y + 1);
break;
case "iZ":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 1, y - 1);
location[3] = new cells(x + 2, y - 1);
break;
case "T":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 1, y - 1);
location[3] = new cells(x + 2, y);
break;
case "O":
location[0] = new cells(x,y);
location[1] = new cells(x, y - 1);
location[2] = new cells(x + 1, y);
location[3] = new cells(x + 1, y - 1);
break;
}
}
//set the new location for the block
public blocks(cells[] location){
this.location = location;
}
//rotate the block
public void rotate(){
cells[] position = this.location;
//differences between the starting location of a block and (0,0) in x-y coordinate.
int xDiff = position[1].getX();
int yDiff = position[1].getY();
//Spin the block counterclockwise for 90 degrees.
for (int i = 0; i < position.length; i++){
//get each cell
cells thisOne = position[i];
//fold every cell in the x-y coordinate with line y = -x as the axis
cells needToBeRotate = new cells(thisOne.getX() - xDiff, thisOne.getY() - yDiff);
//then fold ever cell with x axis as the folding axis
position[i].move(needToBeRotate.getY() + xDiff,-1 * needToBeRotate.getX() + yDiff);
}
}
//move right
public void moveRight(){
for (cells x : location){
x.move(x.getX() + 1, x.getY());
}
}
//move left
public void moveLeft(){
for (cells x : location){
x.move(x.getX() - 1, x.getY());
}
}
//move down by 1
public void drop(){
for (int i = 0; i < location.length; i++){
location[i].move(location[i].getX(), location[i].getY() + 1);
}
}
//print out the block to make it easier for debugging
public String toString(){
int[][] result= new int[4][2];
for (int i = 0; i < 4; i++){
for (int m = 0; m < 2; m++){
if (m == 0){
result[i][m] = location[i].getX();
}
else{
result[i][m] = location[i].getY();
}
}
}
String str = "{";
for (int[] x : result){
str += "(";
for (int c : x){
str += c + ", ";
}
str = str.substring(0, str.length() - 2) + ")";
}
str += "}";
return str;
}
//just some get method, return the coordinate fields.
cells[] getLocation(){
return location;
}
String getType(){
return type;
}
//relocate the block without changing the type of the block.
void setLocation(cells[] cells){
location = cells;
}
}
| UTF-8 | Java | 4,657 | java | blocks.java | Java | [
{
"context": "\n/**\n * @author Lucas Li\n * A bigger unit to make the tetris.\n * Some move",
"end": 24,
"score": 0.9996511340141296,
"start": 16,
"tag": "NAME",
"value": "Lucas Li"
}
] | null | [] |
/**
* @author <NAME>
* A bigger unit to make the tetris.
* Some movement just related to the single block
*/
public class blocks {
private cells[] location;
private String type;
int count;
//The constructor takes two int as parameter. The ints are the starting point of the block object
//Create different blocks based on the starting point.
public blocks(String type, int x, int y){
location = new cells[4];
this.type = type;
switch (type){
case "I":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 2, y);
location[3] = new cells(x + 3, y);
break;
case "L":
location[0] = new cells(x,y);
location[1] = new cells(x, y - 1);
location[2] = new cells(x + 1, y - 1);
location[3] = new cells(x + 2, y - 1);
break;
case "iL":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 2, y);
location[3] = new cells(x + 2, y + 1);
break;
case "Z":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 1, y + 1);
location[3] = new cells(x + 2, y + 1);
break;
case "iZ":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 1, y - 1);
location[3] = new cells(x + 2, y - 1);
break;
case "T":
location[0] = new cells(x,y);
location[1] = new cells(x + 1, y);
location[2] = new cells(x + 1, y - 1);
location[3] = new cells(x + 2, y);
break;
case "O":
location[0] = new cells(x,y);
location[1] = new cells(x, y - 1);
location[2] = new cells(x + 1, y);
location[3] = new cells(x + 1, y - 1);
break;
}
}
//set the new location for the block
public blocks(cells[] location){
this.location = location;
}
//rotate the block
public void rotate(){
cells[] position = this.location;
//differences between the starting location of a block and (0,0) in x-y coordinate.
int xDiff = position[1].getX();
int yDiff = position[1].getY();
//Spin the block counterclockwise for 90 degrees.
for (int i = 0; i < position.length; i++){
//get each cell
cells thisOne = position[i];
//fold every cell in the x-y coordinate with line y = -x as the axis
cells needToBeRotate = new cells(thisOne.getX() - xDiff, thisOne.getY() - yDiff);
//then fold ever cell with x axis as the folding axis
position[i].move(needToBeRotate.getY() + xDiff,-1 * needToBeRotate.getX() + yDiff);
}
}
//move right
public void moveRight(){
for (cells x : location){
x.move(x.getX() + 1, x.getY());
}
}
//move left
public void moveLeft(){
for (cells x : location){
x.move(x.getX() - 1, x.getY());
}
}
//move down by 1
public void drop(){
for (int i = 0; i < location.length; i++){
location[i].move(location[i].getX(), location[i].getY() + 1);
}
}
//print out the block to make it easier for debugging
public String toString(){
int[][] result= new int[4][2];
for (int i = 0; i < 4; i++){
for (int m = 0; m < 2; m++){
if (m == 0){
result[i][m] = location[i].getX();
}
else{
result[i][m] = location[i].getY();
}
}
}
String str = "{";
for (int[] x : result){
str += "(";
for (int c : x){
str += c + ", ";
}
str = str.substring(0, str.length() - 2) + ")";
}
str += "}";
return str;
}
//just some get method, return the coordinate fields.
cells[] getLocation(){
return location;
}
String getType(){
return type;
}
//relocate the block without changing the type of the block.
void setLocation(cells[] cells){
location = cells;
}
}
| 4,655 | 0.455229 | 0.437836 | 154 | 29.233767 | 22.365265 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707792 | false | false | 13 |
09188c596d5aff170378fd88eb1d54572a5b9a21 | 21,148,418,988,618 | 6fa23e1a6bcfd58b18d49485a1cab8449ab118d9 | /src/BookTest.java | 0ca81c4e4e28214f5c590cee2e026c6e6e7f95f7 | [] | no_license | kalyang95/JavaProgramms | https://github.com/kalyang95/JavaProgramms | d3c092a55497218f5511d264747e29970d44e630 | 8836b72bb82bca64843490896e28bdaca87a5b22 | refs/heads/master | 2023-06-16T18:00:07.354000 | 2021-07-07T22:30:10 | 2021-07-07T22:30:10 | 383,933,318 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Book{
int bno;
String bname;
double price;
Book(int bno,String bname,double price){
this.bname = bname;
this.bno = bno;
this.price = price;
}
void display() {
System.out.println("Book Number: "+bno);
System.out.println("Book Name: "+bname);
System.out.println("Book Price: "+price);
}
}
class SpecialEditionBook extends Book{
int discount;
SpecialEditionBook(int bno,String bname,double price,int discount){
super(bno,bname,price);
this.discount = discount;
}
void display() {
super.display();
System.out.println("Discount: "+discount);
}
}
public class BookTest {
public static void main(String[] args) {
SpecialEditionBook b = new SpecialEditionBook(111,"sherlock",25.00,5);
b.display();
}
}
| UTF-8 | Java | 740 | java | BookTest.java | Java | [
{
"context": "pecialEditionBook b = new SpecialEditionBook(111,\"sherlock\",25.00,5);\n\t\tb.display();\n\t}\n\n}\n",
"end": 707,
"score": 0.9930456876754761,
"start": 699,
"tag": "NAME",
"value": "sherlock"
}
] | null | [] | class Book{
int bno;
String bname;
double price;
Book(int bno,String bname,double price){
this.bname = bname;
this.bno = bno;
this.price = price;
}
void display() {
System.out.println("Book Number: "+bno);
System.out.println("Book Name: "+bname);
System.out.println("Book Price: "+price);
}
}
class SpecialEditionBook extends Book{
int discount;
SpecialEditionBook(int bno,String bname,double price,int discount){
super(bno,bname,price);
this.discount = discount;
}
void display() {
super.display();
System.out.println("Discount: "+discount);
}
}
public class BookTest {
public static void main(String[] args) {
SpecialEditionBook b = new SpecialEditionBook(111,"sherlock",25.00,5);
b.display();
}
}
| 740 | 0.694595 | 0.683784 | 34 | 20.764706 | 18.967556 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.882353 | false | false | 13 |
b347580611c9a22ddb33d7cce738abc1782a59e6 | 34,729,105,616,210 | f18986b961084eebe49af6cbdd15fbb82239bf58 | /src/com/address/model/AddressDAO_interface.java | 11d2102c2f6e89c526993fc5fbb7bb5230f2cee3 | [] | no_license | CA105G1/SPORTGO | https://github.com/CA105G1/SPORTGO | f4879b7c97525a71fa2b138e7bb715ea406d22e1 | 04967c2e0e8f70a96e1c06aebb6ede43fd2fce28 | refs/heads/master | 2020-04-10T22:28:59.253000 | 2019-02-10T16:42:55 | 2019-02-10T16:42:55 | 161,317,157 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.address.model;
import java.util.List;
public interface AddressDAO_interface {
public void insert(AddressVO address);
public void delete(String addr_no);
public List<AddressVO> getByForeignKey(String mem_no);
public List<AddressVO> getAll();
}
| UTF-8 | Java | 261 | java | AddressDAO_interface.java | Java | [] | null | [] | package com.address.model;
import java.util.List;
public interface AddressDAO_interface {
public void insert(AddressVO address);
public void delete(String addr_no);
public List<AddressVO> getByForeignKey(String mem_no);
public List<AddressVO> getAll();
}
| 261 | 0.781609 | 0.781609 | 10 | 25.1 | 18.201374 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 13 |
2fee30f977b2c5da747bf8c077e0082c7e8c4bd9 | 35,184,372,141,277 | 48e835e6f176a8ac9ae3ca718e8922891f1e5a18 | /benchmark/training/org/hibernate/test/hql/joinedSubclass/JoinedSubclassBulkManipTest.java | 0f00f4fc99a2866c44a571e01d472858a603d757 | [] | no_license | STAMP-project/dspot-experiments | https://github.com/STAMP-project/dspot-experiments | f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5 | 121487e65cdce6988081b67f21bbc6731354a47f | refs/heads/master | 2023-02-07T14:40:12.919000 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | false | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | 2022-02-18T17:43:31 | 2023-01-26T23:57:40 | 651,434 | 12 | 14 | 5 | null | false | false | /**
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.hql.joinedSubclass;
import org.hibernate.Session;
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
/**
*
*
* @author Steve Ebersole
*/
@SkipForDialect(value = CUBRIDDialect.class, comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" + "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables")
public class JoinedSubclassBulkManipTest extends BaseCoreFunctionalTestCase {
@Test
@TestForIssue(jiraKey = "HHH-1657")
public void testHqlDeleteOnJoinedSubclass() {
Session s = openSession();
s.beginTransaction();
// syntax checking on the database...
s.createQuery("delete from Employee").executeUpdate();
s.createQuery("delete from Person").executeUpdate();
s.createQuery("delete from Employee e").executeUpdate();
s.createQuery("delete from Person p").executeUpdate();
s.createQuery("delete from Employee where name like 'S%'").executeUpdate();
s.createQuery("delete from Employee e where e.name like 'S%'").executeUpdate();
s.createQuery("delete from Person where name like 'S%'").executeUpdate();
s.createQuery("delete from Person p where p.name like 'S%'").executeUpdate();
// now the forms that actually fail from problem underlying HHH-1657
// which is limited to references to properties mapped to column names existing in both tables
// which is normally just the pks. super critical ;)
s.createQuery("delete from Employee where id = 1").executeUpdate();
s.createQuery("delete from Employee e where e.id = 1").executeUpdate();
s.createQuery("delete from Person where id = 1").executeUpdate();
s.createQuery("delete from Person p where p.id = 1").executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
@TestForIssue(jiraKey = "HHH-1657")
public void testHqlUpdateOnJoinedSubclass() {
Session s = openSession();
s.beginTransaction();
// syntax checking on the database...
s.createQuery("update Employee set name = 'Some Other Name' where employeeNumber like 'A%'").executeUpdate();
s.createQuery("update Employee e set e.name = 'Some Other Name' where e.employeeNumber like 'A%'").executeUpdate();
s.createQuery("update Person set name = 'Some Other Name' where name like 'S%'").executeUpdate();
s.createQuery("update Person p set p.name = 'Some Other Name' where p.name like 'S%'").executeUpdate();
// now the forms that actually fail from problem underlying HHH-1657
// which is limited to references to properties mapped to column names existing in both tables
// which is normally just the pks. super critical ;)
s.createQuery("update Employee set name = 'Some Other Name' where id = 1").executeUpdate();
s.createQuery("update Employee e set e.name = 'Some Other Name' where e.id = 1").executeUpdate();
s.createQuery("update Person set name = 'Some Other Name' where id = 1").executeUpdate();
s.createQuery("update Person p set p.name = 'Some Other Name' where p.id = 1").executeUpdate();
s.getTransaction().commit();
s.close();
}
}
| UTF-8 | Java | 3,718 | java | JoinedSubclassBulkManipTest.java | Java | [
{
"context": "ase;\nimport org.junit.Test;\n\n\n/**\n *\n *\n * @author Steve Ebersole\n */\n@SkipForDialect(value = CUBRIDDialect.class, ",
"end": 573,
"score": 0.9997687935829163,
"start": 559,
"tag": "NAME",
"value": "Steve Ebersole"
}
] | null | [] | /**
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.hql.joinedSubclass;
import org.hibernate.Session;
import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
/**
*
*
* @author <NAME>
*/
@SkipForDialect(value = CUBRIDDialect.class, comment = "As of verion 8.4.1 CUBRID doesn't support temporary tables. This test fails with" + "HibernateException: cannot doAfterTransactionCompletion multi-table deletes using dialect not supporting temp tables")
public class JoinedSubclassBulkManipTest extends BaseCoreFunctionalTestCase {
@Test
@TestForIssue(jiraKey = "HHH-1657")
public void testHqlDeleteOnJoinedSubclass() {
Session s = openSession();
s.beginTransaction();
// syntax checking on the database...
s.createQuery("delete from Employee").executeUpdate();
s.createQuery("delete from Person").executeUpdate();
s.createQuery("delete from Employee e").executeUpdate();
s.createQuery("delete from Person p").executeUpdate();
s.createQuery("delete from Employee where name like 'S%'").executeUpdate();
s.createQuery("delete from Employee e where e.name like 'S%'").executeUpdate();
s.createQuery("delete from Person where name like 'S%'").executeUpdate();
s.createQuery("delete from Person p where p.name like 'S%'").executeUpdate();
// now the forms that actually fail from problem underlying HHH-1657
// which is limited to references to properties mapped to column names existing in both tables
// which is normally just the pks. super critical ;)
s.createQuery("delete from Employee where id = 1").executeUpdate();
s.createQuery("delete from Employee e where e.id = 1").executeUpdate();
s.createQuery("delete from Person where id = 1").executeUpdate();
s.createQuery("delete from Person p where p.id = 1").executeUpdate();
s.getTransaction().commit();
s.close();
}
@Test
@TestForIssue(jiraKey = "HHH-1657")
public void testHqlUpdateOnJoinedSubclass() {
Session s = openSession();
s.beginTransaction();
// syntax checking on the database...
s.createQuery("update Employee set name = 'Some Other Name' where employeeNumber like 'A%'").executeUpdate();
s.createQuery("update Employee e set e.name = 'Some Other Name' where e.employeeNumber like 'A%'").executeUpdate();
s.createQuery("update Person set name = 'Some Other Name' where name like 'S%'").executeUpdate();
s.createQuery("update Person p set p.name = 'Some Other Name' where p.name like 'S%'").executeUpdate();
// now the forms that actually fail from problem underlying HHH-1657
// which is limited to references to properties mapped to column names existing in both tables
// which is normally just the pks. super critical ;)
s.createQuery("update Employee set name = 'Some Other Name' where id = 1").executeUpdate();
s.createQuery("update Employee e set e.name = 'Some Other Name' where e.id = 1").executeUpdate();
s.createQuery("update Person set name = 'Some Other Name' where id = 1").executeUpdate();
s.createQuery("update Person p set p.name = 'Some Other Name' where p.id = 1").executeUpdate();
s.getTransaction().commit();
s.close();
}
}
| 3,710 | 0.691232 | 0.682625 | 70 | 52.099998 | 43.592644 | 259 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
63b96d5aa292e724357ec9cd96247dfb8c90f113 | 24,446,953,882,571 | eedcd6eab369112d499e6c48fb6748970542a495 | /percolation/Percolation.java | 096908a7f30ced3d05a6ddd3b81f8384d2c5751e | [] | no_license | akaoss/algorithms | https://github.com/akaoss/algorithms | 050c1f876edbb0eae9ec6144c5231d1b0b1b41c2 | 0503bdfa0af6a5dfc1cbedac6a7c626631a0ab46 | refs/heads/master | 2019-03-12T19:49:20.439000 | 2015-05-04T10:47:12 | 2015-05-04T10:47:12 | 29,282,803 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Percolation {
private int n;
private WeightedQuickUnionUF perc;
private WeightedQuickUnionUF perc2;
private boolean[][] matrix;
private int virtualTop;
private int virtualBottom;
public Percolation(int N) {
n = N;
if (n <= 0) throw new IllegalArgumentException("Matrix size should be greater then 0");
matrix = new boolean[n+1][n+1];
perc = new WeightedQuickUnionUF(n*n+2); // +2 to store virtual top and bottom sites
perc2 = new WeightedQuickUnionUF(n*n+2);
virtualTop = 0;
virtualBottom = n*n + 1;
}
public void open(int i, int j) {
if (!isOpen(i, j)) {
matrix[i][j] = true;
int current = xyTo1D(i, j);
int left = xyTo1D(i, j-1);
int right = xyTo1D(i, j+1);
int top = xyTo1D(i-1, j);
int bottom = xyTo1D(i+1, j);
if (j-1 > 0 && isOpen(i, j-1) && !perc2.connected(current, left)) { perc.union(current, left); perc2.union(current, left); }
if (j+1 <= n && isOpen(i, j+1) && !perc2.connected(current, right)) { perc.union(current, right); perc2.union(current, right); }
if (i-1 > 0 && isOpen(i-1, j) && !perc2.connected(current, top)) { perc.union(current, top); perc2.union(current, top); }
if (i+1 <= n && isOpen(i+1, j) && !perc2.connected(current, bottom)){ perc.union(current, bottom); perc2.union(current, bottom); }
if (i == 1) { perc.union(current, virtualTop); perc2.union(current, virtualTop); }
if (i == n) { perc.union(current, virtualBottom); }
}
}
public boolean isOpen(int i, int j) {
checkIndices(i, j);
return matrix[i][j];
}
public boolean isFull(int i, int j) {
checkIndices(i, j);
return perc2.connected(xyTo1D(i, j), virtualTop);
}
public boolean percolates() {
return perc.connected(virtualTop, virtualBottom);
}
public static void main(String[] args) {
In in = new In(args[0]); // input file
int N = in.readInt(); // N-by-N percolation system
Percolation percTest = new Percolation(N);
while (!in.isEmpty()) {
int i = in.readInt();
int j = in.readInt();
percTest.open(i, j);
}
if (percTest.percolates()) StdOut.println("percolates");
else StdOut.println("does not percolate");
}
private void checkIndices(int i, int j) {
if (i <= 0 || i > n) throw new IndexOutOfBoundsException("row index " + i + " out of bounds");
if (j <= 0 || j > n) throw new IndexOutOfBoundsException("column index " + j + " out of bounds");
}
private int xyTo1D(int x, int y) {
int indent = 1; // indent to store virtual top site
return n*(x-1) + (y-1) + indent;
}
} | UTF-8 | Java | 2,982 | java | Percolation.java | Java | [] | null | [] | public class Percolation {
private int n;
private WeightedQuickUnionUF perc;
private WeightedQuickUnionUF perc2;
private boolean[][] matrix;
private int virtualTop;
private int virtualBottom;
public Percolation(int N) {
n = N;
if (n <= 0) throw new IllegalArgumentException("Matrix size should be greater then 0");
matrix = new boolean[n+1][n+1];
perc = new WeightedQuickUnionUF(n*n+2); // +2 to store virtual top and bottom sites
perc2 = new WeightedQuickUnionUF(n*n+2);
virtualTop = 0;
virtualBottom = n*n + 1;
}
public void open(int i, int j) {
if (!isOpen(i, j)) {
matrix[i][j] = true;
int current = xyTo1D(i, j);
int left = xyTo1D(i, j-1);
int right = xyTo1D(i, j+1);
int top = xyTo1D(i-1, j);
int bottom = xyTo1D(i+1, j);
if (j-1 > 0 && isOpen(i, j-1) && !perc2.connected(current, left)) { perc.union(current, left); perc2.union(current, left); }
if (j+1 <= n && isOpen(i, j+1) && !perc2.connected(current, right)) { perc.union(current, right); perc2.union(current, right); }
if (i-1 > 0 && isOpen(i-1, j) && !perc2.connected(current, top)) { perc.union(current, top); perc2.union(current, top); }
if (i+1 <= n && isOpen(i+1, j) && !perc2.connected(current, bottom)){ perc.union(current, bottom); perc2.union(current, bottom); }
if (i == 1) { perc.union(current, virtualTop); perc2.union(current, virtualTop); }
if (i == n) { perc.union(current, virtualBottom); }
}
}
public boolean isOpen(int i, int j) {
checkIndices(i, j);
return matrix[i][j];
}
public boolean isFull(int i, int j) {
checkIndices(i, j);
return perc2.connected(xyTo1D(i, j), virtualTop);
}
public boolean percolates() {
return perc.connected(virtualTop, virtualBottom);
}
public static void main(String[] args) {
In in = new In(args[0]); // input file
int N = in.readInt(); // N-by-N percolation system
Percolation percTest = new Percolation(N);
while (!in.isEmpty()) {
int i = in.readInt();
int j = in.readInt();
percTest.open(i, j);
}
if (percTest.percolates()) StdOut.println("percolates");
else StdOut.println("does not percolate");
}
private void checkIndices(int i, int j) {
if (i <= 0 || i > n) throw new IndexOutOfBoundsException("row index " + i + " out of bounds");
if (j <= 0 || j > n) throw new IndexOutOfBoundsException("column index " + j + " out of bounds");
}
private int xyTo1D(int x, int y) {
int indent = 1; // indent to store virtual top site
return n*(x-1) + (y-1) + indent;
}
} | 2,982 | 0.540577 | 0.524145 | 76 | 38.25 | 34.655495 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.144737 | false | false | 13 |
f0144a956d047fe54d75bf8e08601e13b1cd082d | 36,361,193,170,172 | 6edc1ca68545236ee71bfe6f63d016835323bfe3 | /app/src/main/java/com/wahidhidayat/newsapp/adapters/CategoryAdapter.java | 0d4ce2aed206d8d3ee70f3f63c3a4d280715334b | [] | no_license | wakhidhidayat/News-App | https://github.com/wakhidhidayat/News-App | 00ad6b5fd39d2241b63bc5f7bd6062f0c9c4f2bb | c30252d30c2d0c236d42a928b9eca975a6be6c4e | refs/heads/master | 2022-11-17T07:46:18.860000 | 2020-07-05T12:54:36 | 2020-07-05T12:54:36 | 272,995,155 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wahidhidayat.newsapp.adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.wahidhidayat.newsapp.R;
import com.wahidhidayat.newsapp.activities.DetailActivity;
import com.wahidhidayat.newsapp.models.Articles;
import com.wahidhidayat.newsapp.models.Favorite;
import org.ocpsoft.prettytime.PrettyTime;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
Context context;
List<Articles> articles;
DatabaseReference favReference;
FirebaseUser firebaseUser;
public CategoryAdapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category_activity, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
final Articles article = articles.get(position);
holder.tvTitle.setText(article.getTitle());
holder.tvSource.setText(article.getSource().getName());
holder.tvDate.setText("\u2022" + dateTime(article.getPublishedAt()));
holder.tvDesc.setText(article.getDescription());
String imageUrl = article.getUrlToImage();
holder.progressBar.setVisibility(View.VISIBLE);
Glide.with(context)
.load(imageUrl)
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.progressBar.setVisibility(View.GONE);
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.progressBar.setVisibility(View.GONE);
return false;
}
})
.into(holder.ivBanner);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
favReference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid()).child("favorites");
}
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (firebaseUser != null) {
favReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String id = "id";
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Favorite favorite = snapshot.getValue(Favorite.class);
assert favorite != null;
if (favorite.getUrl().equals(article.getUrl())) {
id = favorite.getId();
}
}
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("title", article.getTitle());
intent.putExtra("image", article.getUrlToImage());
intent.putExtra("date", article.getPublishedAt());
intent.putExtra("source", article.getSource().getName());
intent.putExtra("url", article.getUrl());
intent.putExtra("description", article.getDescription());
intent.putExtra("id", id);
context.startActivity(intent);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
} else {
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("title", article.getTitle());
intent.putExtra("image", article.getUrlToImage());
intent.putExtra("date", article.getPublishedAt());
intent.putExtra("source", article.getSource().getName());
intent.putExtra("url", article.getUrl());
intent.putExtra("description", article.getDescription());
intent.putExtra("id", "id");
context.startActivity(intent);
}
}
});
}
@Override
public int getItemCount() {
return articles.size();
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
public String dateTime(String t) {
PrettyTime prettyTime = new PrettyTime(new Locale(getCountry()));
String time = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:", Locale.ENGLISH);
Date date = simpleDateFormat.parse(t);
time = prettyTime.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return time;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate, tvDesc;
ImageView ivBanner;
CardView cardView;
ProgressBar progressBar;
public ViewHolder(@NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tv_title_category);
tvSource = itemView.findViewById(R.id.tv_source_category);
tvDate = itemView.findViewById(R.id.tv_date_category);
ivBanner = itemView.findViewById(R.id.iv_banner_category);
cardView = itemView.findViewById(R.id.card_view_category);
tvDesc = itemView.findViewById(R.id.tv_desc_category);
progressBar = itemView.findViewById(R.id.pb_category);
}
}
}
| UTF-8 | Java | 7,547 | java | CategoryAdapter.java | Java | [] | null | [] | package com.wahidhidayat.newsapp.adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.wahidhidayat.newsapp.R;
import com.wahidhidayat.newsapp.activities.DetailActivity;
import com.wahidhidayat.newsapp.models.Articles;
import com.wahidhidayat.newsapp.models.Favorite;
import org.ocpsoft.prettytime.PrettyTime;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
Context context;
List<Articles> articles;
DatabaseReference favReference;
FirebaseUser firebaseUser;
public CategoryAdapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category_activity, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
final Articles article = articles.get(position);
holder.tvTitle.setText(article.getTitle());
holder.tvSource.setText(article.getSource().getName());
holder.tvDate.setText("\u2022" + dateTime(article.getPublishedAt()));
holder.tvDesc.setText(article.getDescription());
String imageUrl = article.getUrlToImage();
holder.progressBar.setVisibility(View.VISIBLE);
Glide.with(context)
.load(imageUrl)
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.progressBar.setVisibility(View.GONE);
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.progressBar.setVisibility(View.GONE);
return false;
}
})
.into(holder.ivBanner);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
favReference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid()).child("favorites");
}
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (firebaseUser != null) {
favReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String id = "id";
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Favorite favorite = snapshot.getValue(Favorite.class);
assert favorite != null;
if (favorite.getUrl().equals(article.getUrl())) {
id = favorite.getId();
}
}
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("title", article.getTitle());
intent.putExtra("image", article.getUrlToImage());
intent.putExtra("date", article.getPublishedAt());
intent.putExtra("source", article.getSource().getName());
intent.putExtra("url", article.getUrl());
intent.putExtra("description", article.getDescription());
intent.putExtra("id", id);
context.startActivity(intent);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
} else {
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("title", article.getTitle());
intent.putExtra("image", article.getUrlToImage());
intent.putExtra("date", article.getPublishedAt());
intent.putExtra("source", article.getSource().getName());
intent.putExtra("url", article.getUrl());
intent.putExtra("description", article.getDescription());
intent.putExtra("id", "id");
context.startActivity(intent);
}
}
});
}
@Override
public int getItemCount() {
return articles.size();
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
public String dateTime(String t) {
PrettyTime prettyTime = new PrettyTime(new Locale(getCountry()));
String time = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:", Locale.ENGLISH);
Date date = simpleDateFormat.parse(t);
time = prettyTime.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return time;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate, tvDesc;
ImageView ivBanner;
CardView cardView;
ProgressBar progressBar;
public ViewHolder(@NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tv_title_category);
tvSource = itemView.findViewById(R.id.tv_source_category);
tvDate = itemView.findViewById(R.id.tv_date_category);
ivBanner = itemView.findViewById(R.id.iv_banner_category);
cardView = itemView.findViewById(R.id.card_view_category);
tvDesc = itemView.findViewById(R.id.tv_desc_category);
progressBar = itemView.findViewById(R.id.pb_category);
}
}
}
| 7,547 | 0.612296 | 0.611766 | 183 | 40.240437 | 29.630827 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.743169 | false | false | 13 |
3bc0ee75b3224550b82036c9f5450daf0af2f6bb | 35,407,710,432,713 | ca5b2cad8aeb18629226b520aedcde53547d481e | /src/logic/Rule.java | b140337a81eb1a5368dbc4b5a006c9d7051c0ff9 | [] | no_license | mokeddembillel/Multi-Agent-Seller | https://github.com/mokeddembillel/Multi-Agent-Seller | aac41e1a6764a61cc27d843849e3bda9b9f236a9 | 765d1bed83c9371a0b0a12ffb5462c1640d4770f | refs/heads/main | 2023-02-04T04:36:23.771000 | 2020-12-15T21:05:21 | 2020-12-15T21:05:21 | 315,458,549 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package logic;
import java.util.ArrayList;
public class Rule {
public BooleanRuleBase rb;
public String name;
public ArrayList<Clause> antecedents = new ArrayList<>();
public Clause consequent;
public Boolean truth;
public Boolean fired = false;
public Rule(BooleanRuleBase rb, String name, Clause lhs, Clause rhs) {
this.rb = rb;
this.name = name;
this.antecedents.add(lhs);
lhs.addRuleRef(this);
this.consequent = rhs;
rhs.addRuleRef(this);
rhs.setConsequent();
rb.ruleList.add(this);
truth = null;
}
public Rule(BooleanRuleBase rb, String name, ArrayList<Clause> lhsClauses, Clause rhs) {
this.rb = rb;
this.name = name;
for (Clause lhsClause : lhsClauses) {
lhsClause.addRuleRef(this);
antecedents.add(lhsClause);
}
consequent = rhs;
rhs.addRuleRef(this);
rhs.setConsequent();
rb.ruleList.add(this);
truth = null;
}
public Integer numAntecedents() {
return this.antecedents.size();
}
public Boolean check() {
//rb.trace("\nTesting rule " + name);
for (int i = 0; i < numAntecedents(); i++) {
if (antecedents.get(i).truth == null) {
return null;
}
if (antecedents.get(i).truth) {
continue;
} else {
truth = false;
return false;
}
}
truth = true;
return true;
}
public void fire() {
//rb.trace("\nFiring rule " + name);
truth = true;
fired = true;
if (consequent.lhs == null) {
//consequent.peform(rb);
} else {
consequent.lhs.setValue(consequent.rhs);
System.out.println("Firing Rule : " + this.name + " , result is => " + consequent.lhs.name + " = " + consequent.rhs);
checkRules(consequent.lhs.clauseRefs);
}
}
public static void checkRules(ArrayList<Clause> clauseRefs) {
for (Clause clauseRef : clauseRefs) {
ArrayList<Rule> tmpRules = clauseRef.ruleRefs;
for (Rule tmpRule : tmpRules) {
tmpRule.check();
}
}
}
}
| UTF-8 | Java | 2,307 | java | Rule.java | Java | [] | null | [] | package logic;
import java.util.ArrayList;
public class Rule {
public BooleanRuleBase rb;
public String name;
public ArrayList<Clause> antecedents = new ArrayList<>();
public Clause consequent;
public Boolean truth;
public Boolean fired = false;
public Rule(BooleanRuleBase rb, String name, Clause lhs, Clause rhs) {
this.rb = rb;
this.name = name;
this.antecedents.add(lhs);
lhs.addRuleRef(this);
this.consequent = rhs;
rhs.addRuleRef(this);
rhs.setConsequent();
rb.ruleList.add(this);
truth = null;
}
public Rule(BooleanRuleBase rb, String name, ArrayList<Clause> lhsClauses, Clause rhs) {
this.rb = rb;
this.name = name;
for (Clause lhsClause : lhsClauses) {
lhsClause.addRuleRef(this);
antecedents.add(lhsClause);
}
consequent = rhs;
rhs.addRuleRef(this);
rhs.setConsequent();
rb.ruleList.add(this);
truth = null;
}
public Integer numAntecedents() {
return this.antecedents.size();
}
public Boolean check() {
//rb.trace("\nTesting rule " + name);
for (int i = 0; i < numAntecedents(); i++) {
if (antecedents.get(i).truth == null) {
return null;
}
if (antecedents.get(i).truth) {
continue;
} else {
truth = false;
return false;
}
}
truth = true;
return true;
}
public void fire() {
//rb.trace("\nFiring rule " + name);
truth = true;
fired = true;
if (consequent.lhs == null) {
//consequent.peform(rb);
} else {
consequent.lhs.setValue(consequent.rhs);
System.out.println("Firing Rule : " + this.name + " , result is => " + consequent.lhs.name + " = " + consequent.rhs);
checkRules(consequent.lhs.clauseRefs);
}
}
public static void checkRules(ArrayList<Clause> clauseRefs) {
for (Clause clauseRef : clauseRefs) {
ArrayList<Rule> tmpRules = clauseRef.ruleRefs;
for (Rule tmpRule : tmpRules) {
tmpRule.check();
}
}
}
}
| 2,307 | 0.534894 | 0.53446 | 84 | 26.464285 | 21.719778 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false | 13 |
63698020187a5b7dae89ec09698ebd687cb0a245 | 4,028,679,384,887 | 73f9be6fa5b3a5ad165585cc1657ee60695aa0ed | /Spring/src/main/java/tests/hashmap/HashMapTest.java | 42c27a251c3f6f20d96908e3a5e26987132d45e6 | [
"Apache-2.0"
] | permissive | jiaoqiyuan/codeabbeyTests | https://github.com/jiaoqiyuan/codeabbeyTests | bc664b2a37319d7dd79f38948557cc2fbf202ef4 | e9811b8905d4b78adaff0de61d19b175cc109862 | refs/heads/master | 2022-12-24T13:15:37.755000 | 2022-04-06T05:45:49 | 2022-04-06T05:45:49 | 195,944,113 | 1 | 1 | Apache-2.0 | false | 2022-12-16T15:00:31 | 2019-07-09T06:13:03 | 2022-04-06T05:45:40 | 2022-12-16T15:00:23 | 379 | 0 | 0 | 41 | Java | false | false | package tests.hashmap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapTest {
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "Jony");
hashMap.put(2, "Bill");
//System.out.println(hashMap.get(1));
Iterator<Map.Entry<Integer, String>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}
Iterator<Integer> iterator1 = hashMap.keySet().iterator();
while (iterator1.hasNext()) {
Object key = iterator1.next();
System.out.println("key: " + key.toString() + " value: " + hashMap.get(key));
}
}
} | UTF-8 | Java | 901 | java | HashMapTest.java | Java | [
{
"context": "shMap<Integer, String>();\n hashMap.put(1, \"Jony\");\n hashMap.put(2, \"Bill\");\n //Syst",
"end": 275,
"score": 0.9994529485702515,
"start": 271,
"tag": "NAME",
"value": "Jony"
},
{
"context": " hashMap.put(1, \"Jony\");\n hashMap.put(2, \"Bill\");\n //System.out.println(hashMap.get(1));\n",
"end": 307,
"score": 0.9998627305030823,
"start": 303,
"tag": "NAME",
"value": "Bill"
}
] | null | [] | package tests.hashmap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapTest {
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "Jony");
hashMap.put(2, "Bill");
//System.out.println(hashMap.get(1));
Iterator<Map.Entry<Integer, String>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}
Iterator<Integer> iterator1 = hashMap.keySet().iterator();
while (iterator1.hasNext()) {
Object key = iterator1.next();
System.out.println("key: " + key.toString() + " value: " + hashMap.get(key));
}
}
} | 901 | 0.599334 | 0.592675 | 25 | 35.080002 | 28.054119 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 13 |
651c736aca54b22fb2146a124c595f1994f11844 | 10,582,799,471,409 | ab5f81ee84700c417faa88d4944cf7b5466907ca | /src/corpustools/Defined.java | 22bafa5e84b9eb6f6e34de0bd62dc2f19f97919e | [] | no_license | pombredanne/yutta | https://github.com/pombredanne/yutta | cd8cccf267c910f4e2eb8d571f6e109a7e1a44ca | 841a641e0744e086b9b1527afd0e9c7970080ff0 | refs/heads/master | 2018-01-10T19:56:37.929000 | 2011-03-08T17:27:04 | 2011-03-08T17:27:04 | 47,922,947 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package corpustools;
import swutils.BinaryIn;
import swutils.BinaryOut;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
/**
* Simple test program to print out all utf-8 sequences.
*/
public class Defined {
/** Utility class. No construction needed or allowed. */
private Defined() { }
/**
* Breaks a character into multiple bytes and prints out the byte sequence.
* @param cp the code point to print
*/
public static void printTheHardWay(int cp) {
char[] c = Character.toChars(cp);
String cStr = new String(c);
BinaryIn in = null;
try {
in = new BinaryIn(new ByteArrayInputStream(cStr.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
System.out.println(e);
}
StringBuilder sb = new StringBuilder();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOut out = new BinaryOut(baos);
while (!in.isEmpty()) {
byte b = in.readByte();
sb.append(String.format("%x ", b));
out.write(b);
}
out.flush();
String bstr = baos.toString();
System.out.print(bstr);
}
/** Max code point for Unicode. */
private static final int UNICODEMAX = 0x10FFFF;
/**
* Print out all of Unicode.
* @param args unused
*/
public static void main(String[] args) {
int counter = 0;
String block = "";
for (int i = 0; i < UNICODEMAX; i++) {
printTheHardWay(i);
System.out.print(" ");
final int LineLength = 16;
if (++counter == LineLength) {
counter = 0;
Character.UnicodeBlock b = Character.UnicodeBlock.of(i + 1);
String newBlock = "";
if (b == null) {
newBlock = "null";
} else {
newBlock = b.toString();
}
if (newBlock.equals(block)) {
printTheHardWay((int) '\n');
continue;
}
final int NL = 0x0A;
printTheHardWay(NL);
printTheHardWay(NL);
int j = 0;
while (j < newBlock.length()) {
printTheHardWay((int) newBlock.charAt(j));
j++;
}
String cStr = new String(Character.toChars(i + 1));
String byteSeqLength = "";
try {
byteSeqLength =
" "
+ cStr.getBytes("UTF-8").length
+ " bytes\n";
} catch (UnsupportedEncodingException e) {
System.out.println(e);
}
j = 0;
while (j < byteSeqLength.length()) {
printTheHardWay((int) byteSeqLength.charAt(j));
j++;
}
block = newBlock;
}
}
}
}
| UTF-8 | Java | 3,133 | java | Defined.java | Java | [] | null | [] | package corpustools;
import swutils.BinaryIn;
import swutils.BinaryOut;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
/**
* Simple test program to print out all utf-8 sequences.
*/
public class Defined {
/** Utility class. No construction needed or allowed. */
private Defined() { }
/**
* Breaks a character into multiple bytes and prints out the byte sequence.
* @param cp the code point to print
*/
public static void printTheHardWay(int cp) {
char[] c = Character.toChars(cp);
String cStr = new String(c);
BinaryIn in = null;
try {
in = new BinaryIn(new ByteArrayInputStream(cStr.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
System.out.println(e);
}
StringBuilder sb = new StringBuilder();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOut out = new BinaryOut(baos);
while (!in.isEmpty()) {
byte b = in.readByte();
sb.append(String.format("%x ", b));
out.write(b);
}
out.flush();
String bstr = baos.toString();
System.out.print(bstr);
}
/** Max code point for Unicode. */
private static final int UNICODEMAX = 0x10FFFF;
/**
* Print out all of Unicode.
* @param args unused
*/
public static void main(String[] args) {
int counter = 0;
String block = "";
for (int i = 0; i < UNICODEMAX; i++) {
printTheHardWay(i);
System.out.print(" ");
final int LineLength = 16;
if (++counter == LineLength) {
counter = 0;
Character.UnicodeBlock b = Character.UnicodeBlock.of(i + 1);
String newBlock = "";
if (b == null) {
newBlock = "null";
} else {
newBlock = b.toString();
}
if (newBlock.equals(block)) {
printTheHardWay((int) '\n');
continue;
}
final int NL = 0x0A;
printTheHardWay(NL);
printTheHardWay(NL);
int j = 0;
while (j < newBlock.length()) {
printTheHardWay((int) newBlock.charAt(j));
j++;
}
String cStr = new String(Character.toChars(i + 1));
String byteSeqLength = "";
try {
byteSeqLength =
" "
+ cStr.getBytes("UTF-8").length
+ " bytes\n";
} catch (UnsupportedEncodingException e) {
System.out.println(e);
}
j = 0;
while (j < byteSeqLength.length()) {
printTheHardWay((int) byteSeqLength.charAt(j));
j++;
}
block = newBlock;
}
}
}
}
| 3,133 | 0.483243 | 0.477817 | 102 | 29.715687 | 19.6735 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490196 | false | false | 13 |
1ffff96dca67a6015a0af777462fe4e5d478c247 | 4,191,888,098,873 | ba29179f41fdf2884f8894e1c5484a11480ae9d8 | /src/main/java/com/example/springAuthenticationJWT/Controllers/SeasonController.java | 403d9175550a1be8839f1023e7cc9d5e967f2b25 | [] | no_license | Abilda/Final_HotelChain | https://github.com/Abilda/Final_HotelChain | b994189d1e76933dd50cb6b4200aff4ace7ea223 | 1af90381bd44a5df3b8e81235e1bdef6b2caca96 | refs/heads/master | 2023-01-14T00:01:52.652000 | 2020-11-13T18:15:29 | 2020-11-13T18:15:29 | 312,241,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.springAuthenticationJWT.Controllers;
import com.example.springAuthenticationJWT.models.*;
import com.example.springAuthenticationJWT.payload.response.MessageResponse;
import com.example.springAuthenticationJWT.repository.HotelRepository;
import com.example.springAuthenticationJWT.repository.SeasonRepository;
import com.example.springAuthenticationJWT.repository.UserRepository;
import com.example.springAuthenticationJWT.security.jwt.JwtUtils;
import org.apache.coyote.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import javax.websocket.server.PathParam;
import java.util.*;
@RestController
@CrossOrigin
@RequestMapping("/api/season/")
public class SeasonController {
@Autowired
HotelRepository hotelRepository;
@Autowired
SeasonRepository seasonRepository;
@Autowired
UserRepository userRepository;
@Autowired
JwtUtils jwtUtils;
@GetMapping("/getSeasons")
public ResponseEntity<?> get() {
// System.out.print("Inside getSeasons");
HashMap<String, Set<String>> season_hotels = new HashMap<>();
List<Season> allSeasons = seasonRepository.findAll();
for (Season season : allSeasons)
if (season.getHotels().size() > 0) {
String seasonInfo = "From " + season.getStartDate() + " to " + season.getEndDate() + ", discount rate - " + season.getSeasonalRate();
Set<String> hotelsInfo = new HashSet<>();
Set<Hotel> hotels = season.getHotels();
for (Hotel hotel : hotels)
hotelsInfo.add(hotel.getName() + ", at city " + hotel.getCity());
season_hotels.put(seasonInfo, hotelsInfo);
}
return ResponseEntity.ok(season_hotels);
}
@PostMapping("/create")
public ResponseEntity<?> create(@RequestHeader("authorization") String authHeader,
@RequestBody Season season) {
String jwt = authHeader.substring(7, authHeader.length());
boolean isValidJWT = jwtUtils.validateJwtToken(jwt);
Optional<User> user = userRepository.findByUsername(jwtUtils.getUserNameFromJwtToken(jwt));
boolean isAdmin = false;
for (Role role : user.get().getRoles())
if (role.getName() == ERole.ROLE_ADMIN) {
isAdmin = true;
break;
}
if (!isValidJWT || !isAdmin) {
return ResponseEntity.ok("You are not authorized to access Admin's area");
}
Season createdseason = new Season(season.getStartDate(), season.getEndDate(), season.getSeasonalRate());
seasonRepository.save(createdseason);
System.out.print(createdseason.getId());
return ResponseEntity.ok(new MessageResponse("succesfully created"));
}
@PostMapping("/addSeasonToHotel")
public ResponseEntity<?> add(@RequestHeader("authorization") String authHeader,
@PathParam("hotelId") Long hotelId, @PathParam("seasonId") Long seasonId) {
String jwt = authHeader.substring(7, authHeader.length());
boolean isValidJWT = jwtUtils.validateJwtToken(jwt);
Optional<User> user = userRepository.findByUsername(jwtUtils.getUserNameFromJwtToken(jwt));
boolean isAdmin = false;
for (Role role : user.get().getRoles())
if (role.getName() == ERole.ROLE_ADMIN) {
isAdmin = true;
break;
}
if (!isValidJWT || !isAdmin) {
return ResponseEntity.ok("You are not authorized to access Admin's area");
}
Optional<Season> season = seasonRepository.findById(seasonId);
Optional<Hotel> hotel = hotelRepository.findById(hotelId);
season.get().addHotel(hotel.get());
seasonRepository.save(season.get());
return ResponseEntity.ok(new MessageResponse("Hotel was added to season"));
}
@PostMapping("/cancel")
public ResponseEntity<?> Delete(@RequestHeader("authorization") String authHeader,
@RequestBody Object obj) {
Long id = ((LinkedHashMap<String, Integer>)obj).get("seasonId").longValue();
Optional<Season> season = seasonRepository.findById(id);
season.get().clearHotels();
seasonRepository.save(season.get());
return ResponseEntity.ok(new MessageResponse("The season was successfully canceled"));
}
@GetMapping("/getadvisory")
public ResponseEntity<?> getadvisory() {
ArrayList<Season> activeSeasons = getCurrentSeasons();
if (activeSeasons.size() == 0)
return ResponseEntity.ok(new MessageResponse("Currently there is no any seasonal discounts." +
"However, we surely will have one soon. Stay tuned :)"));
Season bestOffer = new Season();
Double bestDiscount = 0.0;
for (Season season : activeSeasons)
if (season.getSeasonalRate() > bestDiscount) {
bestDiscount = season.getSeasonalRate();
bestOffer = season;
}
Set<Hotel> hotels = bestOffer.getHotels();
StringBuilder discountHotels = new StringBuilder("");
int num = 1;
for (Hotel hotel : hotels) {
discountHotels.append(hotel.getName() + " - " + hotel.getCity() + " city");
if (num != hotels.size())
discountHotels.append(", ");
num++;
}
String advisory = "There is currently a " + bestDiscount + " % discount for rooms at " +
discountHotels.toString();
return ResponseEntity.ok(new MessageResponse(advisory));
}
private ArrayList<Season> getCurrentSeasons() {
Date currentDate = new Date();
List<Season> allSeasons = seasonRepository.findAll();
ArrayList<Season> activeSeasons = new ArrayList<>();
for (Season season : allSeasons)
if (currentDate.compareTo(season.getStartDate()) >= 0 &&
season.getEndDate().compareTo(currentDate) >= 0)
activeSeasons.add(season);
return activeSeasons;
}
}
| UTF-8 | Java | 6,411 | java | SeasonController.java | Java | [] | null | [] | package com.example.springAuthenticationJWT.Controllers;
import com.example.springAuthenticationJWT.models.*;
import com.example.springAuthenticationJWT.payload.response.MessageResponse;
import com.example.springAuthenticationJWT.repository.HotelRepository;
import com.example.springAuthenticationJWT.repository.SeasonRepository;
import com.example.springAuthenticationJWT.repository.UserRepository;
import com.example.springAuthenticationJWT.security.jwt.JwtUtils;
import org.apache.coyote.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import javax.websocket.server.PathParam;
import java.util.*;
@RestController
@CrossOrigin
@RequestMapping("/api/season/")
public class SeasonController {
@Autowired
HotelRepository hotelRepository;
@Autowired
SeasonRepository seasonRepository;
@Autowired
UserRepository userRepository;
@Autowired
JwtUtils jwtUtils;
@GetMapping("/getSeasons")
public ResponseEntity<?> get() {
// System.out.print("Inside getSeasons");
HashMap<String, Set<String>> season_hotels = new HashMap<>();
List<Season> allSeasons = seasonRepository.findAll();
for (Season season : allSeasons)
if (season.getHotels().size() > 0) {
String seasonInfo = "From " + season.getStartDate() + " to " + season.getEndDate() + ", discount rate - " + season.getSeasonalRate();
Set<String> hotelsInfo = new HashSet<>();
Set<Hotel> hotels = season.getHotels();
for (Hotel hotel : hotels)
hotelsInfo.add(hotel.getName() + ", at city " + hotel.getCity());
season_hotels.put(seasonInfo, hotelsInfo);
}
return ResponseEntity.ok(season_hotels);
}
@PostMapping("/create")
public ResponseEntity<?> create(@RequestHeader("authorization") String authHeader,
@RequestBody Season season) {
String jwt = authHeader.substring(7, authHeader.length());
boolean isValidJWT = jwtUtils.validateJwtToken(jwt);
Optional<User> user = userRepository.findByUsername(jwtUtils.getUserNameFromJwtToken(jwt));
boolean isAdmin = false;
for (Role role : user.get().getRoles())
if (role.getName() == ERole.ROLE_ADMIN) {
isAdmin = true;
break;
}
if (!isValidJWT || !isAdmin) {
return ResponseEntity.ok("You are not authorized to access Admin's area");
}
Season createdseason = new Season(season.getStartDate(), season.getEndDate(), season.getSeasonalRate());
seasonRepository.save(createdseason);
System.out.print(createdseason.getId());
return ResponseEntity.ok(new MessageResponse("succesfully created"));
}
@PostMapping("/addSeasonToHotel")
public ResponseEntity<?> add(@RequestHeader("authorization") String authHeader,
@PathParam("hotelId") Long hotelId, @PathParam("seasonId") Long seasonId) {
String jwt = authHeader.substring(7, authHeader.length());
boolean isValidJWT = jwtUtils.validateJwtToken(jwt);
Optional<User> user = userRepository.findByUsername(jwtUtils.getUserNameFromJwtToken(jwt));
boolean isAdmin = false;
for (Role role : user.get().getRoles())
if (role.getName() == ERole.ROLE_ADMIN) {
isAdmin = true;
break;
}
if (!isValidJWT || !isAdmin) {
return ResponseEntity.ok("You are not authorized to access Admin's area");
}
Optional<Season> season = seasonRepository.findById(seasonId);
Optional<Hotel> hotel = hotelRepository.findById(hotelId);
season.get().addHotel(hotel.get());
seasonRepository.save(season.get());
return ResponseEntity.ok(new MessageResponse("Hotel was added to season"));
}
@PostMapping("/cancel")
public ResponseEntity<?> Delete(@RequestHeader("authorization") String authHeader,
@RequestBody Object obj) {
Long id = ((LinkedHashMap<String, Integer>)obj).get("seasonId").longValue();
Optional<Season> season = seasonRepository.findById(id);
season.get().clearHotels();
seasonRepository.save(season.get());
return ResponseEntity.ok(new MessageResponse("The season was successfully canceled"));
}
@GetMapping("/getadvisory")
public ResponseEntity<?> getadvisory() {
ArrayList<Season> activeSeasons = getCurrentSeasons();
if (activeSeasons.size() == 0)
return ResponseEntity.ok(new MessageResponse("Currently there is no any seasonal discounts." +
"However, we surely will have one soon. Stay tuned :)"));
Season bestOffer = new Season();
Double bestDiscount = 0.0;
for (Season season : activeSeasons)
if (season.getSeasonalRate() > bestDiscount) {
bestDiscount = season.getSeasonalRate();
bestOffer = season;
}
Set<Hotel> hotels = bestOffer.getHotels();
StringBuilder discountHotels = new StringBuilder("");
int num = 1;
for (Hotel hotel : hotels) {
discountHotels.append(hotel.getName() + " - " + hotel.getCity() + " city");
if (num != hotels.size())
discountHotels.append(", ");
num++;
}
String advisory = "There is currently a " + bestDiscount + " % discount for rooms at " +
discountHotels.toString();
return ResponseEntity.ok(new MessageResponse(advisory));
}
private ArrayList<Season> getCurrentSeasons() {
Date currentDate = new Date();
List<Season> allSeasons = seasonRepository.findAll();
ArrayList<Season> activeSeasons = new ArrayList<>();
for (Season season : allSeasons)
if (currentDate.compareTo(season.getStartDate()) >= 0 &&
season.getEndDate().compareTo(currentDate) >= 0)
activeSeasons.add(season);
return activeSeasons;
}
}
| 6,411 | 0.645141 | 0.643737 | 143 | 43.832169 | 29.401247 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657343 | false | false | 13 |
d12fd778d0c455e62e10d776fc8cd4d90d0a40e1 | 26,010,321,983,033 | 2f851be67ad219dff5e7d23fe9bc37151bbbf6bd | /P03/credhub/app/src/main/java/com/gonzalezolmedo/credhub/repository/RetrieveCredentialListTask.java | 2c45dfb607e6306131dfafc2cfc482e487adffdf | [] | no_license | olmedocr-university/mobile-security | https://github.com/olmedocr-university/mobile-security | d6981f896df22e75991190c66ace729835615d71 | e989d7bb10cbe8086f8e9f1a06e8b488580b63c2 | refs/heads/master | 2022-04-14T02:16:17.795000 | 2020-03-31T17:31:53 | 2020-03-31T17:31:53 | 241,073,020 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gonzalezolmedo.credhub.repository;
import android.os.AsyncTask;
import android.util.Log;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class RetrieveCredentialListTask extends AsyncTask<Void, Void, List<String>> {
private final String TAG = "RetrieveCredentialListTask";
private static HttpTransportSE androidHttpTransport;
private static List<HeaderProperty> headerList_basicAuth;
private static final String WS_NAMESPACE = "http://sdm_webrepo/";
private static final String WS_METHOD_LIST = "ListCredentials";
@Override
protected List<String> doInBackground(Void... voids) {
List<String> remoteCredentials = new ArrayList<>();
try {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0]; }
@Override public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) { }
@Override public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) { }
}
};
HttpsURLConnection.setDefaultHostnameVerifier ((hostname, session) -> true);
// Initialize TLS context
SSLContext sc = null;
try {
sc = SSLContext.getInstance("TLSv1.2");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
sc.init(null, trustAllCerts, new java.security.SecureRandom()); // *Set 2nd argument to NULL for default trust managers
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Set HTTPS URL
androidHttpTransport = new HttpTransportSE("https://10.0.2.2/SDM/WebRepo?wsdl");
headerList_basicAuth = new ArrayList<HeaderProperty>();
SingletonCredential credentials = SingletonCredential.getInstance();
String strUserPass = credentials.username + ":" + credentials.password;
headerList_basicAuth.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode(strUserPass.getBytes())));
SoapObject request = new SoapObject(WS_NAMESPACE, WS_METHOD_LIST);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
androidHttpTransport.call("\"" + WS_NAMESPACE + WS_METHOD_LIST + "\"", envelope, headerList_basicAuth);
Vector<SoapPrimitive> listIds = new Vector<>();
if (envelope.getResponse() instanceof Vector) {
listIds.addAll((Vector<SoapPrimitive>) envelope.getResponse());
} else if (envelope.getResponse() instanceof SoapPrimitive) {
listIds.add((SoapPrimitive) envelope.getResponse());
}
Log.i(TAG, "doInBackground: got credential list from server");
for (int i = 0; i < listIds.size(); i++) {
remoteCredentials.add(listIds.get(i).toString());
}
return remoteCredentials;
} catch (Exception ex) {
Log.e(TAG, "doInBackground: error while making http request to repo", ex);
}
return null;
}
}
| UTF-8 | Java | 4,204 | java | RetrieveCredentialListTask.java | Java | [
{
"context": "package com.gonzalezolmedo.credhub.repository;\n\nimport android.os.AsyncTask;",
"end": 26,
"score": 0.9666044116020203,
"start": 12,
"tag": "USERNAME",
"value": "gonzalezolmedo"
},
{
"context": "oidHttpTransport = new HttpTransportSE(\"https://10.0.2.2/SDM/WebRepo?wsdl\");\n\n headerList_",
"end": 2682,
"score": 0.5228963494300842,
"start": 2682,
"tag": "IP_ADDRESS",
"value": ""
},
{
"context": "dHttpTransport = new HttpTransportSE(\"https://10.0.2.2/SDM/WebRepo?wsdl\");\n\n headerList_basic",
"end": 2688,
"score": 0.6079542636871338,
"start": 2685,
"tag": "IP_ADDRESS",
"value": "2.2"
}
] | null | [] | package com.gonzalezolmedo.credhub.repository;
import android.os.AsyncTask;
import android.util.Log;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class RetrieveCredentialListTask extends AsyncTask<Void, Void, List<String>> {
private final String TAG = "RetrieveCredentialListTask";
private static HttpTransportSE androidHttpTransport;
private static List<HeaderProperty> headerList_basicAuth;
private static final String WS_NAMESPACE = "http://sdm_webrepo/";
private static final String WS_METHOD_LIST = "ListCredentials";
@Override
protected List<String> doInBackground(Void... voids) {
List<String> remoteCredentials = new ArrayList<>();
try {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0]; }
@Override public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) { }
@Override public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) { }
}
};
HttpsURLConnection.setDefaultHostnameVerifier ((hostname, session) -> true);
// Initialize TLS context
SSLContext sc = null;
try {
sc = SSLContext.getInstance("TLSv1.2");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
sc.init(null, trustAllCerts, new java.security.SecureRandom()); // *Set 2nd argument to NULL for default trust managers
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Set HTTPS URL
androidHttpTransport = new HttpTransportSE("https://10.0.2.2/SDM/WebRepo?wsdl");
headerList_basicAuth = new ArrayList<HeaderProperty>();
SingletonCredential credentials = SingletonCredential.getInstance();
String strUserPass = credentials.username + ":" + credentials.password;
headerList_basicAuth.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode(strUserPass.getBytes())));
SoapObject request = new SoapObject(WS_NAMESPACE, WS_METHOD_LIST);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
androidHttpTransport.call("\"" + WS_NAMESPACE + WS_METHOD_LIST + "\"", envelope, headerList_basicAuth);
Vector<SoapPrimitive> listIds = new Vector<>();
if (envelope.getResponse() instanceof Vector) {
listIds.addAll((Vector<SoapPrimitive>) envelope.getResponse());
} else if (envelope.getResponse() instanceof SoapPrimitive) {
listIds.add((SoapPrimitive) envelope.getResponse());
}
Log.i(TAG, "doInBackground: got credential list from server");
for (int i = 0; i < listIds.size(); i++) {
remoteCredentials.add(listIds.get(i).toString());
}
return remoteCredentials;
} catch (Exception ex) {
Log.e(TAG, "doInBackground: error while making http request to repo", ex);
}
return null;
}
}
| 4,204 | 0.648192 | 0.637964 | 95 | 43.252632 | 32.949394 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705263 | false | false | 13 |
b6c935b8165471099842e93af5d2abf6779a66e7 | 4,045,859,233,006 | 6eeba5ee421416a8424f0a3948e6cf98855b7730 | /projects/bingdou-core/src/main/java/com/bingdou/core/repository/user/UserStatisticsDao.java | a172cf9b09a6861b3d403f567a5e06d1c97d22d5 | [] | no_license | magichill/sdk | https://github.com/magichill/sdk | 3cba634ca8c3f49f4174d211e39103366da87c46 | 509bf60e2a1ee73f261bb77045c619be1a84d372 | refs/heads/master | 2020-06-23T12:38:48.938000 | 2017-06-28T05:13:54 | 2017-06-28T05:13:54 | 74,646,508 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bingdou.core.repository.user;
import com.bingdou.core.mapper.user.IUserStatisticsMapper;
import com.bingdou.core.model.UserSourceReport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public class UserStatisticsDao {
@Autowired
private IUserStatisticsMapper userStatisticsMapper;
public int getUserActiveRecordCount(int userId, int applicationId, String date) {
return userStatisticsMapper.getUserActiveRecordCount(userId, applicationId, date);
}
public Map<String, Object> getUserActiveRecord(int userId, int applicationId, String date) {
return userStatisticsMapper.getUserActiveRecord(userId, applicationId, date);
}
public int getUserActiveCountByAid(int applicationId) {
return userStatisticsMapper.getUserActiveCountByAid(applicationId);
}
public int isNewUserActiveRecord(int userId, int applicationId, String date) {
Integer result = userStatisticsMapper.isNewUserActiveRecord(userId, applicationId, date);
if (result == null)
return 0;
return result;
}
public int getUserRegister4AppRecordCount(int userId, int applicationId) {
return userStatisticsMapper.getUserRegister4AppRecordCount(userId, applicationId);
}
public void insertUserRegister4AppRecord(int userId, int applicationId,
int appMemberId, long addTime) {
userStatisticsMapper.insertUserRegister4AppRecord(userId, applicationId,
appMemberId, addTime);
}
public void insertUserActiveRecord(int userId, int applicationId,
int appMemberId, int payMoney,
int isNewMember, int isActiveMember,
int isAgainMember, String reportDate) {
userStatisticsMapper.insertUserActiveRecord(userId, applicationId, appMemberId,
payMoney, isNewMember, isActiveMember, isAgainMember, reportDate);
}
public int getUserSourceReportCount(int applicationId, int userId, String deviceStr, String reportDate) {
return userStatisticsMapper.getUserSourceReportCount(applicationId, userId, deviceStr, reportDate);
}
public void insertUserSourceReport(UserSourceReport userSourceReport) {
userStatisticsMapper.insertUserSourceReport(userSourceReport);
}
public int updateUserActiveMoney(int id, int moneyFen) {
return userStatisticsMapper.updateUserActiveMoney(id, moneyFen);
}
}
| UTF-8 | Java | 2,636 | java | UserStatisticsDao.java | Java | [] | null | [] | package com.bingdou.core.repository.user;
import com.bingdou.core.mapper.user.IUserStatisticsMapper;
import com.bingdou.core.model.UserSourceReport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public class UserStatisticsDao {
@Autowired
private IUserStatisticsMapper userStatisticsMapper;
public int getUserActiveRecordCount(int userId, int applicationId, String date) {
return userStatisticsMapper.getUserActiveRecordCount(userId, applicationId, date);
}
public Map<String, Object> getUserActiveRecord(int userId, int applicationId, String date) {
return userStatisticsMapper.getUserActiveRecord(userId, applicationId, date);
}
public int getUserActiveCountByAid(int applicationId) {
return userStatisticsMapper.getUserActiveCountByAid(applicationId);
}
public int isNewUserActiveRecord(int userId, int applicationId, String date) {
Integer result = userStatisticsMapper.isNewUserActiveRecord(userId, applicationId, date);
if (result == null)
return 0;
return result;
}
public int getUserRegister4AppRecordCount(int userId, int applicationId) {
return userStatisticsMapper.getUserRegister4AppRecordCount(userId, applicationId);
}
public void insertUserRegister4AppRecord(int userId, int applicationId,
int appMemberId, long addTime) {
userStatisticsMapper.insertUserRegister4AppRecord(userId, applicationId,
appMemberId, addTime);
}
public void insertUserActiveRecord(int userId, int applicationId,
int appMemberId, int payMoney,
int isNewMember, int isActiveMember,
int isAgainMember, String reportDate) {
userStatisticsMapper.insertUserActiveRecord(userId, applicationId, appMemberId,
payMoney, isNewMember, isActiveMember, isAgainMember, reportDate);
}
public int getUserSourceReportCount(int applicationId, int userId, String deviceStr, String reportDate) {
return userStatisticsMapper.getUserSourceReportCount(applicationId, userId, deviceStr, reportDate);
}
public void insertUserSourceReport(UserSourceReport userSourceReport) {
userStatisticsMapper.insertUserSourceReport(userSourceReport);
}
public int updateUserActiveMoney(int id, int moneyFen) {
return userStatisticsMapper.updateUserActiveMoney(id, moneyFen);
}
}
| 2,636 | 0.717754 | 0.715857 | 65 | 39.553844 | 36.641308 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.953846 | false | false | 13 |
1cd1635ae1b00a35da5d1f2e934932495fe33f3e | 20,435,454,451,259 | 3cc21bf61b46481ebf1b94f26f49eb5889f774ce | /test/com/jpozarycki/utils/entity/Message.java | d4aeaa848cb9ea4b631949c7f593cb7da28e3143 | [] | no_license | jpozarycki/play-hibernate-util | https://github.com/jpozarycki/play-hibernate-util | 3fad2ba5831df92cbfee0d4e2c2dabe0fc2d3a0d | 02c5ad9aeb02f4e30eecb7c698b0f9779d683194 | refs/heads/main | 2023-01-03T01:35:19.227000 | 2020-10-25T17:48:33 | 2020-10-25T17:48:33 | 307,079,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jpozarycki.utils.entity;
import javax.persistence.*;
@Entity
@Table(name = "messages")
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "text")
private String text;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
private User author;
public Message() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
}
| UTF-8 | Java | 778 | java | Message.java | Java | [] | null | [] | package com.jpozarycki.utils.entity;
import javax.persistence.*;
@Entity
@Table(name = "messages")
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "text")
private String text;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
private User author;
public Message() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
}
| 778 | 0.589974 | 0.589974 | 46 | 15.913043 | 14.488115 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.23913 | false | false | 13 |
d0717c1cd5a43e36e5d5c49c63fb7ffc9b3bbb31 | 1,692,217,132,755 | b86b6cfefb29612b45fe0df6a903517bbea9262e | /src/main/java/com/mabaya/sponsored/SponsoredApplication.java | 18a19a472ff7f344342ed0ba14877576ed6bd861 | [] | no_license | rantsur/SponsoredAds | https://github.com/rantsur/SponsoredAds | c21486ca1fd7820da24b800e581fc8c77f187f36 | 5ded7dd697d41ad37a000c8be16031923b864049 | refs/heads/master | 2022-10-27T03:32:12.863000 | 2020-06-11T12:23:34 | 2020-06-11T12:23:34 | 270,724,739 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mabaya.sponsored;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SponsoredApplication
{
public static void main(String[] args)
{
SpringApplication.run(SponsoredApplication.class, args);
}
}
| UTF-8 | Java | 320 | java | SponsoredApplication.java | Java | [] | null | [] | package com.mabaya.sponsored;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SponsoredApplication
{
public static void main(String[] args)
{
SpringApplication.run(SponsoredApplication.class, args);
}
}
| 320 | 0.821875 | 0.821875 | 15 | 20.333334 | 23.425531 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 13 |
bd2647379b73159c06fc013c8de8083eec8a7a14 | 32,478,542,761,551 | 65239a206fe5c38d8e2f57328ebde1384b30a2e6 | /src/main/java/schoolManagment/SchoolManagment/ImplementCourseList.java | 39caea01b78d90750d4617c51de10d896dc82613 | [] | no_license | anashlal/schoolmanagment | https://github.com/anashlal/schoolmanagment | 0d5358607e6fec588e8d276863911bfdb7aaad4b | 9d72a46de84df96ca1ba76eeeba0ca284727c360 | refs/heads/master | 2021-07-09T02:04:47.705000 | 2019-08-19T13:28:28 | 2019-08-19T13:28:28 | 203,178,286 | 0 | 0 | null | false | 2020-10-13T15:26:24 | 2019-08-19T13:27:30 | 2019-08-19T13:28:40 | 2020-10-13T15:26:23 | 8 | 0 | 0 | 1 | Java | false | false | package schoolManagment.SchoolManagment;
import java.lang.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ImplementCourseList implements CourseList {
Scanner scanerInput = new Scanner(System.in);
static List<Course> CoursesList = new ArrayList<Course>();
public List<Course> getCoursesList() {
return CoursesList;
}
public void setCoursesList(List<Course> coursesList) {
CoursesList = coursesList;
}
public void CreatCourse() {
Course Courses = new Course();
System.out.println("please enter course name ");
String courseName = scanerInput.next();
Courses.setCourseName(courseName);
System.out.println(" please add start date example (20160816)");
int courseDate = scanerInput.nextInt();
Courses.setStartDate(courseDate);
System.out.println(" please add course duration by month");
int courseDuration = scanerInput.nextInt();
System.out.println("course duration" + ": " + courseDuration + " month");
Courses.setWeekDuration(courseDuration);
saveCourse(Courses);
CoursesList.add(Courses);
System.out.println(Courses);
}
@Override
public Course saveCourse(Course course) {
if (course == null) {
throw new IllegalArgumentException();
} else {
CoursesList.add(course);
return course;
}
}
@Override
public List<Course> findByName(String name) {
List<Course> result = new ArrayList<>();
for (Course cor : CoursesList) {
if (cor.getCourseName().equalsIgnoreCase(name)) {
result.add(cor);
System.out.println(cor);
}
}
return result;
}
public Course findById(int id) {
for (Course cor : CoursesList)
if (cor.getCourseID(id) == id) {
return cor;
}
return null;
}
@Override
public List<Course> findAll() {
System.out.println(CoursesList);
return CoursesList;
}
@Override
public boolean removeCourse(Course course) {
boolean isDeleted = false;
for (Course cor : CoursesList) {
isDeleted = CoursesList.remove(cor);
if (isDeleted)
System.out.println("Course Has Been Removed");
else
System.out.println("course Has Not Been Removed");
return isDeleted;
}
return false;
}
public void toPrintCourse(Course course) {
for (Course cor : CoursesList) {
System.out.println(cor);
}
}
public void corsAction() {
System.out.println("Welcome to Course Section" + "\n20-|| Add New Course ||" + "\n21-|| Search ||"
+ "\n22-|| Delete ||" + "\n23-|| Find All ||");
int selections = scanerInput.nextInt();
boolean running = true;
while (running) {
if (selections == 20) {
System.out.println("You Can Add Here");
CreatCourse();
break;
}
if (selections == 21) {
System.out.println("Please Select" + "\n211-|| By Name ||" + "\n212-|| By Id ||");
selections = scanerInput.nextInt();
if (selections == 211) {
System.out.println("please enter course name ");
String name = scanerInput.next();
List<Course> courses = findByName(name);
for (Course cor : courses) {
System.out.println(cor);
}
break;
}
if (selections == 212) {
System.out.println("please enter course id");
int CourseID = scanerInput.nextInt();
Course cours = findById(CourseID);
System.out.println(cours);
break;
}
break;
}
if (selections == 22) {
System.out.println("You Can Delete Here");
System.out.println("please enter course id ");
int CourseId = scanerInput.nextInt();
Course Cor = (Course) findById(CourseId);
System.out.println(Cor);
removeCourse(Cor);
System.out.println(Cor + "has been removed ");
break;
}
if (selections == 23) {
findAll();
break;
}
}
}
}
| UTF-8 | Java | 3,884 | java | ImplementCourseList.java | Java | [] | null | [] | package schoolManagment.SchoolManagment;
import java.lang.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ImplementCourseList implements CourseList {
Scanner scanerInput = new Scanner(System.in);
static List<Course> CoursesList = new ArrayList<Course>();
public List<Course> getCoursesList() {
return CoursesList;
}
public void setCoursesList(List<Course> coursesList) {
CoursesList = coursesList;
}
public void CreatCourse() {
Course Courses = new Course();
System.out.println("please enter course name ");
String courseName = scanerInput.next();
Courses.setCourseName(courseName);
System.out.println(" please add start date example (20160816)");
int courseDate = scanerInput.nextInt();
Courses.setStartDate(courseDate);
System.out.println(" please add course duration by month");
int courseDuration = scanerInput.nextInt();
System.out.println("course duration" + ": " + courseDuration + " month");
Courses.setWeekDuration(courseDuration);
saveCourse(Courses);
CoursesList.add(Courses);
System.out.println(Courses);
}
@Override
public Course saveCourse(Course course) {
if (course == null) {
throw new IllegalArgumentException();
} else {
CoursesList.add(course);
return course;
}
}
@Override
public List<Course> findByName(String name) {
List<Course> result = new ArrayList<>();
for (Course cor : CoursesList) {
if (cor.getCourseName().equalsIgnoreCase(name)) {
result.add(cor);
System.out.println(cor);
}
}
return result;
}
public Course findById(int id) {
for (Course cor : CoursesList)
if (cor.getCourseID(id) == id) {
return cor;
}
return null;
}
@Override
public List<Course> findAll() {
System.out.println(CoursesList);
return CoursesList;
}
@Override
public boolean removeCourse(Course course) {
boolean isDeleted = false;
for (Course cor : CoursesList) {
isDeleted = CoursesList.remove(cor);
if (isDeleted)
System.out.println("Course Has Been Removed");
else
System.out.println("course Has Not Been Removed");
return isDeleted;
}
return false;
}
public void toPrintCourse(Course course) {
for (Course cor : CoursesList) {
System.out.println(cor);
}
}
public void corsAction() {
System.out.println("Welcome to Course Section" + "\n20-|| Add New Course ||" + "\n21-|| Search ||"
+ "\n22-|| Delete ||" + "\n23-|| Find All ||");
int selections = scanerInput.nextInt();
boolean running = true;
while (running) {
if (selections == 20) {
System.out.println("You Can Add Here");
CreatCourse();
break;
}
if (selections == 21) {
System.out.println("Please Select" + "\n211-|| By Name ||" + "\n212-|| By Id ||");
selections = scanerInput.nextInt();
if (selections == 211) {
System.out.println("please enter course name ");
String name = scanerInput.next();
List<Course> courses = findByName(name);
for (Course cor : courses) {
System.out.println(cor);
}
break;
}
if (selections == 212) {
System.out.println("please enter course id");
int CourseID = scanerInput.nextInt();
Course cours = findById(CourseID);
System.out.println(cours);
break;
}
break;
}
if (selections == 22) {
System.out.println("You Can Delete Here");
System.out.println("please enter course id ");
int CourseId = scanerInput.nextInt();
Course Cor = (Course) findById(CourseId);
System.out.println(Cor);
removeCourse(Cor);
System.out.println(Cor + "has been removed ");
break;
}
if (selections == 23) {
findAll();
break;
}
}
}
}
| 3,884 | 0.628733 | 0.619464 | 159 | 22.427673 | 20.77355 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.647799 | false | false | 13 |
23110c26e3b6e0b62de6108d2288f5b3ac2432d8 | 23,845,658,485,325 | 3e0d6cc5fdffc31c0d19c56c2bf4c558f08354b2 | /temp/src/lxj/ssh2/base/core/search/TermQueryFactoryUtil.java | f2ecf7dc01a709044470702343a2b409ca4bdfae | [] | no_license | lixiaojian/demo | https://github.com/lixiaojian/demo | 324b65278738ae5968ca156db168e57004fdf884 | b4b39bc8d838c10af040cbe58ac369866ce820f1 | refs/heads/master | 2016-07-26T09:35:10.804000 | 2013-06-08T05:23:22 | 2013-06-08T05:23:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*@copyright :Copyright @2012, VISIONET ltd. All right reserved.
*
*/
package lxj.ssh2.base.core.search;
/**
* @author visionet
*/
public class TermQueryFactoryUtil {
public static TermQuery create(String field, long value) {
return getTermQueryFactory().create(field, value);
}
public static TermQuery create(String field, String value) {
return getTermQueryFactory().create(field, value);
}
public static TermQueryFactory getTermQueryFactory() {
return _termQueryFactory;
}
public void setTermQueryFactory(
TermQueryFactory termQueryFactory) {
_termQueryFactory = termQueryFactory;
}
private static TermQueryFactory _termQueryFactory;
} | UTF-8 | Java | 678 | java | TermQueryFactoryUtil.java | Java | [
{
"context": "package lxj.ssh2.base.core.search;\n\n/**\n * @author visionet\n */\npublic class TermQueryFactoryUtil {\n\n\tpublic ",
"end": 140,
"score": 0.9995237588882446,
"start": 132,
"tag": "USERNAME",
"value": "visionet"
}
] | null | [] | /**
*
*@copyright :Copyright @2012, VISIONET ltd. All right reserved.
*
*/
package lxj.ssh2.base.core.search;
/**
* @author visionet
*/
public class TermQueryFactoryUtil {
public static TermQuery create(String field, long value) {
return getTermQueryFactory().create(field, value);
}
public static TermQuery create(String field, String value) {
return getTermQueryFactory().create(field, value);
}
public static TermQueryFactory getTermQueryFactory() {
return _termQueryFactory;
}
public void setTermQueryFactory(
TermQueryFactory termQueryFactory) {
_termQueryFactory = termQueryFactory;
}
private static TermQueryFactory _termQueryFactory;
} | 678 | 0.747788 | 0.740413 | 34 | 18.970589 | 22.808002 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.882353 | false | false | 13 |
fd8afdb9b8a747ee122597b94917682961c7db62 | 10,393,820,866,334 | dd1ec9edef3c41ce51003f687c7cbead432b84f2 | /Drawable.java | 867f1110b8ce9b61466683476c52eef186447141 | [] | no_license | Solopie/Five-in-a-Row | https://github.com/Solopie/Five-in-a-Row | 83d9c8fe20dfa35f3a04a058156154f5cf81e5d0 | 530f1ec7b60a1d42f8543d7a29c073551560a428 | refs/heads/master | 2021-01-06T06:12:41.384000 | 2020-04-24T11:50:25 | 2020-04-24T11:50:25 | 241,231,867 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | interface Drawable {
public void drawComponent();
}
| UTF-8 | Java | 59 | java | Drawable.java | Java | [] | null | [] | interface Drawable {
public void drawComponent();
}
| 59 | 0.677966 | 0.677966 | 4 | 13.75 | 12.968713 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 13 |
b566c9ae523fe9e1a4ad4468aea1b809c6ff6c1e | 16,243,566,374,119 | 3e7d74e632f081d4ed44d06c0cb7a60eb592a904 | /summer/SpringBoot/springboot-jdbc/src/main/java/com/example/springbootjdbc/controller/AccountController.java | 6b9f502d32986fcf9a16b871a47495699b374efd | [] | no_license | lalahaha323/SpringBootPractice | https://github.com/lalahaha323/SpringBootPractice | da32a3ec87fb94626790b4b2af827b7b060aedcd | 14659b262671f9495034b7792a424d15d209e15a | refs/heads/master | 2022-07-27T16:25:27.636000 | 2020-01-29T14:11:20 | 2020-01-29T14:11:20 | 197,742,452 | 0 | 0 | null | false | 2022-06-21T01:48:10 | 2019-07-19T09:16:23 | 2020-01-29T14:11:30 | 2022-06-21T01:48:10 | 624 | 0 | 0 | 5 | Java | false | false | package com.example.springbootjdbc.controller;
import com.example.springbootjdbc.enty.Account;
import com.example.springbootjdbc.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
IAccountService accountService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<Account> getAccounts() {
return accountService.findAccountList();
}
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public Account getAccountById(@PathVariable("id") int id) {
return accountService.findAccountById(id);
}
@RequestMapping(value="/{id}",method=RequestMethod.PUT)
public String updateAccount(@RequestBody HashMap<String, String> map) {
int id = Integer.parseInt(map.get("id"));
double money = Double.parseDouble(map.get("money"));
String name = map.get("name");
Account account = new Account();
account.setMoney(money);
account.setName(name);
account.setId(id);
int t = accountService.update(account);
if(t == 1) {
return account.toString();
} else {
return "fail";
}
}
@RequestMapping(value = "", method = RequestMethod.POST)
public String postAccount(@RequestBody HashMap<String, String> map) {
Account account = new Account();
double money = Double.parseDouble(map.get("money"));
String name = map.get("name");
account.setMoney(money);
account.setName(name);
int t = accountService.add(account);
if(t == 1) {
return account.toString();
} else {
return "fail";
}
}
}
| UTF-8 | Java | 1,954 | java | AccountController.java | Java | [] | null | [] | package com.example.springbootjdbc.controller;
import com.example.springbootjdbc.enty.Account;
import com.example.springbootjdbc.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
IAccountService accountService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<Account> getAccounts() {
return accountService.findAccountList();
}
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public Account getAccountById(@PathVariable("id") int id) {
return accountService.findAccountById(id);
}
@RequestMapping(value="/{id}",method=RequestMethod.PUT)
public String updateAccount(@RequestBody HashMap<String, String> map) {
int id = Integer.parseInt(map.get("id"));
double money = Double.parseDouble(map.get("money"));
String name = map.get("name");
Account account = new Account();
account.setMoney(money);
account.setName(name);
account.setId(id);
int t = accountService.update(account);
if(t == 1) {
return account.toString();
} else {
return "fail";
}
}
@RequestMapping(value = "", method = RequestMethod.POST)
public String postAccount(@RequestBody HashMap<String, String> map) {
Account account = new Account();
double money = Double.parseDouble(map.get("money"));
String name = map.get("name");
account.setMoney(money);
account.setName(name);
int t = accountService.add(account);
if(t == 1) {
return account.toString();
} else {
return "fail";
}
}
}
| 1,954 | 0.654555 | 0.653531 | 61 | 31.032787 | 22.200256 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57377 | false | false | 13 |
77720b1fa4fe8ab09d9e1a41f4edbffa7d5c1d8e | 13,786,845,060,725 | 02b464724d0db652824552c1a01d32fe65d2c076 | /InscriptionsSportives/src/gui/controllers/competition/VoirCandidatsController.java | c9443b95bf8642759def2d673f0840d0e3045f4c | [] | no_license | Nenjil/inscriptionsSportives | https://github.com/Nenjil/inscriptionsSportives | 9d2e5abaf24fae837d8fd4748da1176a7f7e072a | 4415cc11ab91931065be913a32ce33173566d182 | refs/heads/master | 2020-04-04T19:39:26.852000 | 2019-05-20T01:40:40 | 2019-05-20T01:40:40 | 156,215,088 | 0 | 1 | null | true | 2018-11-05T12:33:33 | 2018-11-05T12:33:32 | 2016-01-14T23:38:16 | 2018-03-12T14:14:11 | 13 | 0 | 0 | 0 | null | false | null | package gui.controllers.competition;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import inscriptions.Candidat;
import inscriptions.Competition;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
public class VoirCandidatsController implements Initializable {
@FXML
ListView<Candidat> LV_candidats= new ListView<Candidat>() ;;
private Stage dialogStage;
private ObservableList<Candidat>candidats ;
public void setDialogStage(Stage dialogStage) {
this.dialogStage = dialogStage;
}
public void setListCandidats (Competition compet) {
candidats = FXCollections.observableArrayList(compet.getCandidats());
LV_candidats.setItems(candidats);
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
}
@FXML
public void backtoMainMenu(ActionEvent e) throws IOException {
dialogStage.close();
}
}
| UTF-8 | Java | 1,141 | java | VoirCandidatsController.java | Java | [] | null | [] | package gui.controllers.competition;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import inscriptions.Candidat;
import inscriptions.Competition;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
public class VoirCandidatsController implements Initializable {
@FXML
ListView<Candidat> LV_candidats= new ListView<Candidat>() ;;
private Stage dialogStage;
private ObservableList<Candidat>candidats ;
public void setDialogStage(Stage dialogStage) {
this.dialogStage = dialogStage;
}
public void setListCandidats (Competition compet) {
candidats = FXCollections.observableArrayList(compet.getCandidats());
LV_candidats.setItems(candidats);
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
}
@FXML
public void backtoMainMenu(ActionEvent e) throws IOException {
dialogStage.close();
}
}
| 1,141 | 0.743208 | 0.741455 | 45 | 23.355556 | 21.649897 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.933333 | false | false | 13 |
858723c0c3c087c3125678da50141ca6c6412dc8 | 6,811,818,199,574 | 25e025e2ea944c17311075470a29be4d419a1321 | /OCRManager/ocr-system/src/main/java/com/ocr/system/model/MarriageLicense.java | ee86e80c79ffc51a50b6828c968b03fb42f5774c | [
"MIT"
] | permissive | Fanbb/XTOCR | https://github.com/Fanbb/XTOCR | 4eba91b5b66349348cdb40a965b0681bd2f268f5 | 8e5e8641cf7f375aa69d374086405e33b1c7e622 | refs/heads/main | 2023-03-30T06:13:00.256000 | 2021-03-26T06:30:00 | 2021-03-26T06:30:00 | 351,686,682 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ocr.system.model;
import com.ocr.common.utils.StringUtils;
/**
* 结婚证
* @author Jocker
*/
public class MarriageLicense {
/**
* 流水ID
*/
private String tradeId;
/**
* 结婚证号
*/
private String marriageNo;
/**
* 配偶姓名
*/
private String name;
/**
* 配偶身份证号
*/
private String idCardNo;
/**
* 图片类型
*/
private String imgType;
/**
* 识别结果
*/
private String flag;
/**
* 预警结果
*/
private String riskFlag;
public String getTradeId() {
return tradeId;
}
public void setTradeId(String tradeId) {
this.tradeId = tradeId;
}
public String getMarriageNo() {
return marriageNo;
}
public void setMarriageNo(String marriageNo) {
this.marriageNo = marriageNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdCardNo() {
return idCardNo;
}
public void setIdCardNo(String idCardNo) {
this.idCardNo = idCardNo;
}
public String getImgType() {
return imgType;
}
public void setImgType(String imgType) {
this.imgType = imgType;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getRiskFlag() {
return riskFlag;
}
public void setRiskFlag(String riskFlag) {
this.riskFlag = riskFlag;
}
public MarriageLicense() {
}
public MarriageLicense(String tradeId, String marriageNo, String name, String idCardNo, String imgType, String flag, String riskFlag) {
this.tradeId = tradeId;
this.marriageNo = marriageNo;
this.name = name;
this.idCardNo = idCardNo;
this.imgType = imgType;
this.flag = flag;
this.riskFlag = riskFlag;
}
@Override
public String toString() {
return "MarriageLicense{" +
"tradeId='" + tradeId + '\'' +
", marriageNo='" + marriageNo + '\'' +
", name='" + name + '\'' +
", idCardNo='" + idCardNo + '\'' +
", imgType='" + imgType + '\'' +
", flag='" + flag + '\'' +
", riskFlag='" + riskFlag + '\'' +
'}';
}
public boolean hasEmptyField() {
return StringUtils.isEmpty(getMarriageNo())|| StringUtils.isEmpty(getIdCardNo())||StringUtils.isEmpty(getName());
}
}
| UTF-8 | Java | 2,646 | java | MarriageLicense.java | Java | [
{
"context": "r.common.utils.StringUtils;\n\n/**\n * 结婚证\n * @author Jocker\n */\npublic class MarriageLicense {\n /**\n *",
"end": 102,
"score": 0.8510545492172241,
"start": 96,
"tag": "USERNAME",
"value": "Jocker"
}
] | null | [] | package com.ocr.system.model;
import com.ocr.common.utils.StringUtils;
/**
* 结婚证
* @author Jocker
*/
public class MarriageLicense {
/**
* 流水ID
*/
private String tradeId;
/**
* 结婚证号
*/
private String marriageNo;
/**
* 配偶姓名
*/
private String name;
/**
* 配偶身份证号
*/
private String idCardNo;
/**
* 图片类型
*/
private String imgType;
/**
* 识别结果
*/
private String flag;
/**
* 预警结果
*/
private String riskFlag;
public String getTradeId() {
return tradeId;
}
public void setTradeId(String tradeId) {
this.tradeId = tradeId;
}
public String getMarriageNo() {
return marriageNo;
}
public void setMarriageNo(String marriageNo) {
this.marriageNo = marriageNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdCardNo() {
return idCardNo;
}
public void setIdCardNo(String idCardNo) {
this.idCardNo = idCardNo;
}
public String getImgType() {
return imgType;
}
public void setImgType(String imgType) {
this.imgType = imgType;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getRiskFlag() {
return riskFlag;
}
public void setRiskFlag(String riskFlag) {
this.riskFlag = riskFlag;
}
public MarriageLicense() {
}
public MarriageLicense(String tradeId, String marriageNo, String name, String idCardNo, String imgType, String flag, String riskFlag) {
this.tradeId = tradeId;
this.marriageNo = marriageNo;
this.name = name;
this.idCardNo = idCardNo;
this.imgType = imgType;
this.flag = flag;
this.riskFlag = riskFlag;
}
@Override
public String toString() {
return "MarriageLicense{" +
"tradeId='" + tradeId + '\'' +
", marriageNo='" + marriageNo + '\'' +
", name='" + name + '\'' +
", idCardNo='" + idCardNo + '\'' +
", imgType='" + imgType + '\'' +
", flag='" + flag + '\'' +
", riskFlag='" + riskFlag + '\'' +
'}';
}
public boolean hasEmptyField() {
return StringUtils.isEmpty(getMarriageNo())|| StringUtils.isEmpty(getIdCardNo())||StringUtils.isEmpty(getName());
}
}
| 2,646 | 0.53483 | 0.53483 | 125 | 19.672001 | 20.954342 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384 | false | false | 13 |
1479ecd14f19d237b193750b513e1ba05460a4c0 | 10,926,396,820,336 | 259b114e0fb2a7ea2d44543035df2545311192c4 | /src/com/cadastro/servelets/AtivaCadastro.java | cd49847a5f7b662d7c28dd34cb63469f59356269 | [] | no_license | cledsonAlves/digitalJava | https://github.com/cledsonAlves/digitalJava | 0580411b968716de5ca8c2e65d1e3ac11a6af596 | ac45a5ab6f0fc40b33e5b6b078c2cdbb991acfd7 | refs/heads/master | 2021-01-16T18:19:14.837000 | 2014-11-20T21:29:08 | 2014-11-20T21:29:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cadastro.servelets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cadastro.banco.ManipulaBanco;
public class AtivaCadastro extends HttpServlet {
private static final long serialVersionUID = 1L;
public AtivaCadastro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
ManipulaBanco mb = new ManipulaBanco();
String token = request.getParameter("token");
if(mb.ativaRegistro(token)){
response.setContentType("text/html");
// redireciona para pagina de sucesso ...
String pagina = "./sucess-ativacao.jsp";
RequestDispatcher dis = request.getRequestDispatcher(pagina);
dis.forward(request, response);
}
// cadastro já foi efetivado
else {
out.println("<script>");
out.println("alert('Este token não é válido! Registro já foi ativado ou token expirou');");
out.println("</script>");
}
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| ISO-8859-1 | Java | 1,429 | java | AtivaCadastro.java | Java | [] | null | [] | package com.cadastro.servelets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cadastro.banco.ManipulaBanco;
public class AtivaCadastro extends HttpServlet {
private static final long serialVersionUID = 1L;
public AtivaCadastro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
ManipulaBanco mb = new ManipulaBanco();
String token = request.getParameter("token");
if(mb.ativaRegistro(token)){
response.setContentType("text/html");
// redireciona para pagina de sucesso ...
String pagina = "./sucess-ativacao.jsp";
RequestDispatcher dis = request.getRequestDispatcher(pagina);
dis.forward(request, response);
}
// cadastro já foi efetivado
else {
out.println("<script>");
out.println("alert('Este token não é válido! Registro já foi ativado ou token expirou');");
out.println("</script>");
}
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| 1,429 | 0.719101 | 0.718399 | 58 | 23.551723 | 28.153013 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.637931 | false | false | 13 |
7654b24cc409fa2f9f1985faf0af85efb8d548b7 | 13,168,369,793,388 | ff0dc48e0a85c0c6e1acb6d3da4842cbe322d34f | /letubaselib/src/main/java/com/letu/app/baselib/base/BaseFragmentView.java | 9e3aef3da38907a903ae7643f7b9be66a8159ab0 | [] | no_license | id4lin/letu | https://github.com/id4lin/letu | 9dccbbb96c0232c49d139715df667a83d9304885 | bec70a2c10ddfdc72bc2e31f8cb44ab34dc485ce | refs/heads/master | 2020-03-27T00:51:08.831000 | 2018-09-28T11:32:27 | 2018-09-28T11:32:27 | 145,662,292 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.letu.app.baselib.base;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;
/**
* Created by ${user} on 2018/7/5
*/
public interface BaseFragmentView {
BaseFragment getFragment();
LifecycleProvider<FragmentEvent> getLifecycleProvider();
}
| UTF-8 | Java | 314 | java | BaseFragmentView.java | Java | [
{
"context": "fecycle2.android.FragmentEvent;\n\n/**\n * Created by ${user} on 2018/7/5\n */\npublic interface BaseFragmen",
"end": 158,
"score": 0.7630532383918762,
"start": 158,
"tag": "USERNAME",
"value": ""
},
{
"context": "ycle2.android.FragmentEvent;\n\n/**\n * Created by ${user} on 2018/7/5\n */\npublic interface BaseFragmentVie",
"end": 165,
"score": 0.632024884223938,
"start": 161,
"tag": "USERNAME",
"value": "user"
}
] | null | [] | package com.letu.app.baselib.base;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;
/**
* Created by ${user} on 2018/7/5
*/
public interface BaseFragmentView {
BaseFragment getFragment();
LifecycleProvider<FragmentEvent> getLifecycleProvider();
}
| 314 | 0.77707 | 0.751592 | 12 | 25.166666 | 21.717249 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 13 |
111e6ea21c619d72e37a6676e38e39398efa5007 | 25,262,997,704,864 | 6cb34b25be0c254fcba72165777bf939d65686cd | /library/src/com/eyeem/poll/Poll.java | 7d9ab58bdf89848ab2f2ce77629346200102ad4c | [
"Apache-2.0"
] | permissive | mttkay/PotatoLibrary | https://github.com/mttkay/PotatoLibrary | 00942408f0b1f016e7d29fa8befebf9a48cca0c2 | 7a6e9cc420f9face7c195641af91ced07ff62b27 | refs/heads/master | 2021-01-18T14:15:53.980000 | 2013-02-22T09:18:29 | 2013-02-22T09:18:29 | 8,389,425 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eyeem.poll;
import java.util.ArrayList;
import java.util.Vector;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.eyeem.storage.Storage;
import com.eyeem.storage.Storage.List;
/**
* Base class for polling. Works in combination with {@link Storage}
* class.
*
* @param <T>
*/
public abstract class Poll<T> {
public static boolean DEBUG = false;
/**
* No poll has been made yet so we don't know
* anything.
*/
public static final int STATE_UNKNOWN = -1;
/**
* Poll is looking good.
*/
public static final int STATE_OK = 0;
/**
* Poll has no content.
*/
public static final int STATE_NO_CONTENT = 1;
/**
* Poll has no content due to a error.
*/
public static final int STATE_ERROR = 2;
/**
* Associated storage.
*/
protected Storage<T>.List list;
/**
* No more items to poll
*/
protected boolean exhausted;
/**
* Indicates whether we're polling or not.
*/
protected boolean polling;
/**
* Last time successful {@link #update(Listener, boolean)} occured.
* UNIX time ms.
*/
protected long lastTimeUpdated;
/**
* How often should polling happen.
*/
protected long refreshPeriod;
/**
* Represents state in which poll is.
*/
private int state = STATE_UNKNOWN;
/**
* Fetches new items
* @return
* @throws Throwable
*/
protected abstract ArrayList<T> newItems() throws Throwable;
/**
* Fetches older items
* @return
* @throws Throwable
*/
protected abstract ArrayList<T> oldItems() throws Throwable;
/**
* Appends new items to the {@link #list}
* @param newItems
* @param listener
* @param cleanUp
* @return
*/
protected abstract int appendNewItems(ArrayList<T> newItems, Poll.Listener listener, boolean cleanUp);
/**
* Appends old items to the {@link #list}
* @param oldItems
* @param listener
* @return
*/
protected abstract int appendOldItems(ArrayList<T> oldItems, Poll.Listener listener);
/**
* @param ctx
* @param newCount
* @return Message associated with successful update.
*/
protected abstract String getSuccessMessage(Context ctx, int newCount);
/**
* Fetch new items task
*/
private RefreshTask updating;
/**
* Fetch older items task
*/
private RefreshTask fetchingMore;
/**
* Indicates whether {@link Poll} should update or not. Default policy
* is to update if {@link #lastTimeUpdated} happened more than
* {@link #refreshPeriod} time ago.
* @return
*/
public boolean shouldUpdate() {
return (System.currentTimeMillis() - refreshPeriod) > lastTimeUpdated;
}
/**
* Updates poll if it {@link #shouldUpdate()}
* @param listener
*/
public void updateIfNecessary(Listener listener) {
if (shouldUpdate())
update(listener, false);
}
/**
* Updates poll always. Please consider using
* {@link #updateIfNecessary(Listener)}
* @param listener
* @param cleanUp
*/
public synchronized void update(final Listener listener, final boolean cleanUp) {
if (updating == null || updating.working == false) {
updating = new RefreshTask() {
@Override
protected ArrayList<T> doInBackground(Void... params) {
try {
return newItems();
} catch (Throwable e) {
error = e;
this.cancel(true);
}
return new ArrayList<T>();
}
@Override
public int itemsAction(ArrayList<T> result) throws Throwable {
return appendNewItems(result, listener, cleanUp);
}
@Override
protected void onSuccess(int result) {
lastTimeUpdated = System.currentTimeMillis();
if (list.isEmpty()) {
state = STATE_NO_CONTENT;
onStateChanged();
}
super.onSuccess(result);
}
@Override
protected void onError(Throwable error) {
if (list.isEmpty()) {
state = STATE_ERROR;
onStateChanged();
}
super.onError(error);
}
};
}
updating.refresh(listener);
}
public synchronized void fetchMore(final Listener listener) {
if (exhausted) {
if (listener != null)
listener.onExhausted();
return;
}
if (fetchingMore == null || fetchingMore.working == false) {
fetchingMore = new RefreshTask() {
@Override
protected ArrayList<T> doInBackground(Void... params) {
try {
return oldItems();
} catch (Throwable e) {
error = e;
this.cancel(true);
}
return new ArrayList<T>();
}
@Override
public int itemsAction(ArrayList<T> result) throws Throwable {
return appendOldItems(result, listener);
}
};
}
fetchingMore.refresh(listener);
}
/**
* Sets the associated {@link List}
* @param list
*/
public void setStorage(Storage<T>.List list) { this.list = list; }
/**
* Getter for the Poll's associated {@link List}
* @return
*/
public Storage<T>.List getStorage() { return list; }
/**
* Poll refresh interface
*/
public interface Listener {
/**
* Poll started
*/
public void onStart();
/**
* Poll encountered an error
* @param error
*/
public void onError(Throwable error);
/**
* Poll was successful
* @param newCount number of new items
*/
public void onSuccess(int newCount);
/**
* Poll is already polling
*/
public void onAlreadyPolling();
/**
* Poll's state has changed
* @param state
*/
public void onStateChanged(int state);
/**
* Poll has exhausted.
*/
public void onExhausted();
}
private abstract class RefreshTask extends AsyncTask<Void, Void, ArrayList<T>> {
Throwable error;
Vector<Listener> listeners = new Vector<Listener>();
boolean working;
boolean executed = false;
public abstract int itemsAction(ArrayList<T> result) throws Throwable;
@Override
protected void onPostExecute(ArrayList<T> result) {
super.onPostExecute(result);
int addedItemsCount = 0;
try {
addedItemsCount = itemsAction(result);
} catch (Throwable e) {
error = e;
}
if (error != null) {
onError(error);
} else if (result != null) {
onSuccess(addedItemsCount);
}
working = false;
}
protected void onSuccess(int result) {
for (Listener listener : listeners)
listener.onSuccess(result);
listeners.clear();
if (this == fetchingMore)
fetchingMore = null;
if (this == updating)
updating = null;
}
protected void onError(Throwable error) {
if (DEBUG) Log.w(getClass().getSimpleName(), "onError", error);
for (Listener listener : listeners)
listener.onError(error);
listeners.clear();
if (this == fetchingMore)
fetchingMore = null;
if (this == updating)
updating = null;
}
@Override
protected void onCancelled() {
super.onCancelled();
onError(error);
working = false;
}
protected void onStateChanged() {
for (Listener listener : listeners)
listener.onStateChanged(state);
}
synchronized void refresh(Listener listener) {
if (listener != null) {
if (!listeners.contains(listener))
listeners.add(listener);
if (working) {
listener.onAlreadyPolling();
}
}
if (!working && !executed) {
executed = true;
working = true;
if (listener != null)
listener.onStart();
execute();
}
}
}
/**
* @return Poll's state
*/
public int getState() {
if (list != null && !list.isEmpty())
return state = STATE_OK;
return state;
}
/**
* @return tells whether it's ok to persist list in it's current state
*/
public boolean okToSave() { return true; }
/**
* Sets {@link #lastTimeUpdated} value to 0.
*/
public void resetLastTimeUpdated() {
lastTimeUpdated = 0;
}
}
| UTF-8 | Java | 8,939 | java | Poll.java | Java | [] | null | [] | package com.eyeem.poll;
import java.util.ArrayList;
import java.util.Vector;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.eyeem.storage.Storage;
import com.eyeem.storage.Storage.List;
/**
* Base class for polling. Works in combination with {@link Storage}
* class.
*
* @param <T>
*/
public abstract class Poll<T> {
public static boolean DEBUG = false;
/**
* No poll has been made yet so we don't know
* anything.
*/
public static final int STATE_UNKNOWN = -1;
/**
* Poll is looking good.
*/
public static final int STATE_OK = 0;
/**
* Poll has no content.
*/
public static final int STATE_NO_CONTENT = 1;
/**
* Poll has no content due to a error.
*/
public static final int STATE_ERROR = 2;
/**
* Associated storage.
*/
protected Storage<T>.List list;
/**
* No more items to poll
*/
protected boolean exhausted;
/**
* Indicates whether we're polling or not.
*/
protected boolean polling;
/**
* Last time successful {@link #update(Listener, boolean)} occured.
* UNIX time ms.
*/
protected long lastTimeUpdated;
/**
* How often should polling happen.
*/
protected long refreshPeriod;
/**
* Represents state in which poll is.
*/
private int state = STATE_UNKNOWN;
/**
* Fetches new items
* @return
* @throws Throwable
*/
protected abstract ArrayList<T> newItems() throws Throwable;
/**
* Fetches older items
* @return
* @throws Throwable
*/
protected abstract ArrayList<T> oldItems() throws Throwable;
/**
* Appends new items to the {@link #list}
* @param newItems
* @param listener
* @param cleanUp
* @return
*/
protected abstract int appendNewItems(ArrayList<T> newItems, Poll.Listener listener, boolean cleanUp);
/**
* Appends old items to the {@link #list}
* @param oldItems
* @param listener
* @return
*/
protected abstract int appendOldItems(ArrayList<T> oldItems, Poll.Listener listener);
/**
* @param ctx
* @param newCount
* @return Message associated with successful update.
*/
protected abstract String getSuccessMessage(Context ctx, int newCount);
/**
* Fetch new items task
*/
private RefreshTask updating;
/**
* Fetch older items task
*/
private RefreshTask fetchingMore;
/**
* Indicates whether {@link Poll} should update or not. Default policy
* is to update if {@link #lastTimeUpdated} happened more than
* {@link #refreshPeriod} time ago.
* @return
*/
public boolean shouldUpdate() {
return (System.currentTimeMillis() - refreshPeriod) > lastTimeUpdated;
}
/**
* Updates poll if it {@link #shouldUpdate()}
* @param listener
*/
public void updateIfNecessary(Listener listener) {
if (shouldUpdate())
update(listener, false);
}
/**
* Updates poll always. Please consider using
* {@link #updateIfNecessary(Listener)}
* @param listener
* @param cleanUp
*/
public synchronized void update(final Listener listener, final boolean cleanUp) {
if (updating == null || updating.working == false) {
updating = new RefreshTask() {
@Override
protected ArrayList<T> doInBackground(Void... params) {
try {
return newItems();
} catch (Throwable e) {
error = e;
this.cancel(true);
}
return new ArrayList<T>();
}
@Override
public int itemsAction(ArrayList<T> result) throws Throwable {
return appendNewItems(result, listener, cleanUp);
}
@Override
protected void onSuccess(int result) {
lastTimeUpdated = System.currentTimeMillis();
if (list.isEmpty()) {
state = STATE_NO_CONTENT;
onStateChanged();
}
super.onSuccess(result);
}
@Override
protected void onError(Throwable error) {
if (list.isEmpty()) {
state = STATE_ERROR;
onStateChanged();
}
super.onError(error);
}
};
}
updating.refresh(listener);
}
public synchronized void fetchMore(final Listener listener) {
if (exhausted) {
if (listener != null)
listener.onExhausted();
return;
}
if (fetchingMore == null || fetchingMore.working == false) {
fetchingMore = new RefreshTask() {
@Override
protected ArrayList<T> doInBackground(Void... params) {
try {
return oldItems();
} catch (Throwable e) {
error = e;
this.cancel(true);
}
return new ArrayList<T>();
}
@Override
public int itemsAction(ArrayList<T> result) throws Throwable {
return appendOldItems(result, listener);
}
};
}
fetchingMore.refresh(listener);
}
/**
* Sets the associated {@link List}
* @param list
*/
public void setStorage(Storage<T>.List list) { this.list = list; }
/**
* Getter for the Poll's associated {@link List}
* @return
*/
public Storage<T>.List getStorage() { return list; }
/**
* Poll refresh interface
*/
public interface Listener {
/**
* Poll started
*/
public void onStart();
/**
* Poll encountered an error
* @param error
*/
public void onError(Throwable error);
/**
* Poll was successful
* @param newCount number of new items
*/
public void onSuccess(int newCount);
/**
* Poll is already polling
*/
public void onAlreadyPolling();
/**
* Poll's state has changed
* @param state
*/
public void onStateChanged(int state);
/**
* Poll has exhausted.
*/
public void onExhausted();
}
private abstract class RefreshTask extends AsyncTask<Void, Void, ArrayList<T>> {
Throwable error;
Vector<Listener> listeners = new Vector<Listener>();
boolean working;
boolean executed = false;
public abstract int itemsAction(ArrayList<T> result) throws Throwable;
@Override
protected void onPostExecute(ArrayList<T> result) {
super.onPostExecute(result);
int addedItemsCount = 0;
try {
addedItemsCount = itemsAction(result);
} catch (Throwable e) {
error = e;
}
if (error != null) {
onError(error);
} else if (result != null) {
onSuccess(addedItemsCount);
}
working = false;
}
protected void onSuccess(int result) {
for (Listener listener : listeners)
listener.onSuccess(result);
listeners.clear();
if (this == fetchingMore)
fetchingMore = null;
if (this == updating)
updating = null;
}
protected void onError(Throwable error) {
if (DEBUG) Log.w(getClass().getSimpleName(), "onError", error);
for (Listener listener : listeners)
listener.onError(error);
listeners.clear();
if (this == fetchingMore)
fetchingMore = null;
if (this == updating)
updating = null;
}
@Override
protected void onCancelled() {
super.onCancelled();
onError(error);
working = false;
}
protected void onStateChanged() {
for (Listener listener : listeners)
listener.onStateChanged(state);
}
synchronized void refresh(Listener listener) {
if (listener != null) {
if (!listeners.contains(listener))
listeners.add(listener);
if (working) {
listener.onAlreadyPolling();
}
}
if (!working && !executed) {
executed = true;
working = true;
if (listener != null)
listener.onStart();
execute();
}
}
}
/**
* @return Poll's state
*/
public int getState() {
if (list != null && !list.isEmpty())
return state = STATE_OK;
return state;
}
/**
* @return tells whether it's ok to persist list in it's current state
*/
public boolean okToSave() { return true; }
/**
* Sets {@link #lastTimeUpdated} value to 0.
*/
public void resetLastTimeUpdated() {
lastTimeUpdated = 0;
}
}
| 8,939 | 0.549838 | 0.549055 | 370 | 23.15946 | 20.371256 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.302703 | false | false | 13 |
e0cfc5c7d1ea38997ea0a569f44b2ba645d71328 | 34,797,825,056,021 | d454c0939078fed92ad2052723f5433b6172f367 | /src/main/java/common_toolkits/multi_thread/callable/FutureAndCallableExample.java | 0d8228936c288e5ffc159bb0b99545946f6bd43a | [] | no_license | dangshanli/highlight_spring4idea | https://github.com/dangshanli/highlight_spring4idea | 71ccfe80afbf27b69b23e37f7ac4404b8c31bff5 | 15a64295ff52063929cbf5408dabd22eed7d1716 | refs/heads/master | 2021-09-19T23:44:37.727000 | 2018-08-01T14:26:06 | 2018-08-01T14:26:06 | 115,599,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package common_toolkits.multi_thread.callable;
import java.util.concurrent.*;
/**
* @author luzj
* @description: 1.使用Callable接口,创建任务
* 2.Callable几乎等同于Runnable,不同的是他可以在call()方法中返回结果
* 3.Callable<T>通过泛型T指定返回类型
* 4.Callable返回的是Future类型,里面包装的是我们的泛型类型的结果对象
* 5.future.get()获取返回值,在task结束之前这个方法处于阻塞状态
* 6.Future对象是可以及时得到的,但是里面的值是异步得到的,他要等到task执行完毕
* 7.future.get(time,TimeUnit),设定task阻塞超时时间,一般task依赖远程服务或者其他的服务挂掉,
* 会一直线程阻塞,这时设定一个超时时间,超时后会自动中断任务,抛出TimeoutException异常
* @date 2018/4/3
*/
public class FutureAndCallableExample {
/**
* Callable的基础应用
*/
public static void example1() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> callable = () -> {
System.out.println("进入Callable");
Thread.sleep(2000);
return "Hello from Callable";
};
System.out.println("提交Callable");
Future<String> future = executorService.submit(callable);
System.out.println("做其他事情,在Callable的结果出来之前");
try {
//todo 在Callable结束之前,这个方法处于阻塞状态
String result = future.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
executorService.shutdown();
}
/**
* 例子2,使用future.isDone()检测任务是否完成
*/
public static void example2() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(() -> {
Thread.sleep(2000);
return "hello is done";
});
//TODO 任务检测,不完成会一直卡在这
//TODO main主线程和executor的新线程不断交织运行,直到executor线程结束
while (!future.isDone()) {
System.out.println("任务仍然在进行...");
Thread.sleep(200);
}
System.out.println("任务完成");
String result = future.get();
System.out.println(result);
executorService.shutdown();
}
public static void example3() throws InterruptedException, ExecutionException, TimeoutException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
long startTime = System.nanoTime();
Future<String> future = executorService.submit(() -> {
Thread.sleep(3000);
return "hello from is cancelled";
});
while (!future.isDone()) {
System.out.println("任务仍在进行...");
Thread.sleep(200);
double elapsedTimeInSec = (System.nanoTime() - startTime) / (1000 * 1000 * 1000.0);
if (elapsedTimeInSec > 4)
future.cancel(true);
}
if (!future.isCancelled()) {
System.out.println("任务完成!检验结果");
//todo 设定任务超时
String result = future.get(1, TimeUnit.SECONDS);
System.out.println(result);
} else
System.out.println("任务被取消");
executorService.shutdown();
}
public static void main(String[] args) {
try {
// example1();
// example2();
example3();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 4,074 | java | FutureAndCallableExample.java | Java | [
{
"context": "e;\n\nimport java.util.concurrent.*;\n\n/**\n * @author luzj\n * @description: 1.使用Callable接口,创建任务\n * 2.Callabl",
"end": 99,
"score": 0.9996485710144043,
"start": 95,
"tag": "USERNAME",
"value": "luzj"
}
] | null | [] | package common_toolkits.multi_thread.callable;
import java.util.concurrent.*;
/**
* @author luzj
* @description: 1.使用Callable接口,创建任务
* 2.Callable几乎等同于Runnable,不同的是他可以在call()方法中返回结果
* 3.Callable<T>通过泛型T指定返回类型
* 4.Callable返回的是Future类型,里面包装的是我们的泛型类型的结果对象
* 5.future.get()获取返回值,在task结束之前这个方法处于阻塞状态
* 6.Future对象是可以及时得到的,但是里面的值是异步得到的,他要等到task执行完毕
* 7.future.get(time,TimeUnit),设定task阻塞超时时间,一般task依赖远程服务或者其他的服务挂掉,
* 会一直线程阻塞,这时设定一个超时时间,超时后会自动中断任务,抛出TimeoutException异常
* @date 2018/4/3
*/
public class FutureAndCallableExample {
/**
* Callable的基础应用
*/
public static void example1() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> callable = () -> {
System.out.println("进入Callable");
Thread.sleep(2000);
return "Hello from Callable";
};
System.out.println("提交Callable");
Future<String> future = executorService.submit(callable);
System.out.println("做其他事情,在Callable的结果出来之前");
try {
//todo 在Callable结束之前,这个方法处于阻塞状态
String result = future.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
executorService.shutdown();
}
/**
* 例子2,使用future.isDone()检测任务是否完成
*/
public static void example2() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(() -> {
Thread.sleep(2000);
return "hello is done";
});
//TODO 任务检测,不完成会一直卡在这
//TODO main主线程和executor的新线程不断交织运行,直到executor线程结束
while (!future.isDone()) {
System.out.println("任务仍然在进行...");
Thread.sleep(200);
}
System.out.println("任务完成");
String result = future.get();
System.out.println(result);
executorService.shutdown();
}
public static void example3() throws InterruptedException, ExecutionException, TimeoutException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
long startTime = System.nanoTime();
Future<String> future = executorService.submit(() -> {
Thread.sleep(3000);
return "hello from is cancelled";
});
while (!future.isDone()) {
System.out.println("任务仍在进行...");
Thread.sleep(200);
double elapsedTimeInSec = (System.nanoTime() - startTime) / (1000 * 1000 * 1000.0);
if (elapsedTimeInSec > 4)
future.cancel(true);
}
if (!future.isCancelled()) {
System.out.println("任务完成!检验结果");
//todo 设定任务超时
String result = future.get(1, TimeUnit.SECONDS);
System.out.println(result);
} else
System.out.println("任务被取消");
executorService.shutdown();
}
public static void main(String[] args) {
try {
// example1();
// example2();
example3();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
| 4,074 | 0.594634 | 0.579342 | 120 | 27.883333 | 22.950739 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 13 |
91903827a7c48dec6d11988865029fa393518466 | 22,187,801,116,052 | 141bd778f666df8653b66385ba86b218cd615fe6 | /nova-pis/src/main/java/net/yuan/nova/pis/controller/MenuController.java | 0ae05b502868cf116f4d1c6d3a05778072bcc097 | [] | no_license | ydapp/ydweb | https://github.com/ydapp/ydweb | f6f4260b832ab1f619f5bac92c604e336af67f17 | 58a07e5ec3eaf6abfb2fb50d9551d680d62200a7 | refs/heads/master | 2021-01-09T20:51:10.566000 | 2017-03-24T08:12:32 | 2017-03-24T08:12:32 | 57,933,696 | 4 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.yuan.nova.pis.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.yuan.nova.commons.SystemConstant;
import net.yuan.nova.core.shiro.vo.User;
import net.yuan.nova.core.vo.JsonVo;
import net.yuan.nova.core.vo.TreeNode;
import net.yuan.nova.pis.entity.PisMenuItem;
import net.yuan.nova.pis.entity.PisUserGroup;
import net.yuan.nova.pis.service.MenuItemService;
import net.yuan.nova.pis.service.PisUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 系统菜单控制器
*
* @author zhangshuai
*
*/
@Controller
public class MenuController {
protected final Logger log = LoggerFactory.getLogger(MenuController.class);
@Autowired
private MenuItemService menuItemService;
@Autowired
private PisUserService pisUserService;
/**
* 获得相应的菜单列表数据
*
* @param request
* @param response
* @param modelMap
* @return
*/
@RequestMapping(value = "/admin/menus")
public ModelMap menus(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
log.debug("获得菜单列表");
// 父节点的ID
String parentId = StringUtils.trimToEmpty(request.getParameter("id"));
if ("-1".equals(parentId)) {
parentId = null;
}
List<TreeNode<PisMenuItem>> list = menuItemService.findMenuTreeNodes(parentId,"");
return modelMap.addAttribute("menus", list);
}
/**
* 根据当前用户的权限获得相应的菜单列表数据
*
* @param request
* @param response
* @param modelMap
* @return
*/
@RequestMapping(value = "/admin/usermenus")
public ModelMap menuslevel(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
Subject currentUser = SecurityUtils.getSubject();
String menu = "";
// 判断登录是否成功
if (currentUser.isAuthenticated()) {
Session session = currentUser.getSession();
User user = (User) session.getAttribute(SystemConstant.SESSION_USER);
PisUserGroup pisUserGroup = pisUserService.getPisUserGroup(user.getUserId());
String type = null!=pisUserGroup?pisUserGroup.getType():" ";
String types=PisUserGroup.TYPE.salesman+","+PisUserGroup.TYPE.commissioner+","+PisUserGroup.TYPE.channelManager;
if(types.trim().indexOf(type)!=-1){
menu="xztjexcell";
}else if(PisUserGroup.TYPE.brokingFirm.toString().indexOf(type)!=-1){
menu="xztjexcell,userManager";
}
}
String parentId = StringUtils.trimToEmpty(request.getParameter("id"));
List<TreeNode<PisMenuItem>> list = null;
list = menuItemService.findMenuTreeNodes(parentId,menu);
return modelMap.addAttribute("menus", list);
}
/**
* 菜单
*
* @param request
* @param response
* @param modelMap
* @return
*/
@RequestMapping(value = "/admin/menu")
public String operateMenu(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap,
@RequestParam("edittype") String edittype) {
PisMenuItem menu = new PisMenuItem();
String privName = StringUtils.trimToEmpty(request.getParameter("privName"));
String menuCode = StringUtils.trimToEmpty(request.getParameter("menuCode"));
String url = StringUtils.trimToEmpty(request.getParameter("url"));
int sort = NumberUtils.toInt(StringUtils.trimToEmpty(request.getParameter("sort")), 1);
String comments = StringUtils.trimToEmpty(request.getParameter("comments"));
String parentMenuId = StringUtils.trimToEmpty(request.getParameter("parentMenuId"));
String menuItemId = StringUtils.trimToEmpty(request.getParameter("menuItemId"));
menu.setPrivName(privName);
menu.setMenuCode(menuCode);
menu.setUrl(url);
menu.setSort(sort);
menu.setComments(comments);
menu.setParentId(parentMenuId);
menu.setId(menuItemId);
JsonVo<PisMenuItem> jsonVo = new JsonVo<PisMenuItem>();
if ("add".equals(edittype)) {
log.debug("添加新菜单");
if (StringUtils.isBlank(menu.getPrivName())) {
jsonVo.putError("privName", "菜单文本不能为空");
}
if (StringUtils.isBlank(menu.getMenuCode())) {
jsonVo.putError("menuCode", "菜单名称不能为空");
}
if (jsonVo.validate()) {
modelMap.addAttribute("json", jsonVo);
modelMap.remove("menu");
} else {
modelMap.addAttribute("json", jsonVo);
modelMap.remove("menu");
}
} else if ("del".equals(edittype)) {
log.debug("删除菜单及相应的子菜单");
String ItemId = menu.getId();
if (StringUtils.isBlank(ItemId)) {
jsonVo.putError("id", "菜单ID不能为空");
}
jsonVo.setResult(menu);
modelMap.addAttribute("json", jsonVo);
modelMap.remove("menu");
if (jsonVo.validate()) {
menuItemService.deleteMenuItem(menu.getId());
}
} else {
log.debug("更新当前菜单");
String ItemId = menu.getId();
if (StringUtils.isBlank(ItemId)) {
jsonVo.putError("id", "菜单ID不能为空");
}
if (StringUtils.isBlank(menu.getPrivName())) {
jsonVo.putError("privName", "菜单文本不能为空");
}
if (StringUtils.isBlank(menu.getMenuCode())) {
jsonVo.putError("menuCode", "菜单名称不能为空");
}
jsonVo.setResult(menu);
modelMap.addAttribute("json", jsonVo);
modelMap.remove("menu");
if (jsonVo.validate()) {
menuItemService.updateMenuItem(menu);
}
}
return "menu";
}
/**
* 菜单详情
*
* @param request
* @param response
* @param modelMap
* @return
*/
@RequestMapping(value = "/api/menu/{menuId}")
public String userInfo(@PathVariable("menuId") String menuId, HttpServletRequest request,
HttpServletResponse response, ModelMap modelMap) {
// 获得菜单详情
// 获得菜单的各级父菜单
return "menu";
}
}
| UTF-8 | Java | 6,433 | java | MenuController.java | Java | [
{
"context": ".RequestParam;\r\n\r\n/**\r\n * 系统菜单控制器\r\n * \r\n * @author zhangshuai\r\n * \r\n */\r\n@Controller\r\npublic class MenuControll",
"end": 1195,
"score": 0.9945471286773682,
"start": 1185,
"tag": "USERNAME",
"value": "zhangshuai"
}
] | null | [] | package net.yuan.nova.pis.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.yuan.nova.commons.SystemConstant;
import net.yuan.nova.core.shiro.vo.User;
import net.yuan.nova.core.vo.JsonVo;
import net.yuan.nova.core.vo.TreeNode;
import net.yuan.nova.pis.entity.PisMenuItem;
import net.yuan.nova.pis.entity.PisUserGroup;
import net.yuan.nova.pis.service.MenuItemService;
import net.yuan.nova.pis.service.PisUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 系统菜单控制器
*
* @author zhangshuai
*
*/
@Controller
public class MenuController {
protected final Logger log = LoggerFactory.getLogger(MenuController.class);
@Autowired
private MenuItemService menuItemService;
@Autowired
private PisUserService pisUserService;
/**
* 获得相应的菜单列表数据
*
* @param request
* @param response
* @param modelMap
* @return
*/
@RequestMapping(value = "/admin/menus")
public ModelMap menus(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
log.debug("获得菜单列表");
// 父节点的ID
String parentId = StringUtils.trimToEmpty(request.getParameter("id"));
if ("-1".equals(parentId)) {
parentId = null;
}
List<TreeNode<PisMenuItem>> list = menuItemService.findMenuTreeNodes(parentId,"");
return modelMap.addAttribute("menus", list);
}
/**
* 根据当前用户的权限获得相应的菜单列表数据
*
* @param request
* @param response
* @param modelMap
* @return
*/
@RequestMapping(value = "/admin/usermenus")
public ModelMap menuslevel(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
Subject currentUser = SecurityUtils.getSubject();
String menu = "";
// 判断登录是否成功
if (currentUser.isAuthenticated()) {
Session session = currentUser.getSession();
User user = (User) session.getAttribute(SystemConstant.SESSION_USER);
PisUserGroup pisUserGroup = pisUserService.getPisUserGroup(user.getUserId());
String type = null!=pisUserGroup?pisUserGroup.getType():" ";
String types=PisUserGroup.TYPE.salesman+","+PisUserGroup.TYPE.commissioner+","+PisUserGroup.TYPE.channelManager;
if(types.trim().indexOf(type)!=-1){
menu="xztjexcell";
}else if(PisUserGroup.TYPE.brokingFirm.toString().indexOf(type)!=-1){
menu="xztjexcell,userManager";
}
}
String parentId = StringUtils.trimToEmpty(request.getParameter("id"));
List<TreeNode<PisMenuItem>> list = null;
list = menuItemService.findMenuTreeNodes(parentId,menu);
return modelMap.addAttribute("menus", list);
}
/**
* 菜单
*
* @param request
* @param response
* @param modelMap
* @return
*/
@RequestMapping(value = "/admin/menu")
public String operateMenu(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap,
@RequestParam("edittype") String edittype) {
PisMenuItem menu = new PisMenuItem();
String privName = StringUtils.trimToEmpty(request.getParameter("privName"));
String menuCode = StringUtils.trimToEmpty(request.getParameter("menuCode"));
String url = StringUtils.trimToEmpty(request.getParameter("url"));
int sort = NumberUtils.toInt(StringUtils.trimToEmpty(request.getParameter("sort")), 1);
String comments = StringUtils.trimToEmpty(request.getParameter("comments"));
String parentMenuId = StringUtils.trimToEmpty(request.getParameter("parentMenuId"));
String menuItemId = StringUtils.trimToEmpty(request.getParameter("menuItemId"));
menu.setPrivName(privName);
menu.setMenuCode(menuCode);
menu.setUrl(url);
menu.setSort(sort);
menu.setComments(comments);
menu.setParentId(parentMenuId);
menu.setId(menuItemId);
JsonVo<PisMenuItem> jsonVo = new JsonVo<PisMenuItem>();
if ("add".equals(edittype)) {
log.debug("添加新菜单");
if (StringUtils.isBlank(menu.getPrivName())) {
jsonVo.putError("privName", "菜单文本不能为空");
}
if (StringUtils.isBlank(menu.getMenuCode())) {
jsonVo.putError("menuCode", "菜单名称不能为空");
}
if (jsonVo.validate()) {
modelMap.addAttribute("json", jsonVo);
modelMap.remove("menu");
} else {
modelMap.addAttribute("json", jsonVo);
modelMap.remove("menu");
}
} else if ("del".equals(edittype)) {
log.debug("删除菜单及相应的子菜单");
String ItemId = menu.getId();
if (StringUtils.isBlank(ItemId)) {
jsonVo.putError("id", "菜单ID不能为空");
}
jsonVo.setResult(menu);
modelMap.addAttribute("json", jsonVo);
modelMap.remove("menu");
if (jsonVo.validate()) {
menuItemService.deleteMenuItem(menu.getId());
}
} else {
log.debug("更新当前菜单");
String ItemId = menu.getId();
if (StringUtils.isBlank(ItemId)) {
jsonVo.putError("id", "菜单ID不能为空");
}
if (StringUtils.isBlank(menu.getPrivName())) {
jsonVo.putError("privName", "菜单文本不能为空");
}
if (StringUtils.isBlank(menu.getMenuCode())) {
jsonVo.putError("menuCode", "菜单名称不能为空");
}
jsonVo.setResult(menu);
modelMap.addAttribute("json", jsonVo);
modelMap.remove("menu");
if (jsonVo.validate()) {
menuItemService.updateMenuItem(menu);
}
}
return "menu";
}
/**
* 菜单详情
*
* @param request
* @param response
* @param modelMap
* @return
*/
@RequestMapping(value = "/api/menu/{menuId}")
public String userInfo(@PathVariable("menuId") String menuId, HttpServletRequest request,
HttpServletResponse response, ModelMap modelMap) {
// 获得菜单详情
// 获得菜单的各级父菜单
return "menu";
}
}
| 6,433 | 0.704963 | 0.703662 | 192 | 30.005209 | 25.171185 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.203125 | false | false | 13 |
f3662f2c99a1a768d285fb72e799884c9e35fcbe | 22,187,801,117,813 | 1637b42bfe66763990223d674aa470aa239a240b | /ttsd-point-service/src/main/java/com/tuotiansudai/point/service/SignInService.java | 14070463726602b86a22dceeec2b04141f13cdce | [] | no_license | haifeiforwork/tuotiansudai | https://github.com/haifeiforwork/tuotiansudai | 11feef3e42f02c3e590ca2b7c081f106b706f7da | 891fefef783a96f86c3283ce377ba18e80db0c81 | refs/heads/master | 2020-12-12T09:16:06.320000 | 2019-03-08T09:34:26 | 2019-03-08T09:34:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tuotiansudai.point.service;
import com.tuotiansudai.point.repository.dto.SignInPointDto;
public interface SignInService {
SignInPointDto signIn(String loginName);
boolean signInIsSuccess(String loginName);
SignInPointDto getLastSignIn(String loginName);
int getNextSignInPoint(String loginName);
int getSignInCount(String loginName);
}
| UTF-8 | Java | 377 | java | SignInService.java | Java | [] | null | [] | package com.tuotiansudai.point.service;
import com.tuotiansudai.point.repository.dto.SignInPointDto;
public interface SignInService {
SignInPointDto signIn(String loginName);
boolean signInIsSuccess(String loginName);
SignInPointDto getLastSignIn(String loginName);
int getNextSignInPoint(String loginName);
int getSignInCount(String loginName);
}
| 377 | 0.787798 | 0.787798 | 18 | 19.944445 | 22.785162 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 13 |
17240213a6f4c6d9575ff1cf8d3e0c5df34c9881 | 36,060,545,439,345 | 977d0a2fbc152296c040fcbdcbc61b575f903a4b | /gobblin-metrics/src/main/java/gobblin/metrics/metric/InnerMetric.java | c05a2bfd12d1cac7afb3b002db9a404d690392ed | [
"Apache-2.0",
"BSD-3-Clause",
"xpp",
"MIT"
] | permissive | pndaproject/gobblin | https://github.com/pndaproject/gobblin | 01b963e24e90dc1f91a348c42caf503cfe1812be | 506c4a519911b453412dad784f4bfb10e7e6a84a | refs/heads/develop | 2021-01-20T23:23:44.411000 | 2017-12-06T17:05:40 | 2017-12-06T17:05:40 | 62,383,333 | 1 | 8 | Apache-2.0 | true | 2017-12-06T17:05:41 | 2016-07-01T09:53:50 | 2017-04-19T08:15:44 | 2017-12-06T17:05:41 | 97,824 | 1 | 6 | 0 | Java | false | null | /*
* Copyright (C) 2014-2016 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
package gobblin.metrics.metric;
import com.codahale.metrics.Metric;
import gobblin.metrics.ContextAwareMetric;
/**
* Inner {@link Metric} used for reporting metrics one last time even after the user-facing wrapper has been
* garbage collected.
*/
public interface InnerMetric extends Metric {
/**
* @return the associated {@link ContextAwareMetric}.
*/
public ContextAwareMetric getContextAwareMetric();
}
| UTF-8 | Java | 940 | java | InnerMetric.java | Java | [] | null | [] | /*
* Copyright (C) 2014-2016 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
package gobblin.metrics.metric;
import com.codahale.metrics.Metric;
import gobblin.metrics.ContextAwareMetric;
/**
* Inner {@link Metric} used for reporting metrics one last time even after the user-facing wrapper has been
* garbage collected.
*/
public interface InnerMetric extends Metric {
/**
* @return the associated {@link ContextAwareMetric}.
*/
public ContextAwareMetric getContextAwareMetric();
}
| 940 | 0.744681 | 0.731915 | 31 | 29.32258 | 32.66584 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.290323 | false | false | 13 |
0532b58056d3ea90c1500d254bf05594d2395039 | 35,304,631,202,327 | a038096f0b4fc0969a484ce53298998b6e2aa092 | /CAR/ProjetStruts/src/metawebmodel/Entity.java | fb33f4d3d959254b7b2d074e87e29904f5778f8e | [] | no_license | youba/CARPRO | https://github.com/youba/CARPRO | e3f0ec4c30018852a4c990852dd097331b8772fb | 84a5e98e005d14839a8c43aa486eeed4189f145e | refs/heads/master | 2016-09-06T09:00:02.816000 | 2012-11-21T19:32:05 | 2012-11-21T19:32:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package metawebmodel;
import metawebmodel.tools.IVisiteurModel;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Entity</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link metawebmodel.Entity#getAtributes <em>Atributes</em>}</li>
* </ul>
* </p>
*
* @see metawebmodel.MetawebmodelPackage#getEntity()
* @model
* @generated
*/
public interface Entity extends DataType {
/**
* Returns the value of the '<em><b>Atributes</b></em>' containment reference list.
* The list contents are of type {@link metawebmodel.EntityAtribute}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Atributes</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Atributes</em>' containment reference list.
* @see metawebmodel.MetawebmodelPackage#getEntity_Atributes()
* @model containment="true"
* @generated
*/
EList<EntityAtribute> getAtributes();
/**
*
* @param visiteur
* @generated NOT
*/
public void accepte(IVisiteurModel visiteur);
} // Entity
| UTF-8 | Java | 1,279 | java | Entity.java | Java | [] | null | [] | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package metawebmodel;
import metawebmodel.tools.IVisiteurModel;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Entity</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link metawebmodel.Entity#getAtributes <em>Atributes</em>}</li>
* </ul>
* </p>
*
* @see metawebmodel.MetawebmodelPackage#getEntity()
* @model
* @generated
*/
public interface Entity extends DataType {
/**
* Returns the value of the '<em><b>Atributes</b></em>' containment reference list.
* The list contents are of type {@link metawebmodel.EntityAtribute}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Atributes</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Atributes</em>' containment reference list.
* @see metawebmodel.MetawebmodelPackage#getEntity_Atributes()
* @model containment="true"
* @generated
*/
EList<EntityAtribute> getAtributes();
/**
*
* @param visiteur
* @generated NOT
*/
public void accepte(IVisiteurModel visiteur);
} // Entity
| 1,279 | 0.653636 | 0.653636 | 52 | 23.596153 | 24.817225 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.519231 | false | false | 13 |
abdefb32775c18b9b93978caabd5dd4f0f5e45a8 | 21,157,008,955,586 | bfb75cff58924a548eb385ad77d3054f79715177 | /sandbox/src/main/java/ru/nc/pdtb6/sandbox/MyFirstProject.java | 3bc4fb9ed0f615594df1e405e21c84f8c1969027 | [
"Apache-2.0"
] | permissive | Ch-Natalia/java_pdtb6 | https://github.com/Ch-Natalia/java_pdtb6 | 656c6b0a79ee575e3bbea6b762c47f5fbdb60fdb | 2a3c3f53aedd789043fd851e4ddd72c4d4cc81f0 | refs/heads/master | 2020-07-07T18:47:39.138000 | 2019-08-26T20:12:32 | 2019-08-26T20:12:32 | 203,443,506 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.nc.pdtb6.sandbox;
public class MyFirstProject {
public static void main(String[] args) {
System.out.println("Hello, World");
Point a = new Point();
Point b = new Point();
a.distance(b);
b.distance(a);
distance(a, b);
}
public static void distance(Point a, Point b) {
a.x = 2;
a.y = 3;
b.x = 4;
b.y = 12;
int k1 = a.x - b.x;
if (k1 < 0) {
k1 = k1 * (-1);
}
int k2 = a.y - b.y;
if (k2 < 0) {
k2 = k2 * (-1);
}
int D = (k1 * k1) + (k2 * k2);
double d = Math.sqrt(D);
System.out.println(d);
}
} | UTF-8 | Java | 699 | java | MyFirstProject.java | Java | [] | null | [] | package ru.nc.pdtb6.sandbox;
public class MyFirstProject {
public static void main(String[] args) {
System.out.println("Hello, World");
Point a = new Point();
Point b = new Point();
a.distance(b);
b.distance(a);
distance(a, b);
}
public static void distance(Point a, Point b) {
a.x = 2;
a.y = 3;
b.x = 4;
b.y = 12;
int k1 = a.x - b.x;
if (k1 < 0) {
k1 = k1 * (-1);
}
int k2 = a.y - b.y;
if (k2 < 0) {
k2 = k2 * (-1);
}
int D = (k1 * k1) + (k2 * k2);
double d = Math.sqrt(D);
System.out.println(d);
}
} | 699 | 0.420601 | 0.389127 | 34 | 19.588236 | 14.035915 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617647 | false | false | 13 |
bc0f24c2d354fb90fd1017070b9bcb6ad1b16b61 | 8,959,301,833,488 | f63d18f59cb370fd5ad037ed07cf5dba864c2a63 | /Hzsever/src/main/java/htht/system/ocean/model/UimIssueRole.java | 658a14a903e53061388b7a47f55138d433918e5b | [] | no_license | sengeiou/HzServer | https://github.com/sengeiou/HzServer | db9402604fb35f4e6638828974dfe4982b6fe1d2 | cce2d6a1bef9463ba4e92d081a2930851f8a6eab | refs/heads/master | 2020-05-16T02:01:36.338000 | 2018-10-15T09:05:43 | 2018-10-15T09:05:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package htht.system.ocean.model;
import javax.persistence.*;
@Table(name = "UIM_ISSUE_ROLE")
public class UimIssueRole {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@Column(name = "ROLE_NAME")
private String roleName;
@Column(name = "MEMO")
private String memo;
@Column(name = "ORDER_NUM")
private Short orderNum;
@Column(name = "ISLOCK")
private Short islock;
/**
* @return ID
*/
public String getId() {
return id;
}
/**
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* @return ROLE_NAME
*/
public String getRoleName() {
return roleName;
}
/**
* @param roleName
*/
public void setRoleName(String roleName) {
this.roleName = roleName;
}
/**
* @return MEMO
*/
public String getMemo() {
return memo;
}
/**
* @param memo
*/
public void setMemo(String memo) {
this.memo = memo;
}
/**
* @return ORDER_NUM
*/
public Short getOrderNum() {
return orderNum;
}
/**
* @param orderNum
*/
public void setOrderNum(Short orderNum) {
this.orderNum = orderNum;
}
/**
* @return ISLOCK
*/
public Short getIslock() {
return islock;
}
/**
* @param islock
*/
public void setIslock(Short islock) {
this.islock = islock;
}
} | UTF-8 | Java | 1,535 | java | UimIssueRole.java | Java | [] | null | [] | package htht.system.ocean.model;
import javax.persistence.*;
@Table(name = "UIM_ISSUE_ROLE")
public class UimIssueRole {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@Column(name = "ROLE_NAME")
private String roleName;
@Column(name = "MEMO")
private String memo;
@Column(name = "ORDER_NUM")
private Short orderNum;
@Column(name = "ISLOCK")
private Short islock;
/**
* @return ID
*/
public String getId() {
return id;
}
/**
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* @return ROLE_NAME
*/
public String getRoleName() {
return roleName;
}
/**
* @param roleName
*/
public void setRoleName(String roleName) {
this.roleName = roleName;
}
/**
* @return MEMO
*/
public String getMemo() {
return memo;
}
/**
* @param memo
*/
public void setMemo(String memo) {
this.memo = memo;
}
/**
* @return ORDER_NUM
*/
public Short getOrderNum() {
return orderNum;
}
/**
* @param orderNum
*/
public void setOrderNum(Short orderNum) {
this.orderNum = orderNum;
}
/**
* @return ISLOCK
*/
public Short getIslock() {
return islock;
}
/**
* @param islock
*/
public void setIslock(Short islock) {
this.islock = islock;
}
} | 1,535 | 0.523127 | 0.523127 | 93 | 15.516129 | 13.179989 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.182796 | false | false | 13 |
5e5e18aa4fca63b10a92c691cf8039ff5a6ef59b | 31,533,649,917,140 | 3262eeda1110cdd17ff294be8c783b543f87f0f0 | /src/pepmhc/affy/AffinityCache.java | e0c6d9fc678a7e8567238387dda13fe0a0ffc2bc | [
"Apache-2.0"
] | permissive | tipplerow/pepmhc | https://github.com/tipplerow/pepmhc | 06cffb6d9c02ceae4faa79e823309ad08f641ec5 | fd030de9a72a94ce896da6cbcfa7e962084a4a38 | refs/heads/master | 2021-07-04T07:48:00.392000 | 2020-09-15T16:29:08 | 2020-09-15T16:29:08 | 168,204,813 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pepmhc.affy;
import jam.app.JamProperties;
import jam.util.PairKeyTable;
import jene.hla.Allele;
import pepmhc.bind.BindCache;
/**
* Maintains an in-memory cache of affinity records backed by a
* persistent database store.
*/
public final class AffinityCache extends BindCache<AffinityRecord> {
private static final PairKeyTable<AffinityMethod, Allele, AffinityCache> instances = PairKeyTable.hash();
private AffinityCache(AffinityTable table, AffinityPredictor predictor, Allele allele) {
super(table, predictor, allele);
}
/**
* Name of the environment variable that specifies the directory
* containing the persistent database store. The system property
* {@code pepmhc.affinityCache} will take precedence if both are
* specified.
*/
public static final String CACHE_DIRECTORY_ENV = "PEPMHC_AFFINITY_CACHE";
/**
* Name of the system property that specifies the directory
* containing the persistent database store.
*/
public static final String CACHE_DIRECTORY_PROPERTY = "pepmhc.affinityCache";
/**
* Returns the name of the directory containing the persistent
* affinity database.
*
* @return the name of the directory containing the persistent
* affinity database.
*/
public static String cacheDir() {
return JamProperties.resolve(CACHE_DIRECTORY_PROPERTY, CACHE_DIRECTORY_ENV, null);
}
/**
* Returns the affinity cache for a given allele and prediction
* method.
*
* @param method the affinity prediction method.
*
* @param allele the allele of the binding MHC molecule.
*
* @return the affinity cache for the specified allele and
* prediction method.
*/
public static synchronized AffinityCache instance(AffinityMethod method, Allele allele) {
AffinityCache instance = instances.get(method, allele);
if (instance == null)
instance = newInstance(method, allele);
return instance;
}
private static AffinityCache newInstance(AffinityMethod method, Allele allele) {
AffinityCache instance =
new AffinityCache(AffinityTable.create(method, allele), method.getPredictor(), allele);
instances.put(method, allele, instance);
return instance;
}
/**
* Clears this cache: removes all cached records from memory and
* removes this cache from the underlying instance map.
*/
@Override public void clear() {
super.clear();
synchronized (instances) {
instances.remove(getMethod(), getAllele());
}
}
@Override public AffinityMethod getMethod() {
return (AffinityMethod) super.getMethod();
}
@Override public Class getRecordClass() {
return AffinityRecord.class;
}
}
| UTF-8 | Java | 2,849 | java | AffinityCache.java | Java | [] | null | [] |
package pepmhc.affy;
import jam.app.JamProperties;
import jam.util.PairKeyTable;
import jene.hla.Allele;
import pepmhc.bind.BindCache;
/**
* Maintains an in-memory cache of affinity records backed by a
* persistent database store.
*/
public final class AffinityCache extends BindCache<AffinityRecord> {
private static final PairKeyTable<AffinityMethod, Allele, AffinityCache> instances = PairKeyTable.hash();
private AffinityCache(AffinityTable table, AffinityPredictor predictor, Allele allele) {
super(table, predictor, allele);
}
/**
* Name of the environment variable that specifies the directory
* containing the persistent database store. The system property
* {@code pepmhc.affinityCache} will take precedence if both are
* specified.
*/
public static final String CACHE_DIRECTORY_ENV = "PEPMHC_AFFINITY_CACHE";
/**
* Name of the system property that specifies the directory
* containing the persistent database store.
*/
public static final String CACHE_DIRECTORY_PROPERTY = "pepmhc.affinityCache";
/**
* Returns the name of the directory containing the persistent
* affinity database.
*
* @return the name of the directory containing the persistent
* affinity database.
*/
public static String cacheDir() {
return JamProperties.resolve(CACHE_DIRECTORY_PROPERTY, CACHE_DIRECTORY_ENV, null);
}
/**
* Returns the affinity cache for a given allele and prediction
* method.
*
* @param method the affinity prediction method.
*
* @param allele the allele of the binding MHC molecule.
*
* @return the affinity cache for the specified allele and
* prediction method.
*/
public static synchronized AffinityCache instance(AffinityMethod method, Allele allele) {
AffinityCache instance = instances.get(method, allele);
if (instance == null)
instance = newInstance(method, allele);
return instance;
}
private static AffinityCache newInstance(AffinityMethod method, Allele allele) {
AffinityCache instance =
new AffinityCache(AffinityTable.create(method, allele), method.getPredictor(), allele);
instances.put(method, allele, instance);
return instance;
}
/**
* Clears this cache: removes all cached records from memory and
* removes this cache from the underlying instance map.
*/
@Override public void clear() {
super.clear();
synchronized (instances) {
instances.remove(getMethod(), getAllele());
}
}
@Override public AffinityMethod getMethod() {
return (AffinityMethod) super.getMethod();
}
@Override public Class getRecordClass() {
return AffinityRecord.class;
}
}
| 2,849 | 0.677782 | 0.677782 | 93 | 29.623655 | 29.612885 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.408602 | false | false | 13 |
c5984cb27f71b5164df6ededa0f677a2b1f186c6 | 2,671,469,695,029 | 11a7f36f51f5040391521bfc67e17103f32a0034 | /src/Util/CharacterEscape.java | 3346cb601cc7c25187af800f55cd4d936b5d47fc | [] | no_license | jobrob/FYP | https://github.com/jobrob/FYP | fcec453455126b9e0e6ca2c3be689988de1717e0 | f073cf24fdac9b711ee299855f26b9224e4b06cc | refs/heads/master | 2021-09-11T13:22:51.950000 | 2018-04-07T16:10:54 | 2018-04-07T16:10:54 | 109,271,150 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Util;
import java.util.*;
public class CharacterEscape
{
/**
* Takes a string an returns a string that has its special characters replaced by the escaped values
* @return
*/
public static String escapeHtml(String input)
{
HashMap<String, String> hashmap = new HashMap<>();
hashmap.put("\"",""");
hashmap.put("&","&");
hashmap.put("<","<");
hashmap.put(">",">");
StringBuilder newInput = new StringBuilder();
for(int i = 0;i <input.length(); i++)
{
if(hashmap.containsKey("" + input.charAt(i)))
{
StringBuilder replacement = new StringBuilder(hashmap.get("" + input.charAt(i)));
String[] parts = input.split("" + input.charAt(i));
if(parts.length>0)
{
newInput.append(parts[0]);
for(int j = 1; j<parts.length; j++)
{
newInput.append(replacement.append(parts[j]));
}
}
else
{
newInput.append(replacement);
}
}
}
if(newInput.length() == 0)
{
newInput = new StringBuilder(input);
}
return newInput.toString();
}
} | UTF-8 | Java | 1,044 | java | CharacterEscape.java | Java | [] | null | [] | package Util;
import java.util.*;
public class CharacterEscape
{
/**
* Takes a string an returns a string that has its special characters replaced by the escaped values
* @return
*/
public static String escapeHtml(String input)
{
HashMap<String, String> hashmap = new HashMap<>();
hashmap.put("\"",""");
hashmap.put("&","&");
hashmap.put("<","<");
hashmap.put(">",">");
StringBuilder newInput = new StringBuilder();
for(int i = 0;i <input.length(); i++)
{
if(hashmap.containsKey("" + input.charAt(i)))
{
StringBuilder replacement = new StringBuilder(hashmap.get("" + input.charAt(i)));
String[] parts = input.split("" + input.charAt(i));
if(parts.length>0)
{
newInput.append(parts[0]);
for(int j = 1; j<parts.length; j++)
{
newInput.append(replacement.append(parts[j]));
}
}
else
{
newInput.append(replacement);
}
}
}
if(newInput.length() == 0)
{
newInput = new StringBuilder(input);
}
return newInput.toString();
}
} | 1,044 | 0.611111 | 0.606322 | 44 | 22.75 | 23.005064 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.090909 | false | false | 13 |
5da5a927d856deaa7bb327031eb5ce29768ebd8f | 28,793,460,777,634 | 6700b25d187a172a52ccddbc02a17d6e0485c69a | /src/test/java/io/qdivision/demo/bowling/services/GameServiceTest.java | 74e7330b36eac7b3f6dd78b5d6d4000d949f918e | [] | no_license | jwmorrow1s/bowling-api | https://github.com/jwmorrow1s/bowling-api | 139be652fd581798ec10bc7eb5247db8edfb695a | d050f4fec9c35a370c4e8725197465f2b8f95f7b | refs/heads/master | 2020-03-31T13:19:52.379000 | 2018-10-09T12:57:36 | 2018-10-09T12:57:36 | 152,251,163 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.qdivision.demo.bowling.services;
import io.qdivision.demo.bowling.models.Game;
import io.qdivision.demo.bowling.models.Player;
import io.qdivision.demo.bowling.repositories.GameRepository;
import io.qdivision.demo.bowling.utils.GameStatus;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.ResponseEntity;
import java.sql.SQLOutput;
import java.util.List;
@RunWith(MockitoJUnitRunner.class)
public class GameServiceTest {
@Mock
private GameRepository gameRepository;
@Test
public void givenGameNotStarted_whenGetScoreCard_thenReturnGame(){
final var gameService = new GameService(gameRepository);
final var game = new Game();
Mockito.when(gameRepository.getScoreCard())
.thenReturn(game);
Assert.assertEquals(gameService.getScoreCard(), game);
Assert.assertEquals(game.getGameStatus(), GameStatus.INITIALIZED);
}
@Test
public void givenGameHasStarted_whenPlayerAdded_thenReturnPlayersWithNewPlayerAdded(){
final var gameService = new GameService(gameRepository);
final var name = "Morpheus";
final var game = new Game();
final Player player = new Player();
player.setName(name);
game.addPlayer(player);
Mockito.when(gameRepository.addPlayer(player))
.thenReturn(game);
final Game response = gameService.addPlayer(player);
Assert.assertEquals(gameService.addPlayer(player), game);
}
@Test
public void givenPlayerExists_whenRemovePlayer_thenRemovePlayer(){
final var gameService= new GameService(gameRepository);
final int id = 1;
final String name = "Morpheus";
final var game = new Game();
final var player = new Player();
player.setName(name);
Mockito.when(gameRepository.removePlayer(id)).thenReturn(game);
Assert.assertNotNull(gameRepository.removePlayer(id));
}
@Test
public void givenGameNotStarted_whenStartGame_thenReturnGame(){
final var gameService = new GameService(gameRepository);
final var game = new Game();
final var incomingGameStatus = GameStatus.IN_PROGRESS;
game.setGameStatus(incomingGameStatus);
Mockito.when(gameRepository.gameTimeStarted(incomingGameStatus)).thenReturn(game);
Game response = gameService.gameTimeStarted(incomingGameStatus);
Assert.assertTrue(response instanceof Game);
}
@Test
public void givenPlayerExists_whenPostAddScoreToPlayer_thenReturnTypeGame() {
final var gameService = new GameService(gameRepository);
final var game = new Game();
final int id = 1;
final int score = 5;
final int frameNumber = 1;
Mockito.when(gameRepository.addScore(id, frameNumber, score)).thenReturn(game);
Game response = gameService.addScore(id, frameNumber, score);
Assert.assertTrue(response instanceof Game);
}
@Test
public void givenPlayerExistsAndOneScoreAlreadyExists_whenPostAddScoreToPlayer_thenReturnTypeGame() {
final var gameService = new GameService(gameRepository);
final var game = new Game();
final int id = 1;
final int score = 5;
final int frameNumber = 1;
Mockito.when(gameRepository.addScore(id, frameNumber, score)).thenReturn(game);
Game response = gameService.addScore(id, frameNumber, score);
Assert.assertTrue(response instanceof Game);
}
}
| UTF-8 | Java | 3,657 | java | GameServiceTest.java | Java | [] | null | [] | package io.qdivision.demo.bowling.services;
import io.qdivision.demo.bowling.models.Game;
import io.qdivision.demo.bowling.models.Player;
import io.qdivision.demo.bowling.repositories.GameRepository;
import io.qdivision.demo.bowling.utils.GameStatus;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.ResponseEntity;
import java.sql.SQLOutput;
import java.util.List;
@RunWith(MockitoJUnitRunner.class)
public class GameServiceTest {
@Mock
private GameRepository gameRepository;
@Test
public void givenGameNotStarted_whenGetScoreCard_thenReturnGame(){
final var gameService = new GameService(gameRepository);
final var game = new Game();
Mockito.when(gameRepository.getScoreCard())
.thenReturn(game);
Assert.assertEquals(gameService.getScoreCard(), game);
Assert.assertEquals(game.getGameStatus(), GameStatus.INITIALIZED);
}
@Test
public void givenGameHasStarted_whenPlayerAdded_thenReturnPlayersWithNewPlayerAdded(){
final var gameService = new GameService(gameRepository);
final var name = "Morpheus";
final var game = new Game();
final Player player = new Player();
player.setName(name);
game.addPlayer(player);
Mockito.when(gameRepository.addPlayer(player))
.thenReturn(game);
final Game response = gameService.addPlayer(player);
Assert.assertEquals(gameService.addPlayer(player), game);
}
@Test
public void givenPlayerExists_whenRemovePlayer_thenRemovePlayer(){
final var gameService= new GameService(gameRepository);
final int id = 1;
final String name = "Morpheus";
final var game = new Game();
final var player = new Player();
player.setName(name);
Mockito.when(gameRepository.removePlayer(id)).thenReturn(game);
Assert.assertNotNull(gameRepository.removePlayer(id));
}
@Test
public void givenGameNotStarted_whenStartGame_thenReturnGame(){
final var gameService = new GameService(gameRepository);
final var game = new Game();
final var incomingGameStatus = GameStatus.IN_PROGRESS;
game.setGameStatus(incomingGameStatus);
Mockito.when(gameRepository.gameTimeStarted(incomingGameStatus)).thenReturn(game);
Game response = gameService.gameTimeStarted(incomingGameStatus);
Assert.assertTrue(response instanceof Game);
}
@Test
public void givenPlayerExists_whenPostAddScoreToPlayer_thenReturnTypeGame() {
final var gameService = new GameService(gameRepository);
final var game = new Game();
final int id = 1;
final int score = 5;
final int frameNumber = 1;
Mockito.when(gameRepository.addScore(id, frameNumber, score)).thenReturn(game);
Game response = gameService.addScore(id, frameNumber, score);
Assert.assertTrue(response instanceof Game);
}
@Test
public void givenPlayerExistsAndOneScoreAlreadyExists_whenPostAddScoreToPlayer_thenReturnTypeGame() {
final var gameService = new GameService(gameRepository);
final var game = new Game();
final int id = 1;
final int score = 5;
final int frameNumber = 1;
Mockito.when(gameRepository.addScore(id, frameNumber, score)).thenReturn(game);
Game response = gameService.addScore(id, frameNumber, score);
Assert.assertTrue(response instanceof Game);
}
}
| 3,657 | 0.701395 | 0.69948 | 109 | 32.550457 | 27.574581 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.651376 | false | false | 13 |
10eae1f6ed2ec8afb239dce48dfe8cefc2806a96 | 8,246,337,246,683 | 05c76c34eca5753508b79cd488a8486994868b5c | /core/src/main/java/equalshash/Person.java | 32303b98e44e14bbd2fbc75de7d6df9c3d011ca9 | [
"Apache-2.0"
] | permissive | aw3s0me/java-tuts | https://github.com/aw3s0me/java-tuts | 3fd56a2a0d260708a00dc4efdf3420b5669906e4 | b7a7dbef1f2611c6c66da62630dd72b23eff5581 | refs/heads/master | 2017-12-11T15:57:01.747000 | 2017-06-20T19:05:03 | 2017-06-20T19:05:03 | 78,959,204 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package equalshash;
import java.util.Objects;
/**
* Created by korovin on 6/13/2017.
*/
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Rules:
* Make sure to override equals(Object) so our method is always called.
* Include a self and null check for an early return in simple edge cases.
* Use getClass to allow subtypes their own implementation (but no comparison across subtypes) or use instanceof and make equals final (and subtypes can equal).
* Compare the desired fields using Objects.equals.
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
// self check
if (this == o)
return true;
// null check
if (o == null)
return false;
// type check and cast. USE THIS METHOD, because INSTANCEOF PASSES ALSO SUBTYPES
if (getClass() != o.getClass())
return false;
Person person = (Person) o;
// field comparison (using Guava equals method)
return Objects.equals(firstName, person.firstName)
&& Objects.equals(lastName, person.lastName);
}
}
| UTF-8 | Java | 1,634 | java | Person.java | Java | [
{
"context": "ash;\n\nimport java.util.Objects;\n\n/**\n * Created by korovin on 6/13/2017.\n */\npublic class Person {\n priva",
"end": 73,
"score": 0.997648298740387,
"start": 66,
"tag": "USERNAME",
"value": "korovin"
}
] | null | [] | package equalshash;
import java.util.Objects;
/**
* Created by korovin on 6/13/2017.
*/
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Rules:
* Make sure to override equals(Object) so our method is always called.
* Include a self and null check for an early return in simple edge cases.
* Use getClass to allow subtypes their own implementation (but no comparison across subtypes) or use instanceof and make equals final (and subtypes can equal).
* Compare the desired fields using Objects.equals.
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
// self check
if (this == o)
return true;
// null check
if (o == null)
return false;
// type check and cast. USE THIS METHOD, because INSTANCEOF PASSES ALSO SUBTYPES
if (getClass() != o.getClass())
return false;
Person person = (Person) o;
// field comparison (using Guava equals method)
return Objects.equals(firstName, person.firstName)
&& Objects.equals(lastName, person.lastName);
}
}
| 1,634 | 0.618115 | 0.613831 | 58 | 27.172413 | 28.365921 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.327586 | false | false | 13 |
f7c666aea00148e0d692d22126dcaef609052e5d | 32,968,169,011,454 | 459035782e96a17c623a062a88c581a1780921ae | /ego_manage/src/main/java/com/ego/manage/controller/PageController.java | ecd3f8a3abcdb8b55501b48eb9c345e522b1bd0b | [] | no_license | yueqianhan/ego_parent | https://github.com/yueqianhan/ego_parent | ea3a1916f72520bb4382a1dc12e3aebcca4e893d | 1bf6bbf7481c08d2a101b63d3a4c17fba98ced8f | refs/heads/master | 2022-05-10T00:34:48.720000 | 2019-10-28T13:37:01 | 2019-10-28T13:37:01 | 218,054,503 | 0 | 0 | null | false | 2022-06-21T02:07:56 | 2019-10-28T13:35:46 | 2019-10-28T13:38:14 | 2022-06-21T02:07:53 | 3,602 | 0 | 0 | 4 | CSS | false | false | package com.ego.manage.controller;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author hanyueqian
* @date 2019/9/20 0020-下午 16:21
*/
@Controller
public class PageController
{
/**
* 显示页面控制器
* @return
*/
@RequestMapping("/")
public String welcome()
{
return "index";
}
@RequestMapping("/{page}")
public String showPage(@PathVariable String page)
{
return page;
}
@RequestMapping("/rest/page/item-edit")
public String showItemUpdate()
{
return "item-edit";
}
}
| UTF-8 | Java | 756 | java | PageController.java | Java | [
{
"context": "eb.bind.annotation.RequestMapping;\n\n/**\n * @author hanyueqian\n * @date 2019/9/20 0020-下午 16:21\n */\n@Controller\n",
"end": 282,
"score": 0.9993515014648438,
"start": 272,
"tag": "USERNAME",
"value": "hanyueqian"
}
] | null | [] | package com.ego.manage.controller;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author hanyueqian
* @date 2019/9/20 0020-下午 16:21
*/
@Controller
public class PageController
{
/**
* 显示页面控制器
* @return
*/
@RequestMapping("/")
public String welcome()
{
return "index";
}
@RequestMapping("/{page}")
public String showPage(@PathVariable String page)
{
return page;
}
@RequestMapping("/rest/page/item-edit")
public String showItemUpdate()
{
return "item-edit";
}
}
| 756 | 0.659892 | 0.639566 | 36 | 19.5 | 18.249048 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 13 |
1a18b62c88d2a230190d369f349c975cb01ab7b0 | 23,871,428,255,076 | ebc5be5c0334fbaea5435a6d36c9c96dd9c570eb | /melon-admin/src/main/java/org/tieland/melon/admin/common/ClientResultBuilder.java | 022ab216d1ed49b61ccd8713a3641a72c5f2349a | [] | no_license | moutainhigh/melon | https://github.com/moutainhigh/melon | 04ea26c5759d1f58fda286f7971612b831726d0c | 5e4e3a6f3af91141cb4e8f885cdbba699ed469d3 | refs/heads/master | 2022-07-30T12:32:56.386000 | 2020-05-21T09:36:49 | 2020-05-21T09:36:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.tieland.melon.admin.common;
/**
* 接口返回Builder
* @author zhouxiang
* @date 2018/6/20 8:30
*/
public final class ClientResultBuilder<T> {
private Integer code;
private T data;
private String message = GlobalCodeEnum.SUCCESS.getMessage();
public ClientResultBuilder<T> success(){
this.code = GlobalCodeEnum.SUCCESS.getCode();
return this;
}
public ClientResultBuilder<T> success(final T data){
this.code = GlobalCodeEnum.SUCCESS.getCode();
this.data = data;
return this;
}
public ClientResultBuilder<T> error(final Integer code, final String message){
this.code = code;
this.message = message;
return this;
}
public ClientResultBuilder<T> error(GlobalCodeEnum codeEnum){
this.code = codeEnum.getCode();
this.message = codeEnum.getMessage();
return this;
}
public ClientResult<T> build(){
ClientResult result = new ClientResult();
result.setCode(code);
result.setMessage(message);
if(GlobalCodeEnum.SUCCESS.getCode().equals(code)){
if(data!=null){
result.setData(data);
}
}else{
result.setMessage(message);
}
return result;
}
}
| UTF-8 | Java | 1,307 | java | ClientResultBuilder.java | Java | [
{
"context": "melon.admin.common;\n\n/**\n * 接口返回Builder\n * @author zhouxiang\n * @date 2018/6/20 8:30\n */\npublic final class Cl",
"end": 80,
"score": 0.9905985593795776,
"start": 71,
"tag": "USERNAME",
"value": "zhouxiang"
}
] | null | [] | package org.tieland.melon.admin.common;
/**
* 接口返回Builder
* @author zhouxiang
* @date 2018/6/20 8:30
*/
public final class ClientResultBuilder<T> {
private Integer code;
private T data;
private String message = GlobalCodeEnum.SUCCESS.getMessage();
public ClientResultBuilder<T> success(){
this.code = GlobalCodeEnum.SUCCESS.getCode();
return this;
}
public ClientResultBuilder<T> success(final T data){
this.code = GlobalCodeEnum.SUCCESS.getCode();
this.data = data;
return this;
}
public ClientResultBuilder<T> error(final Integer code, final String message){
this.code = code;
this.message = message;
return this;
}
public ClientResultBuilder<T> error(GlobalCodeEnum codeEnum){
this.code = codeEnum.getCode();
this.message = codeEnum.getMessage();
return this;
}
public ClientResult<T> build(){
ClientResult result = new ClientResult();
result.setCode(code);
result.setMessage(message);
if(GlobalCodeEnum.SUCCESS.getCode().equals(code)){
if(data!=null){
result.setData(data);
}
}else{
result.setMessage(message);
}
return result;
}
}
| 1,307 | 0.61047 | 0.602771 | 54 | 23.055555 | 20.970364 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false | 13 |
08d9dd80d10c9d4e240d24a3b9afa2ae94894625 | 33,560,874,474,787 | 19f7e40c448029530d191a262e5215571382bf9f | /decompiled/instagram/sources/p000X/C25741Ac.java | 3a9c61aaa0266145d97b02e46e455012f9ae7779 | [] | no_license | stanvanrooy/decompiled-instagram | https://github.com/stanvanrooy/decompiled-instagram | c1fb553c52e98fd82784a3a8a17abab43b0f52eb | 3091a40af7accf6c0a80b9dda608471d503c4d78 | refs/heads/master | 2022-12-07T22:31:43.155000 | 2020-08-26T03:42:04 | 2020-08-26T03:42:04 | 283,347,288 | 18 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package p000X;
/* renamed from: X.1Ac reason: invalid class name and case insensitive filesystem */
public final class C25741Ac implements Runnable {
public final /* synthetic */ AnonymousClass1AZ A00;
public C25741Ac(AnonymousClass1AZ r1) {
this.A00 = r1;
}
public final void run() {
AnonymousClass1AZ r1 = this.A00;
if ((r1.A01 & 1) != 0) {
r1.A0b(0);
}
AnonymousClass1AZ r12 = this.A00;
if ((r12.A01 & 4096) != 0) {
r12.A0b(108);
}
AnonymousClass1AZ r0 = this.A00;
r0.A0R = false;
r0.A01 = 0;
}
}
| UTF-8 | Java | 628 | java | C25741Ac.java | Java | [] | null | [] | package p000X;
/* renamed from: X.1Ac reason: invalid class name and case insensitive filesystem */
public final class C25741Ac implements Runnable {
public final /* synthetic */ AnonymousClass1AZ A00;
public C25741Ac(AnonymousClass1AZ r1) {
this.A00 = r1;
}
public final void run() {
AnonymousClass1AZ r1 = this.A00;
if ((r1.A01 & 1) != 0) {
r1.A0b(0);
}
AnonymousClass1AZ r12 = this.A00;
if ((r12.A01 & 4096) != 0) {
r12.A0b(108);
}
AnonymousClass1AZ r0 = this.A00;
r0.A0R = false;
r0.A01 = 0;
}
}
| 628 | 0.558917 | 0.457006 | 24 | 25.166666 | 20.649187 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 13 |
a396261d67e4c5ab226e0a392eca92ffccfa7a02 | 9,457,518,007,717 | 11e1feb02aba32524d6d7a24dfca53903b43112e | /Testing/src/test.java | e45cf6a04881996bfdc14cfdc07214e0ceda61b6 | [] | no_license | skuchibh/IdeaProjects | https://github.com/skuchibh/IdeaProjects | 405aa9a3c93fa45597137957ba264f95eebfe9e3 | 4f5030e878e955dcf1940f1ff64eef4ec8e2b490 | refs/heads/master | 2021-01-23T12:47:25.008000 | 2017-06-02T20:24:45 | 2017-06-02T20:24:45 | 93,200,693 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in * Actual solution is at the top
*
* @author Maverickk
*/
class test {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
static char[][] maze;
static boolean[][] visited;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
static int r, c, kk,ticker,tttt;
private static int counta, countl, counti, countz, countw, counte;static String ttt;
static ArrayList<String> ansarray = new ArrayList<String>();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int t = in.nextInt();
for (kk = 0; kk < t; kk++) {
r = in.nextInt();
c = in.nextInt();
maze = new char[r + 2][c + 2];
visited = new boolean[r + 2][c + 2];
for (int i = 1; i <= r; i++) {
String temp = in.next();
for (int j = 1; j <= c; j++) {
maze[i][j] = temp.charAt(j - 1);
}
}
if (maze[1][1] == 'A') counta += 1;
if (maze[1][1] == 'L') countl += 1;
if (maze[1][1] == 'I') counti += 1;
if (maze[1][1] == 'Z') countz += 1;
if (maze[1][1] == 'W') countw += 1;
if (maze[1][1] == 'E') counte += 1;
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
if (!visited[i][j]) {
tttt=dfs(i, j, out, kk);
}
}
}
if (tttt == 1) {
ansarray.add(TaskA.kk, "YES");
}
if (kk > 0 && ansarray.get(kk) != null)
ansarray.add(kk, "NO");
else if (ansarray.isEmpty()) {
ansarray.add(kk, "NO");
}
}
for (int h = 0; h < ansarray.size()-1; h++) {
System.out.println(ansarray.get(h));
}
}
static int dfs(int i, int j, PrintWriter out, int kk) {
visited[i][j] = true;
ttt = null;
for (int z = 0; z < 4; z++) {
int xx = i + dx[z];
int yy = j + dy[z];
if (xx > 0 && yy > 0 && xx <= r && yy <= c && !visited[xx][yy]) {
if (maze[xx][yy] == 'A') counta += 1;
if (maze[xx][yy] == 'L') countl += 1;
if (maze[xx][yy] == 'I') counti += 1;
if (maze[xx][yy] == 'Z') countz += 1;
if (maze[xx][yy] == 'W') countw += 1;
if (maze[xx][yy] == 'E') counte += 1;
//System.out.println("Z="+counta);
dfs(xx, yy, out, kk);
}
if (visited[xx][yy]) {
if (counta > 0 && countl >= 4 && counti > 0 && countz >= 2 && countw > 0 && counte > 0) {
ticker = 1;
}
}
}
return ticker;
} }
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| UTF-8 | Java | 4,037 | java | test.java | Java | [
{
"context": "g-in * Actual solution is at the top\n *\n * @author Maverickk\n */\nclass test {\n public static void main(Stri",
"end": 171,
"score": 0.8577058911323547,
"start": 162,
"tag": "NAME",
"value": "Maverickk"
}
] | null | [] | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in * Actual solution is at the top
*
* @author Maverickk
*/
class test {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
static char[][] maze;
static boolean[][] visited;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
static int r, c, kk,ticker,tttt;
private static int counta, countl, counti, countz, countw, counte;static String ttt;
static ArrayList<String> ansarray = new ArrayList<String>();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int t = in.nextInt();
for (kk = 0; kk < t; kk++) {
r = in.nextInt();
c = in.nextInt();
maze = new char[r + 2][c + 2];
visited = new boolean[r + 2][c + 2];
for (int i = 1; i <= r; i++) {
String temp = in.next();
for (int j = 1; j <= c; j++) {
maze[i][j] = temp.charAt(j - 1);
}
}
if (maze[1][1] == 'A') counta += 1;
if (maze[1][1] == 'L') countl += 1;
if (maze[1][1] == 'I') counti += 1;
if (maze[1][1] == 'Z') countz += 1;
if (maze[1][1] == 'W') countw += 1;
if (maze[1][1] == 'E') counte += 1;
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
if (!visited[i][j]) {
tttt=dfs(i, j, out, kk);
}
}
}
if (tttt == 1) {
ansarray.add(TaskA.kk, "YES");
}
if (kk > 0 && ansarray.get(kk) != null)
ansarray.add(kk, "NO");
else if (ansarray.isEmpty()) {
ansarray.add(kk, "NO");
}
}
for (int h = 0; h < ansarray.size()-1; h++) {
System.out.println(ansarray.get(h));
}
}
static int dfs(int i, int j, PrintWriter out, int kk) {
visited[i][j] = true;
ttt = null;
for (int z = 0; z < 4; z++) {
int xx = i + dx[z];
int yy = j + dy[z];
if (xx > 0 && yy > 0 && xx <= r && yy <= c && !visited[xx][yy]) {
if (maze[xx][yy] == 'A') counta += 1;
if (maze[xx][yy] == 'L') countl += 1;
if (maze[xx][yy] == 'I') counti += 1;
if (maze[xx][yy] == 'Z') countz += 1;
if (maze[xx][yy] == 'W') countw += 1;
if (maze[xx][yy] == 'E') counte += 1;
//System.out.println("Z="+counta);
dfs(xx, yy, out, kk);
}
if (visited[xx][yy]) {
if (counta > 0 && countl >= 4 && counti > 0 && countz >= 2 && countw > 0 && counte > 0) {
ticker = 1;
}
}
}
return ticker;
} }
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| 4,037 | 0.434481 | 0.420114 | 139 | 28.021584 | 22.567394 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.755396 | false | false | 13 |
cd76e8e766bdb4cb49478c3cfa7da6098a72f578 | 8,057,358,674,596 | 1aca61570d7440242da1ab5ca9a74848d9d44fa8 | /ADIES/src/adies/ConfirmacionCita.java | 27badd094ad0443bc5a3cedd12db74026edb2794 | [] | no_license | GJHR-6/ADIES | https://github.com/GJHR-6/ADIES | 2ee78c5eb36f279abf0349cfea6cc8e202c10787 | c5d47c699033bac558022a605841570cf26ca650 | refs/heads/main | 2023-03-27T00:49:38.421000 | 2021-03-25T01:06:04 | 2021-03-25T01:06:04 | 339,560,399 | 1 | 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 adies;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
*
* @author guill
*/
public class ConfirmacionCita extends javax.swing.JFrame {
/**
* Creates new form ConfirmacionCita
*/
public ConfirmacionCita() {
initComponents();
}
String paciente;
String Medico;
String Fecha;
String Hora;
Citas cita = new Citas();
public ConfirmacionCita(String paciente, String Medico, String Fecha, String Hora, Citas cita) {
getContentPane().setBackground(new java.awt.Color(255,255,255));
this.paciente = paciente;
this.Medico = Medico;
this.Fecha = Fecha;
this.Hora = Hora;
this.cita = cita;
initComponents();
jLabel6.setText(paciente);
jLabel7.setText(Medico);
jLabel8.setText(Fecha);
jLabel9.setText(Hora);
btn_icon.setIcon(setIcono("/imagenes/logo_nuevo.jpeg",btn_icon));
}
/**
* This method is callfed 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();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
btn_icon = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setText("Confirmación de cita");
jLabel2.setText("Paciente:");
jLabel3.setText("Médico:");
jLabel4.setText("Fecha:");
jLabel5.setText("Hora:");
jLabel6.setText("jLabel6");
jLabel7.setText("jLabel7");
jLabel8.setText("jLabel8");
jLabel9.setText("jLabel9");
jButton1.setBackground(new java.awt.Color(51, 204, 0));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("Guardar");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(51, 204, 0));
jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton2.setText("Atrás");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
btn_icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/logo_nuevo.jpeg"))); // NOI18N
btn_icon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_iconActionPerformed(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()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING))
.addGap(96, 96, 96)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel7)
.addComponent(jLabel8)
.addComponent(jLabel9)))
.addGroup(layout.createSequentialGroup()
.addComponent(btn_icon, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)))
.addContainerGap(21, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(48, 48, 48))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(btn_icon, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel6))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel7))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel8))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel9))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1))
.addContainerGap(20, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
// Ingreso de datos de la cita a la BD
cita.ingresoCitas();
correo c = new correo(jLabel6.getText(),jLabel8.getText(),jLabel9.getText());
c.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton1MouseClicked
private void btn_iconActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_iconActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btn_iconActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// Regresar a citas
this.dispose();
}//GEN-LAST:event_jButton2ActionPerformed
public Icon setIcono(String url, JButton boton){
ImageIcon icon = new ImageIcon(getClass().getResource(url));
int ancho = boton.getWidth();
int alto = boton.getHeight();
ImageIcon icono = new ImageIcon(icon.getImage().getScaledInstance(ancho, alto, Image.SCALE_DEFAULT));
return icono;
}
public Icon setIconoPresionado(String url, JButton boton, int ancho, int altura)
{
ImageIcon icon = new ImageIcon(getClass().getResource(url));
int width = boton.getWidth() - ancho;
int height = boton.getHeight() - altura;
ImageIcon icono = new ImageIcon(icon.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT));
return icono;
}
/**
* @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(ConfirmacionCita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ConfirmacionCita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ConfirmacionCita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConfirmacionCita.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 ConfirmacionCita().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_icon;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 12,115 | java | ConfirmacionCita.java | Java | [
{
"context": "on;\nimport javax.swing.JButton;\n\n/**\n *\n * @author guill\n */\npublic class ConfirmacionCita extends javax.s",
"end": 331,
"score": 0.9947910308837891,
"start": 326,
"tag": "USERNAME",
"value": "guill"
}
] | 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 adies;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
*
* @author guill
*/
public class ConfirmacionCita extends javax.swing.JFrame {
/**
* Creates new form ConfirmacionCita
*/
public ConfirmacionCita() {
initComponents();
}
String paciente;
String Medico;
String Fecha;
String Hora;
Citas cita = new Citas();
public ConfirmacionCita(String paciente, String Medico, String Fecha, String Hora, Citas cita) {
getContentPane().setBackground(new java.awt.Color(255,255,255));
this.paciente = paciente;
this.Medico = Medico;
this.Fecha = Fecha;
this.Hora = Hora;
this.cita = cita;
initComponents();
jLabel6.setText(paciente);
jLabel7.setText(Medico);
jLabel8.setText(Fecha);
jLabel9.setText(Hora);
btn_icon.setIcon(setIcono("/imagenes/logo_nuevo.jpeg",btn_icon));
}
/**
* This method is callfed 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();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
btn_icon = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setText("Confirmación de cita");
jLabel2.setText("Paciente:");
jLabel3.setText("Médico:");
jLabel4.setText("Fecha:");
jLabel5.setText("Hora:");
jLabel6.setText("jLabel6");
jLabel7.setText("jLabel7");
jLabel8.setText("jLabel8");
jLabel9.setText("jLabel9");
jButton1.setBackground(new java.awt.Color(51, 204, 0));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("Guardar");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(51, 204, 0));
jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton2.setText("Atrás");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
btn_icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/logo_nuevo.jpeg"))); // NOI18N
btn_icon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_iconActionPerformed(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()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING))
.addGap(96, 96, 96)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel7)
.addComponent(jLabel8)
.addComponent(jLabel9)))
.addGroup(layout.createSequentialGroup()
.addComponent(btn_icon, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)))
.addContainerGap(21, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(48, 48, 48))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(btn_icon, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel6))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel7))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel8))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel9))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1))
.addContainerGap(20, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
// Ingreso de datos de la cita a la BD
cita.ingresoCitas();
correo c = new correo(jLabel6.getText(),jLabel8.getText(),jLabel9.getText());
c.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton1MouseClicked
private void btn_iconActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_iconActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btn_iconActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// Regresar a citas
this.dispose();
}//GEN-LAST:event_jButton2ActionPerformed
public Icon setIcono(String url, JButton boton){
ImageIcon icon = new ImageIcon(getClass().getResource(url));
int ancho = boton.getWidth();
int alto = boton.getHeight();
ImageIcon icono = new ImageIcon(icon.getImage().getScaledInstance(ancho, alto, Image.SCALE_DEFAULT));
return icono;
}
public Icon setIconoPresionado(String url, JButton boton, int ancho, int altura)
{
ImageIcon icon = new ImageIcon(getClass().getResource(url));
int width = boton.getWidth() - ancho;
int height = boton.getHeight() - altura;
ImageIcon icono = new ImageIcon(icon.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT));
return icono;
}
/**
* @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(ConfirmacionCita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ConfirmacionCita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ConfirmacionCita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConfirmacionCita.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 ConfirmacionCita().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_icon;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
// End of variables declaration//GEN-END:variables
}
| 12,115 | 0.613441 | 0.598002 | 278 | 42.568344 | 33.335777 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615108 | false | false | 13 |
272e7a4e46b567e0b1a2798611884548c6e788f9 | 23,441,931,559,036 | 1b2f9c769570c83adf326af0466fa3e852bf9644 | /src/br/com/rick/frederico/file/codec/coding/CodecFactory.java | 52c69bd0dc76590d03f862e654f54f8e357ee2ca | [] | no_license | fredericoarick/file-codec | https://github.com/fredericoarick/file-codec | e44b317ce540520bff4228ccaf4552dd06314cec | 92a62574ed03cfb89203b32a9e6765dfc78f0922 | refs/heads/master | 2023-08-18T19:42:47.296000 | 2021-10-07T00:25:44 | 2021-10-07T00:25:44 | 414,004,133 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.rick.frederico.file.codec.coding;
import br.com.rick.frederico.file.codec.error.CodecException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Queue;
public class CodecFactory {
public static Codec getForEncoding(String codecName, Queue<String> additionalArgs) {
if (GolombCodec.codecName().equals(codecName.toLowerCase())) {
String golombDivider = additionalArgs.poll();
if (golombDivider == null) {
throw new CodecException("WARN: Missing arg for encoding");
}
return new GolombCodec(Integer.parseInt(golombDivider));
} else if (EliasGamaCodec.codecName().equals(codecName.toLowerCase())) {
return new EliasGamaCodec();
} else if (FibonacciCodec.codecName().equals(codecName.toLowerCase())) {
return new FibonacciCodec();
} else if (UnaryCodec.codecName().equals(codecName.toLowerCase())) {
return new UnaryCodec();
} else if (DeltaCodec.codecName().equals(codecName.toLowerCase())) {
return new DeltaCodec();
}
throw new CodecException("WARN: Encoding not supported");
}
public static Codec getForDecoding(InputStream inputStream) throws IOException {
int codecCode = inputStream.read();
int additionalArgs = inputStream.read();
if (GolombCodec.codecCode() == codecCode) {
return new GolombCodec(additionalArgs);
} else if (EliasGamaCodec.codecCode() == codecCode) {
return new EliasGamaCodec();
} else if (FibonacciCodec.codecCode() == codecCode) {
return new FibonacciCodec();
} else if (UnaryCodec.codecCode() == codecCode) {
return new UnaryCodec();
} else if (DeltaCodec.codecCode() == codecCode) {
return new DeltaCodec();
}
throw new CodecException("WARN: Encoding not supported");
}
}
| UTF-8 | Java | 1,959 | java | CodecFactory.java | Java | [] | null | [] | package br.com.rick.frederico.file.codec.coding;
import br.com.rick.frederico.file.codec.error.CodecException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Queue;
public class CodecFactory {
public static Codec getForEncoding(String codecName, Queue<String> additionalArgs) {
if (GolombCodec.codecName().equals(codecName.toLowerCase())) {
String golombDivider = additionalArgs.poll();
if (golombDivider == null) {
throw new CodecException("WARN: Missing arg for encoding");
}
return new GolombCodec(Integer.parseInt(golombDivider));
} else if (EliasGamaCodec.codecName().equals(codecName.toLowerCase())) {
return new EliasGamaCodec();
} else if (FibonacciCodec.codecName().equals(codecName.toLowerCase())) {
return new FibonacciCodec();
} else if (UnaryCodec.codecName().equals(codecName.toLowerCase())) {
return new UnaryCodec();
} else if (DeltaCodec.codecName().equals(codecName.toLowerCase())) {
return new DeltaCodec();
}
throw new CodecException("WARN: Encoding not supported");
}
public static Codec getForDecoding(InputStream inputStream) throws IOException {
int codecCode = inputStream.read();
int additionalArgs = inputStream.read();
if (GolombCodec.codecCode() == codecCode) {
return new GolombCodec(additionalArgs);
} else if (EliasGamaCodec.codecCode() == codecCode) {
return new EliasGamaCodec();
} else if (FibonacciCodec.codecCode() == codecCode) {
return new FibonacciCodec();
} else if (UnaryCodec.codecCode() == codecCode) {
return new UnaryCodec();
} else if (DeltaCodec.codecCode() == codecCode) {
return new DeltaCodec();
}
throw new CodecException("WARN: Encoding not supported");
}
}
| 1,959 | 0.643185 | 0.643185 | 47 | 40.680851 | 26.82497 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.468085 | false | false | 1 |
d208887f049ed3bb2f79ff01b2eacd2a873041a3 | 34,024,730,919,529 | a8749ee5c5e23468cd5fbebb36d87d8373d25b26 | /libs/ESF/src/emergent/FeedBack.java | 16e3b6d77055b03dc347e400b07dcd3bd3fe95ba | [] | no_license | tectronics/emergent-rules-and-behaviour-study | https://github.com/tectronics/emergent-rules-and-behaviour-study | 559c67facdc8aa008937d3715a698f60b37be6b7 | 4337cff407f7992bbd7a39aa1bd65d485e183ad2 | refs/heads/master | 2018-01-11T15:15:47.479000 | 2010-05-18T16:43:07 | 2010-05-18T16:43:07 | 46,907,560 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package emergent;
public class FeedBack {
}
| UTF-8 | Java | 47 | java | FeedBack.java | Java | [] | null | [] | package emergent;
public class FeedBack {
}
| 47 | 0.723404 | 0.723404 | 6 | 6.833333 | 9.47658 | 23 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 1 |
cdaee580dd01e5dfd967ca38e9f402aa91854566 | 31,078,383,414,676 | f1d73d5b299561875dbc0b85df937541c08d9e68 | /The Second Iteration/palm_meal_customer/src/com/zsct/customer/model/Shop.java | b4cbc8f63d796241bad84ce6a00b571ac25957ad | [] | no_license | KevinLong15/Canteen_Managing_System | https://github.com/KevinLong15/Canteen_Managing_System | d069a13643f1c428ea08f0a4a7ed6d89172dc406 | c7f9ed2d322393abd03b5747b4b11d20d2755c12 | refs/heads/master | 2021-09-03T10:22:20.593000 | 2018-01-08T10:26:21 | 2018-01-08T10:26:21 | 107,943,410 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* http://www.appcodes.cn APP精品源码下载站声明:
* 1、本站源码为网上搜集或网友提供,如果涉及或侵害到您的版 权,请立即通知我们。
* 2、 本站提供免费代码只可供研究学习使用,切勿用于商业用途 由此引起一切后果与本站无关。
* 3、 商业源码请在源码授权范围内进行使用。
* 4、更多APP精品源码下载请访问:http://www.appcodes.cn。
* 5、如有疑问请发信息至appcodes@qq.com。
*/
package com.zsct.customer.model;
import java.io.Serializable;
public class Shop implements Serializable {
private String id;
private String name;
private String type_name;
private String city;
private String phone;
private String average_buy;
private String start_hours;
private String end_hours;
private String routes;
private String address;
private String is_rooms;
private String lon;
private String lat;
private String license;
private String permit;
private String short_message;
private String short_message_remark;
private String bank_name;
private String bank_number;
private String bane_username;
private String zhifubao;
private String discount;
private String create_time;
private String image;
private String image_thumb;
private String is_schedule;
private String is_point;
private String is_group;
private String is_card;
private String is_pay;
private String intro;
private String username;
private String password;
private String temp_distance;
public Shop(String id, String name, String type_name, String city,
String phone, String average_buy, String start_hours,
String end_hours, String routes, String address, String is_rooms,
String lon, String lat, String license, String permit,
String short_message, String short_message_remark,
String bank_name, String bank_number, String bane_username,
String zhifubao, String discount, String create_time, String image,
String image_thumb, String is_schedule, String is_point,
String is_group, String is_card, String is_pay, String intro,
String username, String password, String temp_distance) {
super();
this.id = id;
this.name = name;
this.type_name = type_name;
this.city = city;
this.phone = phone;
this.average_buy = average_buy;
this.start_hours = start_hours;
this.end_hours = end_hours;
this.routes = routes;
this.address = address;
this.is_rooms = is_rooms;
this.lon = lon;
this.lat = lat;
this.license = license;
this.permit = permit;
this.short_message = short_message;
this.short_message_remark = short_message_remark;
this.bank_name = bank_name;
this.bank_number = bank_number;
this.bane_username = bane_username;
this.zhifubao = zhifubao;
this.discount = discount;
this.create_time = create_time;
this.image = image;
this.image_thumb = image_thumb;
this.is_schedule = is_schedule;
this.is_point = is_point;
this.is_group = is_group;
this.is_card = is_card;
this.is_pay = is_pay;
this.intro = intro;
this.username = username;
this.password = password;
this.temp_distance = temp_distance;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType_name() {
return type_name;
}
public void setType_name(String type_name) {
this.type_name = type_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAverage_buy() {
return average_buy;
}
public void setAverage_buy(String average_buy) {
this.average_buy = average_buy;
}
public String getStart_hours() {
return start_hours;
}
public void setStart_hours(String start_hours) {
this.start_hours = start_hours;
}
public String getEnd_hours() {
return end_hours;
}
public void setEnd_hours(String end_hours) {
this.end_hours = end_hours;
}
public String getRoutes() {
return routes;
}
public void setRoutes(String routes) {
this.routes = routes;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getIs_rooms() {
return is_rooms;
}
public void setIs_rooms(String is_rooms) {
this.is_rooms = is_rooms;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getPermit() {
return permit;
}
public void setPermit(String permit) {
this.permit = permit;
}
public String getShort_message() {
return short_message;
}
public void setShort_message(String short_message) {
this.short_message = short_message;
}
public String getShort_message_remark() {
return short_message_remark;
}
public void setShort_message_remark(String short_message_remark) {
this.short_message_remark = short_message_remark;
}
public String getBank_name() {
return bank_name;
}
public void setBank_name(String bank_name) {
this.bank_name = bank_name;
}
public String getBank_number() {
return bank_number;
}
public void setBank_number(String bank_number) {
this.bank_number = bank_number;
}
public String getBane_username() {
return bane_username;
}
public void setBane_username(String bane_username) {
this.bane_username = bane_username;
}
public String getZhifubao() {
return zhifubao;
}
public void setZhifubao(String zhifubao) {
this.zhifubao = zhifubao;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getCreate_time() {
return create_time;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getImage_thumb() {
return image_thumb;
}
public void setImage_thumb(String image_thumb) {
this.image_thumb = image_thumb;
}
public String getIs_schedule() {
return is_schedule;
}
public void setIs_schedule(String is_schedule) {
this.is_schedule = is_schedule;
}
public String getIs_point() {
return is_point;
}
public void setIs_point(String is_point) {
this.is_point = is_point;
}
public String getIs_group() {
return is_group;
}
public void setIs_group(String is_group) {
this.is_group = is_group;
}
public String getIs_card() {
return is_card;
}
public void setIs_card(String is_card) {
this.is_card = is_card;
}
public String getIs_pay() {
return is_pay;
}
public void setIs_pay(String is_pay) {
this.is_pay = is_pay;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTemp_distance() {
return temp_distance;
}
public void setTemp_distance(String temp_distance) {
this.temp_distance = temp_distance;
}
@Override
public String toString() {
return "Shop [id=" + id + ", name=" + name + ", type_name=" + type_name
+ ", city=" + city + ", phone=" + phone + ", average_buy="
+ average_buy + ", start_hours=" + start_hours + ", end_hours="
+ end_hours + ", routes=" + routes + ", address=" + address
+ ", is_rooms=" + is_rooms + ", lon=" + lon + ", lat=" + lat
+ ", license=" + license + ", permit=" + permit
+ ", short_message=" + short_message
+ ", short_message_remark=" + short_message_remark
+ ", bank_name=" + bank_name + ", bank_number=" + bank_number
+ ", bane_username=" + bane_username + ", zhifubao=" + zhifubao
+ ", discount=" + discount + ", create_time=" + create_time
+ ", image=" + image + ", image_thumb=" + image_thumb
+ ", is_schedule=" + is_schedule + ", is_point=" + is_point
+ ", is_group=" + is_group + ", is_card=" + is_card
+ ", is_pay=" + is_pay + ", intro=" + intro + ", username="
+ username + ", password=" + password + ", temp_distance="
+ temp_distance + "]";
}
}
| UTF-8 | Java | 8,552 | java | Shop.java | Java | [
{
"context": "PP精品源码下载请访问:http://www.appcodes.cn。\n * 5、如有疑问请发信息至appcodes@qq.com。\n */\npackage com.zsct.customer.model;\n\nimport jav",
"end": 233,
"score": 0.9999287128448486,
"start": 218,
"tag": "EMAIL",
"value": "appcodes@qq.com"
},
{
"context": "\n\tprivate String bane_username;\n\tprivate String zhifubao;\n\tprivate String discount;\n\tprivate String crea",
"end": 890,
"score": 0.5147691965103149,
"start": 886,
"tag": "USERNAME",
"value": "ifub"
},
{
"context": ".bank_number = bank_number;\n\t\tthis.bane_username = bane_username;\n\t\tthis.zhifubao = zhifubao;\n\t\tthis.discount = di",
"end": 2434,
"score": 0.9995542168617249,
"start": 2421,
"tag": "USERNAME",
"value": "bane_username"
},
{
"context": " = is_pay;\n\t\tthis.intro = intro;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tthis.temp_distance",
"end": 2770,
"score": 0.9991958737373352,
"start": 2762,
"tag": "USERNAME",
"value": "username"
},
{
"context": "tro;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tthis.temp_distance = temp_distance;\n\t}\n\tpublic",
"end": 2798,
"score": 0.9991477727890015,
"start": 2790,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "r;\n\t}\n\tpublic String getBane_username() {\n\t\treturn bane_username;\n\t}\n\tpublic void setBane_username(String bane_use",
"end": 5307,
"score": 0.9976423978805542,
"start": 5294,
"tag": "USERNAME",
"value": "bane_username"
},
{
"context": "sername;\n\t}\n\tpublic void setBane_username(String bane_username) {\n\t\tthis.bane_username = bane_username;",
"end": 5353,
"score": 0.5914793610572815,
"start": 5350,
"tag": "USERNAME",
"value": "ane"
},
{
"context": "ame(String bane_username) {\n\t\tthis.bane_username = bane_username;\n\t}\n\tpublic String getZhifubao() {\n\t\treturn zhifu",
"end": 5402,
"score": 0.9620469808578491,
"start": 5389,
"tag": "USERNAME",
"value": "bane_username"
},
{
"context": " intro;\n\t}\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\tpublic void setUsername(String username) {\n\t",
"end": 6863,
"score": 0.714767575263977,
"start": 6855,
"tag": "USERNAME",
"value": "username"
},
{
"context": "d setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\tpublic String getPassword() {\n\t\treturn passw",
"end": 6938,
"score": 0.8599215149879456,
"start": 6930,
"tag": "USERNAME",
"value": "username"
},
{
"context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\tpublic String getTemp_distance() {\n\t\treturn ",
"end": 7066,
"score": 0.8883125185966492,
"start": 7058,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ank_name + \", bank_number=\" + bank_number\n\t\t\t\t+ \", bane_username=\" + bane_username + \", zhifubao=\" + zhif",
"end": 7829,
"score": 0.637205183506012,
"start": 7825,
"tag": "USERNAME",
"value": "bane"
},
{
"context": "me + \", bank_number=\" + bank_number\n\t\t\t\t+ \", bane_username=\" + bane_username + \", zhifubao=\" + zhifubao\n\t\t\t\t",
"end": 7838,
"score": 0.6283015012741089,
"start": 7830,
"tag": "USERNAME",
"value": "username"
},
{
"context": "_number=\" + bank_number\n\t\t\t\t+ \", bane_username=\" + bane_username + \", zhifubao=\" + zhifubao\n\t\t\t\t+ \", discount=\" + ",
"end": 7856,
"score": 0.9787938594818115,
"start": 7843,
"tag": "USERNAME",
"value": "bane_username"
},
{
"context": "mber\n\t\t\t\t+ \", bane_username=\" + bane_username + \", zhifubao=\" + zhifubao\n\t\t\t\t+ \", discount=\" + discount + \", ",
"end": 7870,
"score": 0.802338719367981,
"start": 7862,
"tag": "USERNAME",
"value": "zhifubao"
},
{
"context": " is_pay + \", intro=\" + intro + \", username=\"\n\t\t\t\t+ username + \", password=\" + password + \", temp_distance=\"\n\t",
"end": 8204,
"score": 0.9887901544570923,
"start": 8196,
"tag": "USERNAME",
"value": "username"
},
{
"context": "o + \", username=\"\n\t\t\t\t+ username + \", password=\" + password + \", temp_distance=\"\n\t\t\t\t+ temp_distance + \"]\";\n\t",
"end": 8231,
"score": 0.9982059001922607,
"start": 8223,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | /*
* http://www.appcodes.cn APP精品源码下载站声明:
* 1、本站源码为网上搜集或网友提供,如果涉及或侵害到您的版 权,请立即通知我们。
* 2、 本站提供免费代码只可供研究学习使用,切勿用于商业用途 由此引起一切后果与本站无关。
* 3、 商业源码请在源码授权范围内进行使用。
* 4、更多APP精品源码下载请访问:http://www.appcodes.cn。
* 5、如有疑问请发信息至<EMAIL>。
*/
package com.zsct.customer.model;
import java.io.Serializable;
public class Shop implements Serializable {
private String id;
private String name;
private String type_name;
private String city;
private String phone;
private String average_buy;
private String start_hours;
private String end_hours;
private String routes;
private String address;
private String is_rooms;
private String lon;
private String lat;
private String license;
private String permit;
private String short_message;
private String short_message_remark;
private String bank_name;
private String bank_number;
private String bane_username;
private String zhifubao;
private String discount;
private String create_time;
private String image;
private String image_thumb;
private String is_schedule;
private String is_point;
private String is_group;
private String is_card;
private String is_pay;
private String intro;
private String username;
private String password;
private String temp_distance;
public Shop(String id, String name, String type_name, String city,
String phone, String average_buy, String start_hours,
String end_hours, String routes, String address, String is_rooms,
String lon, String lat, String license, String permit,
String short_message, String short_message_remark,
String bank_name, String bank_number, String bane_username,
String zhifubao, String discount, String create_time, String image,
String image_thumb, String is_schedule, String is_point,
String is_group, String is_card, String is_pay, String intro,
String username, String password, String temp_distance) {
super();
this.id = id;
this.name = name;
this.type_name = type_name;
this.city = city;
this.phone = phone;
this.average_buy = average_buy;
this.start_hours = start_hours;
this.end_hours = end_hours;
this.routes = routes;
this.address = address;
this.is_rooms = is_rooms;
this.lon = lon;
this.lat = lat;
this.license = license;
this.permit = permit;
this.short_message = short_message;
this.short_message_remark = short_message_remark;
this.bank_name = bank_name;
this.bank_number = bank_number;
this.bane_username = bane_username;
this.zhifubao = zhifubao;
this.discount = discount;
this.create_time = create_time;
this.image = image;
this.image_thumb = image_thumb;
this.is_schedule = is_schedule;
this.is_point = is_point;
this.is_group = is_group;
this.is_card = is_card;
this.is_pay = is_pay;
this.intro = intro;
this.username = username;
this.password = <PASSWORD>;
this.temp_distance = temp_distance;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType_name() {
return type_name;
}
public void setType_name(String type_name) {
this.type_name = type_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAverage_buy() {
return average_buy;
}
public void setAverage_buy(String average_buy) {
this.average_buy = average_buy;
}
public String getStart_hours() {
return start_hours;
}
public void setStart_hours(String start_hours) {
this.start_hours = start_hours;
}
public String getEnd_hours() {
return end_hours;
}
public void setEnd_hours(String end_hours) {
this.end_hours = end_hours;
}
public String getRoutes() {
return routes;
}
public void setRoutes(String routes) {
this.routes = routes;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getIs_rooms() {
return is_rooms;
}
public void setIs_rooms(String is_rooms) {
this.is_rooms = is_rooms;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getPermit() {
return permit;
}
public void setPermit(String permit) {
this.permit = permit;
}
public String getShort_message() {
return short_message;
}
public void setShort_message(String short_message) {
this.short_message = short_message;
}
public String getShort_message_remark() {
return short_message_remark;
}
public void setShort_message_remark(String short_message_remark) {
this.short_message_remark = short_message_remark;
}
public String getBank_name() {
return bank_name;
}
public void setBank_name(String bank_name) {
this.bank_name = bank_name;
}
public String getBank_number() {
return bank_number;
}
public void setBank_number(String bank_number) {
this.bank_number = bank_number;
}
public String getBane_username() {
return bane_username;
}
public void setBane_username(String bane_username) {
this.bane_username = bane_username;
}
public String getZhifubao() {
return zhifubao;
}
public void setZhifubao(String zhifubao) {
this.zhifubao = zhifubao;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getCreate_time() {
return create_time;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getImage_thumb() {
return image_thumb;
}
public void setImage_thumb(String image_thumb) {
this.image_thumb = image_thumb;
}
public String getIs_schedule() {
return is_schedule;
}
public void setIs_schedule(String is_schedule) {
this.is_schedule = is_schedule;
}
public String getIs_point() {
return is_point;
}
public void setIs_point(String is_point) {
this.is_point = is_point;
}
public String getIs_group() {
return is_group;
}
public void setIs_group(String is_group) {
this.is_group = is_group;
}
public String getIs_card() {
return is_card;
}
public void setIs_card(String is_card) {
this.is_card = is_card;
}
public String getIs_pay() {
return is_pay;
}
public void setIs_pay(String is_pay) {
this.is_pay = is_pay;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getTemp_distance() {
return temp_distance;
}
public void setTemp_distance(String temp_distance) {
this.temp_distance = temp_distance;
}
@Override
public String toString() {
return "Shop [id=" + id + ", name=" + name + ", type_name=" + type_name
+ ", city=" + city + ", phone=" + phone + ", average_buy="
+ average_buy + ", start_hours=" + start_hours + ", end_hours="
+ end_hours + ", routes=" + routes + ", address=" + address
+ ", is_rooms=" + is_rooms + ", lon=" + lon + ", lat=" + lat
+ ", license=" + license + ", permit=" + permit
+ ", short_message=" + short_message
+ ", short_message_remark=" + short_message_remark
+ ", bank_name=" + bank_name + ", bank_number=" + bank_number
+ ", bane_username=" + bane_username + ", zhifubao=" + zhifubao
+ ", discount=" + discount + ", create_time=" + create_time
+ ", image=" + image + ", image_thumb=" + image_thumb
+ ", is_schedule=" + is_schedule + ", is_point=" + is_point
+ ", is_group=" + is_group + ", is_card=" + is_card
+ ", is_pay=" + is_pay + ", intro=" + intro + ", username="
+ username + ", password=" + <PASSWORD> + ", temp_distance="
+ temp_distance + "]";
}
}
| 8,550 | 0.687817 | 0.687213 | 319 | 24.987461 | 17.54117 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.131661 | false | false | 1 |
0a825e7eb3190005a9f0645501d6cf5a20adac2d | 24,429,773,990,737 | 2a53f85816d8d30f593197afe4314318be989f05 | /src/main/java/org/apache/struts/action/ActionServlet.java | f2be882ad646ac5351495d9b4950653d6ba85339 | [
"Apache-2.0"
] | permissive | ibissource/ibis-struts | https://github.com/ibissource/ibis-struts | c95834d2bf817b7762b019bee7b41aefdaf9d3f8 | d9bdfc3f289d5074d6271a8580a91911ae926ec9 | refs/heads/master | 2020-03-23T12:47:27.795000 | 2018-08-23T15:24:50 | 2018-08-23T15:24:50 | 141,582,182 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* $Id: ActionServlet.java 264684 2005-08-30 03:08:01Z niallp $
*
* Copyright 2000-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.struts.action;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.MissingResourceException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.BigIntegerConverter;
import org.apache.commons.beanutils.converters.BooleanConverter;
import org.apache.commons.beanutils.converters.ByteConverter;
import org.apache.commons.beanutils.converters.CharacterConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortConverter;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.RuleSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.config.ConfigRuleSet;
import org.apache.struts.config.DataSourceConfig;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.MessageResourcesConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.ModuleConfigFactory;
import org.apache.struts.config.PlugInConfig;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.MessageResourcesFactory;
import org.apache.struts.util.ModuleUtils;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ServletContextWriter;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* <p><strong>ActionServlet</strong> provides the "controller" in the
* Model-View-Controller (MVC) design pattern for web applications that is
* commonly known as "Model 2". This nomenclature originated with a
* description in the JavaServerPages Specification, version 0.92, and has
* persisted ever since (in the absence of a better name).</p>
*
* <p>Generally, a "Model 2" application is architected as follows:</p>
* <ul>
* <li>The user interface will generally be created with server pages, which
* will not themselves contain any business logic. These pages represent
* the "view" component of an MVC architecture.</li>
* <li>Forms and hyperlinks in the user interface that require business logic
* to be executed will be submitted to a request URI that is mapped to this
* servlet.</li>
* <li>There can be <b>one</b> instance of this servlet class,
* which receives and processes all requests that change the state of
* a user's interaction with the application. The servlet delegates the
* handling of a request to a {@link RequestProcessor} object. This component
* represents the "controller" component of an MVC architecture.</li>
* <li>The <code>RequestProcessor</code> selects and invokes an {@link Action} class to perform
* the requested business logic, or delegates the response to another resource.</li>
* <li>The <code>Action</code> classes can manipulate the state of the application's
* interaction with the user, typically by creating or modifying JavaBeans
* that are stored as request or session attributes (depending on how long
* they need to be available). Such JavaBeans represent the "model"
* component of an MVC architecture.</li>
* <li>Instead of producing the next page of the user interface directly,
* <code>Action</code> classes generally return an {@link ActionForward} to indicate
* which resource should handle the response. If the <code>Action</code>
* does not return null, the <code>RequestProcessor</code> forwards or
* redirects to the specified resource (by utilizing
* <code>RequestDispatcher.forward</code> or <code>Response.sendRedirect</code>)
* so as to produce the next page of the user interface.</li>
* </ul>
*
* <p>The standard version of <code>RequestsProcessor</code> implements the
* following logic for each incoming HTTP request. You can override
* some or all of this functionality by subclassing this object and
* implementing your own version of the processing.</p>
* <ul>
* <li>Identify, from the incoming request URI, the substring that will be
* used to select an action procedure.</li>
* <li>Use this substring to map to the Java class name of the corresponding
* action class (an implementation of the <code>Action</code> interface).
* </li>
* <li>If this is the first request for a particular <code>Action</code> class,
* instantiate an instance of that class and cache it for future use.</li>
* <li>Optionally populate the properties of an <code>ActionForm</code> bean
* associated with this mapping.</li>
* <li>Call the <code>execute</code> method of this <code>Action</code> class, passing
* on a reference to the mapping that was used, the relevant form-bean
* (if any), and the request and the response that were passed to the
* controller by the servlet container (thereby providing access to any
* specialized properties of the mapping itself as well as to the
* ServletContext).
* </li>
* </ul>
*
* <p>The standard version of <code>ActionServlet</code> is configured based
* on the following servlet initialization parameters, which you will specify
* in the web application deployment descriptor (<code>/WEB-INF/web.xml</code>)
* for your application. Subclasses that specialize this servlet are free to
* define additional initialization parameters. </p>
* <ul>
* <li><strong>config</strong> - Comma-separated list of context-relative
* path(s) to the XML resource(s) containing the configuration information
* for the default module. (Multiple files support since Struts 1.1)
* [/WEB-INF/struts-config.xml].</li>
* <li><strong>config/${module}</strong> - Comma-separated list of
* Context-relative path(s) to the XML resource(s)
* containing the configuration information for the module that
* will use the specified prefix (/${module}). This can be repeated as many
* times as required for multiple modules. (Since Struts 1.1)</li>
* <li><strong>configFactory</strong> - The Java class name of the
* <code>ModuleConfigFactory</code> used to create the implementation of the
* <code>ModuleConfig</code> interface.
* [org.apache.struts.config.impl.DefaultModuleConfigFactory]
* </li>
* <li><strong>convertNull</strong> - Force simulation of the Struts 1.0 behavior
* when populating forms. If set to true, the numeric Java wrapper class types
* (like <code>java.lang.Integer</code>) will default to null (rather than 0).
* (Since Struts 1.1) [false] </li>
* <li><strong>rulesets</strong> - Comma-delimited list of fully qualified
* classnames of additional <code>org.apache.commons.digester.RuleSet</code>
* instances that should be added to the <code>Digester</code> that will
* be processing <code>struts-config.xml</code> files. By default, only
* the <code>RuleSet</code> for the standard configuration elements is
* loaded. (Since Struts 1.1)</li>
* <li><strong>validating</strong> - Should we use a validating XML parser to
* process the configuration file (strongly recommended)? [true]</li>
* </ul>
*
* @version $Rev: 264684 $ $Date: 2005-08-30 04:08:01 +0100 (Tue, 30 Aug 2005) $
*/
public class ActionServlet extends HttpServlet {
// ----------------------------------------------------- Instance Variables
/**
* <p>Comma-separated list of context-relative path(s) to our configuration
* resource(s) for the default module.</p>
*/
protected String config = "/WEB-INF/struts-config.xml";
/**
* <p>The Digester used to produce ModuleConfig objects from a
* Struts configuration file.</p>
*
* @since Struts 1.1
*/
protected Digester configDigester = null;
/**
* <p>The flag to request backwards-compatible conversions for form bean
* properties of the Java wrapper class types.</p>
*
* @since Struts 1.1
*/
protected boolean convertNull = false;
/**
* <p>The JDBC data sources that has been configured for this module,
* if any, keyed by the servlet context attribute under which they are
* stored.</p>
*/
protected FastHashMap dataSources = new FastHashMap();
/**
* <p>The resources object for our internal resources.</p>
*/
protected MessageResources internal = null;
/**
* <p>The Java base name of our internal resources.</p>
* @since Struts 1.1
*/
protected String internalName = "org.apache.struts.action.ActionResources";
/**
* <p>Commons Logging instance.</p>
*
* @since Struts 1.1
*/
protected static Log log = LogFactory.getLog(ActionServlet.class);
/**
* <p>The <code>RequestProcessor</code> instance we will use to process
* all incoming requests.</p>
*
* @since Struts 1.1
*/
protected RequestProcessor processor = null;
/**
* <p>The set of public identifiers, and corresponding resource names, for
* the versions of the configuration file DTDs that we know about. There
* <strong>MUST</strong> be an even number of Strings in this list!</p>
*/
protected String registrations[] = {
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN",
"/org/apache/struts/resources/struts-config_1_0.dtd",
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN",
"/org/apache/struts/resources/struts-config_1_1.dtd",
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN",
"/org/apache/struts/resources/struts-config_1_2.dtd",
"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN",
"/org/apache/struts/resources/web-app_2_2.dtd",
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN",
"/org/apache/struts/resources/web-app_2_3.dtd"
};
/**
* <p>The URL pattern to which we are mapped in our web application
* deployment descriptor.</p>
*/
protected String servletMapping = null; // :FIXME: - multiples?
/**
* <p>The servlet name under which we are registered in our web application
* deployment descriptor.</p>
*/
protected String servletName = null;
// ---------------------------------------------------- HttpServlet Methods
/**
* <p>Gracefully shut down this controller servlet, releasing any resources
* that were allocated at initialization.</p>
*/
public void destroy() {
if (log.isDebugEnabled()) {
log.debug(internal.getMessage("finalizing"));
}
destroyModules();
destroyInternal();
getServletContext().removeAttribute(Globals.ACTION_SERVLET_KEY);
// Release our LogFactory and Log instances (if any)
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = ActionServlet.class.getClassLoader();
}
try {
LogFactory.release(classLoader);
} catch (Throwable t) {
; // Servlet container doesn't have the latest version
; // of commons-logging-api.jar installed
// :FIXME: Why is this dependent on the container's version of commons-logging?
// Shouldn't this depend on the version packaged with Struts?
/*
Reason: LogFactory.release(classLoader); was added as
an attempt to investigate the OutOfMemory error reported on Bugzilla #14042.
It was committed for version 1.136 by craigmcc
*/
}
PropertyUtils.clearDescriptors();
}
/**
* <p>Initialize this servlet. Most of the processing has been factored into
* support methods so that you can override particular functionality at a
* fairly granular level.</p>
*
* @exception ServletException if we cannot configure ourselves correctly
*/
public void init() throws ServletException {
// Wraps the entire initialization in a try/catch to better handle
// unexpected exceptions and errors to provide better feedback
// to the developer
try {
initInternal();
initOther();
initServlet();
getServletContext().setAttribute(Globals.ACTION_SERVLET_KEY, this);
initModuleConfigFactory();
// Initialize modules as needed
ModuleConfig moduleConfig = initModuleConfig("", config);
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
Enumeration names = getServletConfig().getInitParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (!name.startsWith("config/")) {
continue;
}
String prefix = name.substring(6);
moduleConfig = initModuleConfig
(prefix, getServletConfig().getInitParameter(name));
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
}
this.initModulePrefixes(this.getServletContext());
this.destroyConfigDigester();
} catch (UnavailableException ex) {
throw ex;
} catch (Throwable t) {
// The follow error message is not retrieved from internal message
// resources as they may not have been able to have been
// initialized
log.error("Unable to initialize Struts ActionServlet due to an "
+ "unexpected exception or error thrown, so marking the "
+ "servlet as unavailable. Most likely, this is due to an "
+ "incorrect or missing library dependency.", t);
throw new UnavailableException(t.getMessage());
}
}
/**
* <p>Saves a String[] of module prefixes in the ServletContext under
* Globals.MODULE_PREFIXES_KEY. <strong>NOTE</strong> -
* the "" prefix for the default module is not included in this list.</p>
*
* @param context The servlet context.
* @since Struts 1.2
*/
protected void initModulePrefixes(ServletContext context) {
ArrayList prefixList = new ArrayList();
Enumeration names = context.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (!name.startsWith(Globals.MODULE_KEY)) {
continue;
}
String prefix = name.substring(Globals.MODULE_KEY.length());
if (prefix.length() > 0) {
prefixList.add(prefix);
}
}
String[] prefixes = (String[]) prefixList.toArray(new String[prefixList.size()]);
context.setAttribute(Globals.MODULE_PREFIXES_KEY, prefixes);
}
/**
* <p>Process an HTTP "GET" request.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
/**
* <p>Process an HTTP "POST" request.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
// --------------------------------------------------------- Public Methods
/**
* <p>Remember a servlet mapping from our web application deployment
* descriptor, if it is for this servlet.</p>
*
* @param servletName The name of the servlet being mapped
* @param urlPattern The URL pattern to which this servlet is mapped
*/
public void addServletMapping(String servletName, String urlPattern) {
if (log.isDebugEnabled()) {
log.debug("Process servletName=" + servletName +
", urlPattern=" + urlPattern);
}
if (servletName == null) {
return;
}
if (servletName.equals(this.servletName)) {
this.servletMapping = urlPattern;
}
}
/**
* <p>Return the <code>MessageResources</code> instance containing our
* internal message strings.</p>
*
* @since Struts 1.1
*/
public MessageResources getInternal() {
return (this.internal);
}
// ------------------------------------------------------ Protected Methods
/**
* <p>Gracefully terminate use of any modules associated with this
* application (if any).</p>
*
* @since Struts 1.1
*/
protected void destroyModules() {
ArrayList values = new ArrayList();
Enumeration names = getServletContext().getAttributeNames();
while (names.hasMoreElements()) {
values.add(names.nextElement());
}
Iterator keys = values.iterator();
while (keys.hasNext()) {
String name = (String) keys.next();
Object value = getServletContext().getAttribute(name);
if (!(value instanceof ModuleConfig)) {
continue;
}
ModuleConfig config = (ModuleConfig) value;
if (this.getProcessorForModule(config) != null) {
this.getProcessorForModule(config).destroy();
}
getServletContext().removeAttribute(name);
PlugIn plugIns[] =
(PlugIn[]) getServletContext().getAttribute(
Globals.PLUG_INS_KEY + config.getPrefix());
if (plugIns != null) {
for (int i = 0; i < plugIns.length; i++) {
int j = plugIns.length - (i + 1);
plugIns[j].destroy();
}
getServletContext().removeAttribute(
Globals.PLUG_INS_KEY + config.getPrefix());
}
}
}
/**
* <p>Gracefully release any configDigester instance that we have created.</p>
*
* @since Struts 1.1
*/
protected void destroyConfigDigester() {
configDigester = null;
}
/**
* <p>Gracefully terminate use of the internal MessageResources.</p>
*/
protected void destroyInternal() {
internal = null;
}
/**
* <p>Return the module configuration object for the currently selected
* module.</p>
*
* @param request The servlet request we are processing
* @since Struts 1.1
*/
protected ModuleConfig getModuleConfig
(HttpServletRequest request) {
ModuleConfig config = (ModuleConfig)
request.getAttribute(Globals.MODULE_KEY);
if (config == null) {
config = (ModuleConfig)
getServletContext().getAttribute(Globals.MODULE_KEY);
}
return (config);
}
/**
* <p>Look up and return the {@link RequestProcessor} responsible for the
* specified module, creating a new one if necessary.</p>
*
* @param config The module configuration for which to
* acquire and return a RequestProcessor.
*
* @exception ServletException if we cannot instantiate a RequestProcessor
* instance
* @since Struts 1.1
*/
protected synchronized RequestProcessor getRequestProcessor(ModuleConfig config)
throws ServletException {
// :FIXME: Document UnavailableException?
RequestProcessor processor = this.getProcessorForModule(config);
if (processor == null) {
try {
processor =
(RequestProcessor) RequestUtils.applicationInstance(
config.getControllerConfig().getProcessorClass());
} catch (Exception e) {
throw new UnavailableException(
"Cannot initialize RequestProcessor of class "
+ config.getControllerConfig().getProcessorClass()
+ ": "
+ e);
}
processor.init(this, config);
String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();
getServletContext().setAttribute(key, processor);
}
return (processor);
}
/**
* <p>Returns the RequestProcessor for the given module or null if one does not
* exist. This method will not create a RequestProcessor.</p>
*
* @param config The ModuleConfig.
*/
private RequestProcessor getProcessorForModule(ModuleConfig config) {
String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();
return (RequestProcessor) getServletContext().getAttribute(key);
}
/**
* <p>Initialize the factory used to create the module configuration.</p>
* @since Struts 1.2
*/
protected void initModuleConfigFactory(){
String configFactory = getServletConfig().getInitParameter("configFactory");
if (configFactory != null) {
ModuleConfigFactory.setFactoryClass(configFactory);
}
}
/**
* <p>Initialize the module configuration information for the
* specified module.</p>
*
* @param prefix Module prefix for this module
* @param paths Comma-separated list of context-relative resource path(s)
* for this modules's configuration resource(s)
*
* @exception ServletException if initialization cannot be performed
* @since Struts 1.1
*/
protected ModuleConfig initModuleConfig(String prefix, String paths)
throws ServletException {
// :FIXME: Document UnavailableException? (Doesn't actually throw anything)
if (log.isDebugEnabled()) {
log.debug(
"Initializing module path '"
+ prefix
+ "' configuration from '"
+ paths
+ "'");
}
// Parse the configuration for this module
ModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory();
ModuleConfig config = factoryObject.createModuleConfig(prefix);
// Configure the Digester instance we will use
Digester digester = initConfigDigester();
// Process each specified resource path
while (paths.length() > 0) {
digester.push(config);
String path = null;
int comma = paths.indexOf(',');
if (comma >= 0) {
path = paths.substring(0, comma).trim();
paths = paths.substring(comma + 1);
} else {
path = paths.trim();
paths = "";
}
if (path.length() < 1) {
break;
}
this.parseModuleConfigFile(digester, path);
}
getServletContext().setAttribute(
Globals.MODULE_KEY + config.getPrefix(),
config);
// Force creation and registration of DynaActionFormClass instances
// for all dynamic form beans we wil be using
FormBeanConfig fbs[] = config.findFormBeanConfigs();
for (int i = 0; i < fbs.length; i++) {
if (fbs[i].getDynamic()) {
fbs[i].getDynaActionFormClass();
}
}
return config;
}
/**
* <p>Parses one module config file.</p>
*
* @param digester Digester instance that does the parsing
* @param path The path to the config file to parse.
*
* @throws UnavailableException if file cannot be read or parsed
* @since Struts 1.2
*/
protected void parseModuleConfigFile(Digester digester, String path)
throws UnavailableException {
InputStream input = null;
try {
URL url = getServletContext().getResource(path);
// If the config isn't in the servlet context, try the class loader
// which allows the config files to be stored in a jar
if (url == null) {
url = getClass().getResource(path);
}
if (url == null) {
String msg = internal.getMessage("configMissing", path);
log.error(msg);
throw new UnavailableException(msg);
}
InputSource is = new InputSource(url.toExternalForm());
input = url.openStream();
is.setByteStream(input);
digester.parse(is);
} catch (MalformedURLException e) {
handleConfigException(path, e);
} catch (IOException e) {
handleConfigException(path, e);
} catch (SAXException e) {
handleConfigException(path, e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
throw new UnavailableException(e.getMessage());
}
}
}
}
/**
* <p>Simplifies exception handling in the <code>parseModuleConfigFile</code> method.<p>
* @param path
* @param e
* @throws UnavailableException as a wrapper around Exception
*/
private void handleConfigException(String path, Exception e)
throws UnavailableException {
String msg = internal.getMessage("configParse", path);
log.error(msg, e);
throw new UnavailableException(msg);
}
/**
* <p>Initialize the data sources for the specified module.</p>
*
* @param config ModuleConfig information for this module
*
* @exception ServletException if initialization cannot be performed
* @since Struts 1.1
*/
protected void initModuleDataSources(ModuleConfig config) throws ServletException {
// :FIXME: Document UnavailableException?
if (log.isDebugEnabled()) {
log.debug("Initializing module path '" + config.getPrefix() +
"' data sources");
}
ServletContextWriter scw =
new ServletContextWriter(getServletContext());
DataSourceConfig dscs[] = config.findDataSourceConfigs();
if (dscs == null) {
dscs = new DataSourceConfig[0];
}
dataSources.setFast(false);
for (int i = 0; i < dscs.length; i++) {
if (log.isDebugEnabled()) {
log.debug("Initializing module path '" + config.getPrefix() +
"' data source '" + dscs[i].getKey() + "'");
}
DataSource ds = null;
try {
ds = (DataSource)
RequestUtils.applicationInstance(dscs[i].getType());
BeanUtils.populate(ds, dscs[i].getProperties());
ds.setLogWriter(scw);
} catch (Exception e) {
log.error(internal.getMessage("dataSource.init", dscs[i].getKey()), e);
throw new UnavailableException
(internal.getMessage("dataSource.init", dscs[i].getKey()));
}
getServletContext().setAttribute
(dscs[i].getKey() + config.getPrefix(), ds);
dataSources.put(dscs[i].getKey(), ds);
}
dataSources.setFast(true);
}
/**
* <p>Initialize the plug ins for the specified module.</p>
*
* @param config ModuleConfig information for this module
*
* @exception ServletException if initialization cannot be performed
* @since Struts 1.1
*/
protected void initModulePlugIns
(ModuleConfig config) throws ServletException {
if (log.isDebugEnabled()) {
log.debug("Initializing module path '" + config.getPrefix() + "' plug ins");
}
PlugInConfig plugInConfigs[] = config.findPlugInConfigs();
PlugIn plugIns[] = new PlugIn[plugInConfigs.length];
getServletContext().setAttribute(Globals.PLUG_INS_KEY + config.getPrefix(), plugIns);
for (int i = 0; i < plugIns.length; i++) {
try {
plugIns[i] =
(PlugIn)RequestUtils.applicationInstance(plugInConfigs[i].getClassName());
BeanUtils.populate(plugIns[i], plugInConfigs[i].getProperties());
// Pass the current plugIn config object to the PlugIn.
// The property is set only if the plugin declares it.
// This plugin config object is needed by Tiles
try {
PropertyUtils.setProperty(
plugIns[i],
"currentPlugInConfigObject",
plugInConfigs[i]);
} catch (Exception e) {
// FIXME Whenever we fail silently, we must document a valid reason
// for doing so. Why should we fail silently if a property can't be set on
// the plugin?
/**
* Between version 1.138-1.140 cedric made these changes.
* The exceptions are caught to deal with containers applying strict security.
* This was in response to bug #15736
*
* Recommend that we make the currentPlugInConfigObject part of the PlugIn Interface if we can, Rob
*/
}
plugIns[i].init(this, config);
} catch (ServletException e) {
throw e;
} catch (Exception e) {
String errMsg =
internal.getMessage(
"plugIn.init",
plugInConfigs[i].getClassName());
log(errMsg, e);
throw new UnavailableException(errMsg);
}
}
}
/**
* <p>Initialize the application <code>MessageResources</code> for the specified
* module.</p>
*
* @param config ModuleConfig information for this module
*
* @exception ServletException if initialization cannot be performed
* @since Struts 1.1
*/
protected void initModuleMessageResources(ModuleConfig config)
throws ServletException {
MessageResourcesConfig mrcs[] = config.findMessageResourcesConfigs();
for (int i = 0; i < mrcs.length; i++) {
if ((mrcs[i].getFactory() == null)
|| (mrcs[i].getParameter() == null)) {
continue;
}
if (log.isDebugEnabled()) {
log.debug(
"Initializing module path '"
+ config.getPrefix()
+ "' message resources from '"
+ mrcs[i].getParameter()
+ "'");
}
String factory = mrcs[i].getFactory();
MessageResourcesFactory.setFactoryClass(factory);
MessageResourcesFactory factoryObject =
MessageResourcesFactory.createFactory();
factoryObject.setConfig(mrcs[i]);
MessageResources resources =
factoryObject.createResources(mrcs[i].getParameter());
resources.setReturnNull(mrcs[i].getNull());
resources.setEscape(mrcs[i].isEscape());
getServletContext().setAttribute(
mrcs[i].getKey() + config.getPrefix(),
resources);
}
}
/**
* <p>Create (if needed) and return a new <code>Digester</code>
* instance that has been initialized to process Struts module
* configuration files and configure a corresponding <code>ModuleConfig</code>
* object (which must be pushed on to the evaluation stack before parsing
* begins).</p>
*
* @exception ServletException if a Digester cannot be configured
* @since Struts 1.1
*/
protected Digester initConfigDigester() throws ServletException {
// :FIXME: Where can ServletException be thrown?
// Do we have an existing instance?
if (configDigester != null) {
return (configDigester);
}
// Create a new Digester instance with standard capabilities
configDigester = new Digester();
configDigester.setNamespaceAware(true);
configDigester.setValidating(this.isValidating());
configDigester.setUseContextClassLoader(true);
configDigester.addRuleSet(new ConfigRuleSet());
for (int i = 0; i < registrations.length; i += 2) {
URL url = this.getClass().getResource(registrations[i+1]);
if (url != null) {
configDigester.register(registrations[i], url.toString());
}
}
this.addRuleSets();
// Return the completely configured Digester instance
return (configDigester);
}
/**
* <p>Add any custom RuleSet instances to configDigester that have
* been specified in the <code>rulesets</code> init parameter.</p>
*
* @throws ServletException
*/
private void addRuleSets() throws ServletException {
String rulesets = getServletConfig().getInitParameter("rulesets");
if (rulesets == null) {
rulesets = "";
}
rulesets = rulesets.trim();
String ruleset = null;
while (rulesets.length() > 0) {
int comma = rulesets.indexOf(",");
if (comma < 0) {
ruleset = rulesets.trim();
rulesets = "";
} else {
ruleset = rulesets.substring(0, comma).trim();
rulesets = rulesets.substring(comma + 1).trim();
}
if (log.isDebugEnabled()) {
log.debug("Configuring custom Digester Ruleset of type " + ruleset);
}
try {
RuleSet instance = (RuleSet) RequestUtils.applicationInstance(ruleset);
this.configDigester.addRuleSet(instance);
} catch (Exception e) {
log.error("Exception configuring custom Digester RuleSet", e);
throw new ServletException(e);
}
}
}
/**
* <p>Check the status of the <code>validating</code> initialization parameter.</p>
*
* @return true if the module Digester should validate.
*/
private boolean isValidating() {
boolean validating = true;
String value = getServletConfig().getInitParameter("validating");
if ("false".equalsIgnoreCase(value)
|| "no".equalsIgnoreCase(value)
|| "n".equalsIgnoreCase(value)
|| "0".equalsIgnoreCase(value)) {
validating = false;
}
return validating;
}
/**
* <p>Initialize our internal MessageResources bundle.</p>
*
* @exception ServletException if we cannot initialize these resources
*/
protected void initInternal() throws ServletException {
// :FIXME: Document UnavailableException
try {
internal = MessageResources.getMessageResources(internalName);
} catch (MissingResourceException e) {
log.error("Cannot load internal resources from '" + internalName + "'",
e);
throw new UnavailableException
("Cannot load internal resources from '" + internalName + "'");
}
}
/**
* <p>Initialize other global characteristics of the controller servlet.</p>
*
* @exception ServletException if we cannot initialize these resources
*/
protected void initOther() throws ServletException {
String value = null;
value = getServletConfig().getInitParameter("config");
if (value != null) {
config = value;
}
// Backwards compatibility for form beans of Java wrapper classes
// Set to true for strict Struts 1.0 compatibility
value = getServletConfig().getInitParameter("convertNull");
if ("true".equalsIgnoreCase(value)
|| "yes".equalsIgnoreCase(value)
|| "on".equalsIgnoreCase(value)
|| "y".equalsIgnoreCase(value)
|| "1".equalsIgnoreCase(value)) {
convertNull = true;
}
if (convertNull) {
ConvertUtils.deregister();
ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);
ConvertUtils.register(new BooleanConverter(null), Boolean.class);
ConvertUtils.register(new ByteConverter(null), Byte.class);
ConvertUtils.register(new CharacterConverter(null), Character.class);
ConvertUtils.register(new DoubleConverter(null), Double.class);
ConvertUtils.register(new FloatConverter(null), Float.class);
ConvertUtils.register(new IntegerConverter(null), Integer.class);
ConvertUtils.register(new LongConverter(null), Long.class);
ConvertUtils.register(new ShortConverter(null), Short.class);
}
}
/**
* <p>Initialize the servlet mapping under which our controller servlet
* is being accessed. This will be used in the <code>&html:form></code>
* tag to generate correct destination URLs for form submissions.</p>
*
* @throws ServletException if error happens while scanning web.xml
*/
protected void initServlet() throws ServletException {
// Remember our servlet name
this.servletName = getServletConfig().getServletName();
// Prepare a Digester to scan the web application deployment descriptor
Digester digester = new Digester();
digester.push(this);
digester.setNamespaceAware(true);
digester.setValidating(false);
// Register our local copy of the DTDs that we can find
for (int i = 0; i < registrations.length; i += 2) {
URL url = this.getClass().getResource(registrations[i+1]);
if (url != null) {
digester.register(registrations[i], url.toString());
}
}
// Configure the processing rules that we need
digester.addCallMethod("web-app/servlet-mapping",
"addServletMapping", 2);
digester.addCallParam("web-app/servlet-mapping/servlet-name", 0);
digester.addCallParam("web-app/servlet-mapping/url-pattern", 1);
// Process the web application deployment descriptor
if (log.isDebugEnabled()) {
log.debug("Scanning web.xml for controller servlet mapping");
}
InputStream input =
getServletContext().getResourceAsStream("/WEB-INF/web.xml");
if (input == null) {
log.error(internal.getMessage("configWebXml"));
throw new ServletException(internal.getMessage("configWebXml"));
}
try {
digester.parse(input);
} catch (IOException e) {
log.error(internal.getMessage("configWebXml"), e);
throw new ServletException(e);
} catch (SAXException e) {
log.error(internal.getMessage("configWebXml"), e);
throw new ServletException(e);
} finally {
try {
input.close();
} catch (IOException e) {
log.error(internal.getMessage("configWebXml"), e);
throw new ServletException(e);
}
}
// Record a servlet context attribute (if appropriate)
if (log.isDebugEnabled()) {
log.debug("Mapping for servlet '" + servletName + "' = '" +
servletMapping + "'");
}
if (servletMapping != null) {
getServletContext().setAttribute(Globals.SERVLET_KEY, servletMapping);
}
}
/**
* <p>Perform the standard request processing for this request, and create
* the corresponding response.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception is thrown
*/
protected void process(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ModuleUtils.getInstance().selectModule(request, getServletContext());
ModuleConfig config = getModuleConfig(request);
RequestProcessor processor = getProcessorForModule(config);
if (processor == null) {
processor = getRequestProcessor(config);
}
processor.process(request, response);
}
}
| UTF-8 | Java | 43,125 | java | ActionServlet.java | Java | [
{
"context": "Id: ActionServlet.java 264684 2005-08-30 03:08:01Z niallp $ \n *\n * Copyright 2000-2005 The Apache Software ",
"end": 64,
"score": 0.9994458556175232,
"start": 58,
"tag": "USERNAME",
"value": "niallp"
},
{
"context": " It was committed for version 1.136 by craigmcc\n */\n }\n\n PropertyUtils.c",
"end": 13161,
"score": 0.9997315406799316,
"start": 13153,
"tag": "USERNAME",
"value": "craigmcc"
},
{
"context": "ssor.init(this, config);\n\n String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();\n ",
"end": 22500,
"score": 0.6766394376754761,
"start": 22492,
"tag": "KEY",
"value": "Globals."
},
{
"context": "Module(ModuleConfig config) {\n String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();\n return (RequestP",
"end": 22989,
"score": 0.7157503962516785,
"start": 22963,
"tag": "KEY",
"value": "Globals.REQUEST_PROCESSOR_"
}
] | null | [] | /*
* $Id: ActionServlet.java 264684 2005-08-30 03:08:01Z niallp $
*
* Copyright 2000-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.struts.action;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.MissingResourceException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.BigIntegerConverter;
import org.apache.commons.beanutils.converters.BooleanConverter;
import org.apache.commons.beanutils.converters.ByteConverter;
import org.apache.commons.beanutils.converters.CharacterConverter;
import org.apache.commons.beanutils.converters.DoubleConverter;
import org.apache.commons.beanutils.converters.FloatConverter;
import org.apache.commons.beanutils.converters.IntegerConverter;
import org.apache.commons.beanutils.converters.LongConverter;
import org.apache.commons.beanutils.converters.ShortConverter;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.RuleSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.config.ConfigRuleSet;
import org.apache.struts.config.DataSourceConfig;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.MessageResourcesConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.ModuleConfigFactory;
import org.apache.struts.config.PlugInConfig;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.MessageResourcesFactory;
import org.apache.struts.util.ModuleUtils;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ServletContextWriter;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* <p><strong>ActionServlet</strong> provides the "controller" in the
* Model-View-Controller (MVC) design pattern for web applications that is
* commonly known as "Model 2". This nomenclature originated with a
* description in the JavaServerPages Specification, version 0.92, and has
* persisted ever since (in the absence of a better name).</p>
*
* <p>Generally, a "Model 2" application is architected as follows:</p>
* <ul>
* <li>The user interface will generally be created with server pages, which
* will not themselves contain any business logic. These pages represent
* the "view" component of an MVC architecture.</li>
* <li>Forms and hyperlinks in the user interface that require business logic
* to be executed will be submitted to a request URI that is mapped to this
* servlet.</li>
* <li>There can be <b>one</b> instance of this servlet class,
* which receives and processes all requests that change the state of
* a user's interaction with the application. The servlet delegates the
* handling of a request to a {@link RequestProcessor} object. This component
* represents the "controller" component of an MVC architecture.</li>
* <li>The <code>RequestProcessor</code> selects and invokes an {@link Action} class to perform
* the requested business logic, or delegates the response to another resource.</li>
* <li>The <code>Action</code> classes can manipulate the state of the application's
* interaction with the user, typically by creating or modifying JavaBeans
* that are stored as request or session attributes (depending on how long
* they need to be available). Such JavaBeans represent the "model"
* component of an MVC architecture.</li>
* <li>Instead of producing the next page of the user interface directly,
* <code>Action</code> classes generally return an {@link ActionForward} to indicate
* which resource should handle the response. If the <code>Action</code>
* does not return null, the <code>RequestProcessor</code> forwards or
* redirects to the specified resource (by utilizing
* <code>RequestDispatcher.forward</code> or <code>Response.sendRedirect</code>)
* so as to produce the next page of the user interface.</li>
* </ul>
*
* <p>The standard version of <code>RequestsProcessor</code> implements the
* following logic for each incoming HTTP request. You can override
* some or all of this functionality by subclassing this object and
* implementing your own version of the processing.</p>
* <ul>
* <li>Identify, from the incoming request URI, the substring that will be
* used to select an action procedure.</li>
* <li>Use this substring to map to the Java class name of the corresponding
* action class (an implementation of the <code>Action</code> interface).
* </li>
* <li>If this is the first request for a particular <code>Action</code> class,
* instantiate an instance of that class and cache it for future use.</li>
* <li>Optionally populate the properties of an <code>ActionForm</code> bean
* associated with this mapping.</li>
* <li>Call the <code>execute</code> method of this <code>Action</code> class, passing
* on a reference to the mapping that was used, the relevant form-bean
* (if any), and the request and the response that were passed to the
* controller by the servlet container (thereby providing access to any
* specialized properties of the mapping itself as well as to the
* ServletContext).
* </li>
* </ul>
*
* <p>The standard version of <code>ActionServlet</code> is configured based
* on the following servlet initialization parameters, which you will specify
* in the web application deployment descriptor (<code>/WEB-INF/web.xml</code>)
* for your application. Subclasses that specialize this servlet are free to
* define additional initialization parameters. </p>
* <ul>
* <li><strong>config</strong> - Comma-separated list of context-relative
* path(s) to the XML resource(s) containing the configuration information
* for the default module. (Multiple files support since Struts 1.1)
* [/WEB-INF/struts-config.xml].</li>
* <li><strong>config/${module}</strong> - Comma-separated list of
* Context-relative path(s) to the XML resource(s)
* containing the configuration information for the module that
* will use the specified prefix (/${module}). This can be repeated as many
* times as required for multiple modules. (Since Struts 1.1)</li>
* <li><strong>configFactory</strong> - The Java class name of the
* <code>ModuleConfigFactory</code> used to create the implementation of the
* <code>ModuleConfig</code> interface.
* [org.apache.struts.config.impl.DefaultModuleConfigFactory]
* </li>
* <li><strong>convertNull</strong> - Force simulation of the Struts 1.0 behavior
* when populating forms. If set to true, the numeric Java wrapper class types
* (like <code>java.lang.Integer</code>) will default to null (rather than 0).
* (Since Struts 1.1) [false] </li>
* <li><strong>rulesets</strong> - Comma-delimited list of fully qualified
* classnames of additional <code>org.apache.commons.digester.RuleSet</code>
* instances that should be added to the <code>Digester</code> that will
* be processing <code>struts-config.xml</code> files. By default, only
* the <code>RuleSet</code> for the standard configuration elements is
* loaded. (Since Struts 1.1)</li>
* <li><strong>validating</strong> - Should we use a validating XML parser to
* process the configuration file (strongly recommended)? [true]</li>
* </ul>
*
* @version $Rev: 264684 $ $Date: 2005-08-30 04:08:01 +0100 (Tue, 30 Aug 2005) $
*/
public class ActionServlet extends HttpServlet {
// ----------------------------------------------------- Instance Variables
/**
* <p>Comma-separated list of context-relative path(s) to our configuration
* resource(s) for the default module.</p>
*/
protected String config = "/WEB-INF/struts-config.xml";
/**
* <p>The Digester used to produce ModuleConfig objects from a
* Struts configuration file.</p>
*
* @since Struts 1.1
*/
protected Digester configDigester = null;
/**
* <p>The flag to request backwards-compatible conversions for form bean
* properties of the Java wrapper class types.</p>
*
* @since Struts 1.1
*/
protected boolean convertNull = false;
/**
* <p>The JDBC data sources that has been configured for this module,
* if any, keyed by the servlet context attribute under which they are
* stored.</p>
*/
protected FastHashMap dataSources = new FastHashMap();
/**
* <p>The resources object for our internal resources.</p>
*/
protected MessageResources internal = null;
/**
* <p>The Java base name of our internal resources.</p>
* @since Struts 1.1
*/
protected String internalName = "org.apache.struts.action.ActionResources";
/**
* <p>Commons Logging instance.</p>
*
* @since Struts 1.1
*/
protected static Log log = LogFactory.getLog(ActionServlet.class);
/**
* <p>The <code>RequestProcessor</code> instance we will use to process
* all incoming requests.</p>
*
* @since Struts 1.1
*/
protected RequestProcessor processor = null;
/**
* <p>The set of public identifiers, and corresponding resource names, for
* the versions of the configuration file DTDs that we know about. There
* <strong>MUST</strong> be an even number of Strings in this list!</p>
*/
protected String registrations[] = {
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN",
"/org/apache/struts/resources/struts-config_1_0.dtd",
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN",
"/org/apache/struts/resources/struts-config_1_1.dtd",
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN",
"/org/apache/struts/resources/struts-config_1_2.dtd",
"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN",
"/org/apache/struts/resources/web-app_2_2.dtd",
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN",
"/org/apache/struts/resources/web-app_2_3.dtd"
};
/**
* <p>The URL pattern to which we are mapped in our web application
* deployment descriptor.</p>
*/
protected String servletMapping = null; // :FIXME: - multiples?
/**
* <p>The servlet name under which we are registered in our web application
* deployment descriptor.</p>
*/
protected String servletName = null;
// ---------------------------------------------------- HttpServlet Methods
/**
* <p>Gracefully shut down this controller servlet, releasing any resources
* that were allocated at initialization.</p>
*/
public void destroy() {
if (log.isDebugEnabled()) {
log.debug(internal.getMessage("finalizing"));
}
destroyModules();
destroyInternal();
getServletContext().removeAttribute(Globals.ACTION_SERVLET_KEY);
// Release our LogFactory and Log instances (if any)
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = ActionServlet.class.getClassLoader();
}
try {
LogFactory.release(classLoader);
} catch (Throwable t) {
; // Servlet container doesn't have the latest version
; // of commons-logging-api.jar installed
// :FIXME: Why is this dependent on the container's version of commons-logging?
// Shouldn't this depend on the version packaged with Struts?
/*
Reason: LogFactory.release(classLoader); was added as
an attempt to investigate the OutOfMemory error reported on Bugzilla #14042.
It was committed for version 1.136 by craigmcc
*/
}
PropertyUtils.clearDescriptors();
}
/**
* <p>Initialize this servlet. Most of the processing has been factored into
* support methods so that you can override particular functionality at a
* fairly granular level.</p>
*
* @exception ServletException if we cannot configure ourselves correctly
*/
public void init() throws ServletException {
// Wraps the entire initialization in a try/catch to better handle
// unexpected exceptions and errors to provide better feedback
// to the developer
try {
initInternal();
initOther();
initServlet();
getServletContext().setAttribute(Globals.ACTION_SERVLET_KEY, this);
initModuleConfigFactory();
// Initialize modules as needed
ModuleConfig moduleConfig = initModuleConfig("", config);
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
Enumeration names = getServletConfig().getInitParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (!name.startsWith("config/")) {
continue;
}
String prefix = name.substring(6);
moduleConfig = initModuleConfig
(prefix, getServletConfig().getInitParameter(name));
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
moduleConfig.freeze();
}
this.initModulePrefixes(this.getServletContext());
this.destroyConfigDigester();
} catch (UnavailableException ex) {
throw ex;
} catch (Throwable t) {
// The follow error message is not retrieved from internal message
// resources as they may not have been able to have been
// initialized
log.error("Unable to initialize Struts ActionServlet due to an "
+ "unexpected exception or error thrown, so marking the "
+ "servlet as unavailable. Most likely, this is due to an "
+ "incorrect or missing library dependency.", t);
throw new UnavailableException(t.getMessage());
}
}
/**
* <p>Saves a String[] of module prefixes in the ServletContext under
* Globals.MODULE_PREFIXES_KEY. <strong>NOTE</strong> -
* the "" prefix for the default module is not included in this list.</p>
*
* @param context The servlet context.
* @since Struts 1.2
*/
protected void initModulePrefixes(ServletContext context) {
ArrayList prefixList = new ArrayList();
Enumeration names = context.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
if (!name.startsWith(Globals.MODULE_KEY)) {
continue;
}
String prefix = name.substring(Globals.MODULE_KEY.length());
if (prefix.length() > 0) {
prefixList.add(prefix);
}
}
String[] prefixes = (String[]) prefixList.toArray(new String[prefixList.size()]);
context.setAttribute(Globals.MODULE_PREFIXES_KEY, prefixes);
}
/**
* <p>Process an HTTP "GET" request.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
/**
* <p>Process an HTTP "POST" request.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
// --------------------------------------------------------- Public Methods
/**
* <p>Remember a servlet mapping from our web application deployment
* descriptor, if it is for this servlet.</p>
*
* @param servletName The name of the servlet being mapped
* @param urlPattern The URL pattern to which this servlet is mapped
*/
public void addServletMapping(String servletName, String urlPattern) {
if (log.isDebugEnabled()) {
log.debug("Process servletName=" + servletName +
", urlPattern=" + urlPattern);
}
if (servletName == null) {
return;
}
if (servletName.equals(this.servletName)) {
this.servletMapping = urlPattern;
}
}
/**
* <p>Return the <code>MessageResources</code> instance containing our
* internal message strings.</p>
*
* @since Struts 1.1
*/
public MessageResources getInternal() {
return (this.internal);
}
// ------------------------------------------------------ Protected Methods
/**
* <p>Gracefully terminate use of any modules associated with this
* application (if any).</p>
*
* @since Struts 1.1
*/
protected void destroyModules() {
ArrayList values = new ArrayList();
Enumeration names = getServletContext().getAttributeNames();
while (names.hasMoreElements()) {
values.add(names.nextElement());
}
Iterator keys = values.iterator();
while (keys.hasNext()) {
String name = (String) keys.next();
Object value = getServletContext().getAttribute(name);
if (!(value instanceof ModuleConfig)) {
continue;
}
ModuleConfig config = (ModuleConfig) value;
if (this.getProcessorForModule(config) != null) {
this.getProcessorForModule(config).destroy();
}
getServletContext().removeAttribute(name);
PlugIn plugIns[] =
(PlugIn[]) getServletContext().getAttribute(
Globals.PLUG_INS_KEY + config.getPrefix());
if (plugIns != null) {
for (int i = 0; i < plugIns.length; i++) {
int j = plugIns.length - (i + 1);
plugIns[j].destroy();
}
getServletContext().removeAttribute(
Globals.PLUG_INS_KEY + config.getPrefix());
}
}
}
/**
* <p>Gracefully release any configDigester instance that we have created.</p>
*
* @since Struts 1.1
*/
protected void destroyConfigDigester() {
configDigester = null;
}
/**
* <p>Gracefully terminate use of the internal MessageResources.</p>
*/
protected void destroyInternal() {
internal = null;
}
/**
* <p>Return the module configuration object for the currently selected
* module.</p>
*
* @param request The servlet request we are processing
* @since Struts 1.1
*/
protected ModuleConfig getModuleConfig
(HttpServletRequest request) {
ModuleConfig config = (ModuleConfig)
request.getAttribute(Globals.MODULE_KEY);
if (config == null) {
config = (ModuleConfig)
getServletContext().getAttribute(Globals.MODULE_KEY);
}
return (config);
}
/**
* <p>Look up and return the {@link RequestProcessor} responsible for the
* specified module, creating a new one if necessary.</p>
*
* @param config The module configuration for which to
* acquire and return a RequestProcessor.
*
* @exception ServletException if we cannot instantiate a RequestProcessor
* instance
* @since Struts 1.1
*/
protected synchronized RequestProcessor getRequestProcessor(ModuleConfig config)
throws ServletException {
// :FIXME: Document UnavailableException?
RequestProcessor processor = this.getProcessorForModule(config);
if (processor == null) {
try {
processor =
(RequestProcessor) RequestUtils.applicationInstance(
config.getControllerConfig().getProcessorClass());
} catch (Exception e) {
throw new UnavailableException(
"Cannot initialize RequestProcessor of class "
+ config.getControllerConfig().getProcessorClass()
+ ": "
+ e);
}
processor.init(this, config);
String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();
getServletContext().setAttribute(key, processor);
}
return (processor);
}
/**
* <p>Returns the RequestProcessor for the given module or null if one does not
* exist. This method will not create a RequestProcessor.</p>
*
* @param config The ModuleConfig.
*/
private RequestProcessor getProcessorForModule(ModuleConfig config) {
String key = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();
return (RequestProcessor) getServletContext().getAttribute(key);
}
/**
* <p>Initialize the factory used to create the module configuration.</p>
* @since Struts 1.2
*/
protected void initModuleConfigFactory(){
String configFactory = getServletConfig().getInitParameter("configFactory");
if (configFactory != null) {
ModuleConfigFactory.setFactoryClass(configFactory);
}
}
/**
* <p>Initialize the module configuration information for the
* specified module.</p>
*
* @param prefix Module prefix for this module
* @param paths Comma-separated list of context-relative resource path(s)
* for this modules's configuration resource(s)
*
* @exception ServletException if initialization cannot be performed
* @since Struts 1.1
*/
protected ModuleConfig initModuleConfig(String prefix, String paths)
throws ServletException {
// :FIXME: Document UnavailableException? (Doesn't actually throw anything)
if (log.isDebugEnabled()) {
log.debug(
"Initializing module path '"
+ prefix
+ "' configuration from '"
+ paths
+ "'");
}
// Parse the configuration for this module
ModuleConfigFactory factoryObject = ModuleConfigFactory.createFactory();
ModuleConfig config = factoryObject.createModuleConfig(prefix);
// Configure the Digester instance we will use
Digester digester = initConfigDigester();
// Process each specified resource path
while (paths.length() > 0) {
digester.push(config);
String path = null;
int comma = paths.indexOf(',');
if (comma >= 0) {
path = paths.substring(0, comma).trim();
paths = paths.substring(comma + 1);
} else {
path = paths.trim();
paths = "";
}
if (path.length() < 1) {
break;
}
this.parseModuleConfigFile(digester, path);
}
getServletContext().setAttribute(
Globals.MODULE_KEY + config.getPrefix(),
config);
// Force creation and registration of DynaActionFormClass instances
// for all dynamic form beans we wil be using
FormBeanConfig fbs[] = config.findFormBeanConfigs();
for (int i = 0; i < fbs.length; i++) {
if (fbs[i].getDynamic()) {
fbs[i].getDynaActionFormClass();
}
}
return config;
}
/**
* <p>Parses one module config file.</p>
*
* @param digester Digester instance that does the parsing
* @param path The path to the config file to parse.
*
* @throws UnavailableException if file cannot be read or parsed
* @since Struts 1.2
*/
protected void parseModuleConfigFile(Digester digester, String path)
throws UnavailableException {
InputStream input = null;
try {
URL url = getServletContext().getResource(path);
// If the config isn't in the servlet context, try the class loader
// which allows the config files to be stored in a jar
if (url == null) {
url = getClass().getResource(path);
}
if (url == null) {
String msg = internal.getMessage("configMissing", path);
log.error(msg);
throw new UnavailableException(msg);
}
InputSource is = new InputSource(url.toExternalForm());
input = url.openStream();
is.setByteStream(input);
digester.parse(is);
} catch (MalformedURLException e) {
handleConfigException(path, e);
} catch (IOException e) {
handleConfigException(path, e);
} catch (SAXException e) {
handleConfigException(path, e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
throw new UnavailableException(e.getMessage());
}
}
}
}
/**
* <p>Simplifies exception handling in the <code>parseModuleConfigFile</code> method.<p>
* @param path
* @param e
* @throws UnavailableException as a wrapper around Exception
*/
private void handleConfigException(String path, Exception e)
throws UnavailableException {
String msg = internal.getMessage("configParse", path);
log.error(msg, e);
throw new UnavailableException(msg);
}
/**
* <p>Initialize the data sources for the specified module.</p>
*
* @param config ModuleConfig information for this module
*
* @exception ServletException if initialization cannot be performed
* @since Struts 1.1
*/
protected void initModuleDataSources(ModuleConfig config) throws ServletException {
// :FIXME: Document UnavailableException?
if (log.isDebugEnabled()) {
log.debug("Initializing module path '" + config.getPrefix() +
"' data sources");
}
ServletContextWriter scw =
new ServletContextWriter(getServletContext());
DataSourceConfig dscs[] = config.findDataSourceConfigs();
if (dscs == null) {
dscs = new DataSourceConfig[0];
}
dataSources.setFast(false);
for (int i = 0; i < dscs.length; i++) {
if (log.isDebugEnabled()) {
log.debug("Initializing module path '" + config.getPrefix() +
"' data source '" + dscs[i].getKey() + "'");
}
DataSource ds = null;
try {
ds = (DataSource)
RequestUtils.applicationInstance(dscs[i].getType());
BeanUtils.populate(ds, dscs[i].getProperties());
ds.setLogWriter(scw);
} catch (Exception e) {
log.error(internal.getMessage("dataSource.init", dscs[i].getKey()), e);
throw new UnavailableException
(internal.getMessage("dataSource.init", dscs[i].getKey()));
}
getServletContext().setAttribute
(dscs[i].getKey() + config.getPrefix(), ds);
dataSources.put(dscs[i].getKey(), ds);
}
dataSources.setFast(true);
}
/**
* <p>Initialize the plug ins for the specified module.</p>
*
* @param config ModuleConfig information for this module
*
* @exception ServletException if initialization cannot be performed
* @since Struts 1.1
*/
protected void initModulePlugIns
(ModuleConfig config) throws ServletException {
if (log.isDebugEnabled()) {
log.debug("Initializing module path '" + config.getPrefix() + "' plug ins");
}
PlugInConfig plugInConfigs[] = config.findPlugInConfigs();
PlugIn plugIns[] = new PlugIn[plugInConfigs.length];
getServletContext().setAttribute(Globals.PLUG_INS_KEY + config.getPrefix(), plugIns);
for (int i = 0; i < plugIns.length; i++) {
try {
plugIns[i] =
(PlugIn)RequestUtils.applicationInstance(plugInConfigs[i].getClassName());
BeanUtils.populate(plugIns[i], plugInConfigs[i].getProperties());
// Pass the current plugIn config object to the PlugIn.
// The property is set only if the plugin declares it.
// This plugin config object is needed by Tiles
try {
PropertyUtils.setProperty(
plugIns[i],
"currentPlugInConfigObject",
plugInConfigs[i]);
} catch (Exception e) {
// FIXME Whenever we fail silently, we must document a valid reason
// for doing so. Why should we fail silently if a property can't be set on
// the plugin?
/**
* Between version 1.138-1.140 cedric made these changes.
* The exceptions are caught to deal with containers applying strict security.
* This was in response to bug #15736
*
* Recommend that we make the currentPlugInConfigObject part of the PlugIn Interface if we can, Rob
*/
}
plugIns[i].init(this, config);
} catch (ServletException e) {
throw e;
} catch (Exception e) {
String errMsg =
internal.getMessage(
"plugIn.init",
plugInConfigs[i].getClassName());
log(errMsg, e);
throw new UnavailableException(errMsg);
}
}
}
/**
* <p>Initialize the application <code>MessageResources</code> for the specified
* module.</p>
*
* @param config ModuleConfig information for this module
*
* @exception ServletException if initialization cannot be performed
* @since Struts 1.1
*/
protected void initModuleMessageResources(ModuleConfig config)
throws ServletException {
MessageResourcesConfig mrcs[] = config.findMessageResourcesConfigs();
for (int i = 0; i < mrcs.length; i++) {
if ((mrcs[i].getFactory() == null)
|| (mrcs[i].getParameter() == null)) {
continue;
}
if (log.isDebugEnabled()) {
log.debug(
"Initializing module path '"
+ config.getPrefix()
+ "' message resources from '"
+ mrcs[i].getParameter()
+ "'");
}
String factory = mrcs[i].getFactory();
MessageResourcesFactory.setFactoryClass(factory);
MessageResourcesFactory factoryObject =
MessageResourcesFactory.createFactory();
factoryObject.setConfig(mrcs[i]);
MessageResources resources =
factoryObject.createResources(mrcs[i].getParameter());
resources.setReturnNull(mrcs[i].getNull());
resources.setEscape(mrcs[i].isEscape());
getServletContext().setAttribute(
mrcs[i].getKey() + config.getPrefix(),
resources);
}
}
/**
* <p>Create (if needed) and return a new <code>Digester</code>
* instance that has been initialized to process Struts module
* configuration files and configure a corresponding <code>ModuleConfig</code>
* object (which must be pushed on to the evaluation stack before parsing
* begins).</p>
*
* @exception ServletException if a Digester cannot be configured
* @since Struts 1.1
*/
protected Digester initConfigDigester() throws ServletException {
// :FIXME: Where can ServletException be thrown?
// Do we have an existing instance?
if (configDigester != null) {
return (configDigester);
}
// Create a new Digester instance with standard capabilities
configDigester = new Digester();
configDigester.setNamespaceAware(true);
configDigester.setValidating(this.isValidating());
configDigester.setUseContextClassLoader(true);
configDigester.addRuleSet(new ConfigRuleSet());
for (int i = 0; i < registrations.length; i += 2) {
URL url = this.getClass().getResource(registrations[i+1]);
if (url != null) {
configDigester.register(registrations[i], url.toString());
}
}
this.addRuleSets();
// Return the completely configured Digester instance
return (configDigester);
}
/**
* <p>Add any custom RuleSet instances to configDigester that have
* been specified in the <code>rulesets</code> init parameter.</p>
*
* @throws ServletException
*/
private void addRuleSets() throws ServletException {
String rulesets = getServletConfig().getInitParameter("rulesets");
if (rulesets == null) {
rulesets = "";
}
rulesets = rulesets.trim();
String ruleset = null;
while (rulesets.length() > 0) {
int comma = rulesets.indexOf(",");
if (comma < 0) {
ruleset = rulesets.trim();
rulesets = "";
} else {
ruleset = rulesets.substring(0, comma).trim();
rulesets = rulesets.substring(comma + 1).trim();
}
if (log.isDebugEnabled()) {
log.debug("Configuring custom Digester Ruleset of type " + ruleset);
}
try {
RuleSet instance = (RuleSet) RequestUtils.applicationInstance(ruleset);
this.configDigester.addRuleSet(instance);
} catch (Exception e) {
log.error("Exception configuring custom Digester RuleSet", e);
throw new ServletException(e);
}
}
}
/**
* <p>Check the status of the <code>validating</code> initialization parameter.</p>
*
* @return true if the module Digester should validate.
*/
private boolean isValidating() {
boolean validating = true;
String value = getServletConfig().getInitParameter("validating");
if ("false".equalsIgnoreCase(value)
|| "no".equalsIgnoreCase(value)
|| "n".equalsIgnoreCase(value)
|| "0".equalsIgnoreCase(value)) {
validating = false;
}
return validating;
}
/**
* <p>Initialize our internal MessageResources bundle.</p>
*
* @exception ServletException if we cannot initialize these resources
*/
protected void initInternal() throws ServletException {
// :FIXME: Document UnavailableException
try {
internal = MessageResources.getMessageResources(internalName);
} catch (MissingResourceException e) {
log.error("Cannot load internal resources from '" + internalName + "'",
e);
throw new UnavailableException
("Cannot load internal resources from '" + internalName + "'");
}
}
/**
* <p>Initialize other global characteristics of the controller servlet.</p>
*
* @exception ServletException if we cannot initialize these resources
*/
protected void initOther() throws ServletException {
String value = null;
value = getServletConfig().getInitParameter("config");
if (value != null) {
config = value;
}
// Backwards compatibility for form beans of Java wrapper classes
// Set to true for strict Struts 1.0 compatibility
value = getServletConfig().getInitParameter("convertNull");
if ("true".equalsIgnoreCase(value)
|| "yes".equalsIgnoreCase(value)
|| "on".equalsIgnoreCase(value)
|| "y".equalsIgnoreCase(value)
|| "1".equalsIgnoreCase(value)) {
convertNull = true;
}
if (convertNull) {
ConvertUtils.deregister();
ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);
ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);
ConvertUtils.register(new BooleanConverter(null), Boolean.class);
ConvertUtils.register(new ByteConverter(null), Byte.class);
ConvertUtils.register(new CharacterConverter(null), Character.class);
ConvertUtils.register(new DoubleConverter(null), Double.class);
ConvertUtils.register(new FloatConverter(null), Float.class);
ConvertUtils.register(new IntegerConverter(null), Integer.class);
ConvertUtils.register(new LongConverter(null), Long.class);
ConvertUtils.register(new ShortConverter(null), Short.class);
}
}
/**
* <p>Initialize the servlet mapping under which our controller servlet
* is being accessed. This will be used in the <code>&html:form></code>
* tag to generate correct destination URLs for form submissions.</p>
*
* @throws ServletException if error happens while scanning web.xml
*/
protected void initServlet() throws ServletException {
// Remember our servlet name
this.servletName = getServletConfig().getServletName();
// Prepare a Digester to scan the web application deployment descriptor
Digester digester = new Digester();
digester.push(this);
digester.setNamespaceAware(true);
digester.setValidating(false);
// Register our local copy of the DTDs that we can find
for (int i = 0; i < registrations.length; i += 2) {
URL url = this.getClass().getResource(registrations[i+1]);
if (url != null) {
digester.register(registrations[i], url.toString());
}
}
// Configure the processing rules that we need
digester.addCallMethod("web-app/servlet-mapping",
"addServletMapping", 2);
digester.addCallParam("web-app/servlet-mapping/servlet-name", 0);
digester.addCallParam("web-app/servlet-mapping/url-pattern", 1);
// Process the web application deployment descriptor
if (log.isDebugEnabled()) {
log.debug("Scanning web.xml for controller servlet mapping");
}
InputStream input =
getServletContext().getResourceAsStream("/WEB-INF/web.xml");
if (input == null) {
log.error(internal.getMessage("configWebXml"));
throw new ServletException(internal.getMessage("configWebXml"));
}
try {
digester.parse(input);
} catch (IOException e) {
log.error(internal.getMessage("configWebXml"), e);
throw new ServletException(e);
} catch (SAXException e) {
log.error(internal.getMessage("configWebXml"), e);
throw new ServletException(e);
} finally {
try {
input.close();
} catch (IOException e) {
log.error(internal.getMessage("configWebXml"), e);
throw new ServletException(e);
}
}
// Record a servlet context attribute (if appropriate)
if (log.isDebugEnabled()) {
log.debug("Mapping for servlet '" + servletName + "' = '" +
servletMapping + "'");
}
if (servletMapping != null) {
getServletContext().setAttribute(Globals.SERVLET_KEY, servletMapping);
}
}
/**
* <p>Perform the standard request processing for this request, and create
* the corresponding response.</p>
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception is thrown
*/
protected void process(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ModuleUtils.getInstance().selectModule(request, getServletContext());
ModuleConfig config = getModuleConfig(request);
RequestProcessor processor = getProcessorForModule(config);
if (processor == null) {
processor = getRequestProcessor(config);
}
processor.process(request, response);
}
}
| 43,125 | 0.613797 | 0.609461 | 1,200 | 34.9375 | 28.218851 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.366667 | false | false | 1 |
21515b26797bf3b688913800ca7d9da26508b9a9 | 15,341,623,183,123 | 0591f3eae69042a166ac6789df6e1a23f4f023b2 | /codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandshakeHandler.java | fad32463af969a54a301d68298ee7f4d8b3c9c0e | [
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"CC-PDDC",
"BSD-3-Clause",
"APSL-2.0",
"MIT"
] | permissive | netty/netty | https://github.com/netty/netty | 646740a2625e2849eb642183d8adbaab427e9fbb | c91d5a2608a8461377d004d5fe1bd2572533083d | refs/heads/4.1 | 2023-09-04T05:06:31.688000 | 2023-09-01T07:47:58 | 2023-09-01T07:47:58 | 1,064,563 | 31,408 | 16,820 | Apache-2.0 | false | 2023-09-12T23:37:43 | 2010-11-09T09:22:21 | 2023-09-12T15:21:54 | 2023-09-12T17:50:22 | 86,577 | 31,788 | 15,596 | 587 | Java | false | false | /*
* Copyright 2019 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http.websocketx;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.ServerHandshakeStateEvent;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import java.util.concurrent.TimeUnit;
import static io.netty.handler.codec.http.HttpUtil.*;
import static io.netty.util.internal.ObjectUtil.*;
/**
* Handles the HTTP handshake (the HTTP Upgrade request) for {@link WebSocketServerProtocolHandler}.
*/
class WebSocketServerProtocolHandshakeHandler extends ChannelInboundHandlerAdapter {
private final WebSocketServerProtocolConfig serverConfig;
private ChannelHandlerContext ctx;
private ChannelPromise handshakePromise;
private boolean isWebSocketPath;
WebSocketServerProtocolHandshakeHandler(WebSocketServerProtocolConfig serverConfig) {
this.serverConfig = checkNotNull(serverConfig, "serverConfig");
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
this.ctx = ctx;
handshakePromise = ctx.newPromise();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
final HttpObject httpObject = (HttpObject) msg;
if (httpObject instanceof HttpRequest) {
final HttpRequest req = (HttpRequest) httpObject;
isWebSocketPath = isWebSocketPath(req);
if (!isWebSocketPath) {
ctx.fireChannelRead(msg);
return;
}
try {
final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(ctx.pipeline(), req, serverConfig.websocketPath()),
serverConfig.subprotocols(), serverConfig.decoderConfig());
final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
final ChannelPromise localHandshakePromise = handshakePromise;
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
// Ensure we set the handshaker and replace this handler before we
// trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
// before we had a chance to replace it.
//
// See https://github.com/netty/netty/issues/9471.
WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
ctx.pipeline().remove(this);
final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
handshakeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
localHandshakePromise.tryFailure(future.cause());
ctx.fireExceptionCaught(future.cause());
} else {
localHandshakePromise.trySuccess();
// Kept for compatibility
ctx.fireUserEventTriggered(
WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
ctx.fireUserEventTriggered(
new WebSocketServerProtocolHandler.HandshakeComplete(
req.uri(), req.headers(), handshaker.selectedSubprotocol()));
}
}
});
applyHandshakeTimeout();
}
} finally {
ReferenceCountUtil.release(req);
}
} else if (!isWebSocketPath) {
ctx.fireChannelRead(msg);
} else {
ReferenceCountUtil.release(msg);
}
}
private boolean isWebSocketPath(HttpRequest req) {
String websocketPath = serverConfig.websocketPath();
String uri = req.uri();
boolean checkStartUri = uri.startsWith(websocketPath);
boolean checkNextUri = "/".equals(websocketPath) || checkNextUri(uri, websocketPath);
return serverConfig.checkStartsWith() ? (checkStartUri && checkNextUri) : uri.equals(websocketPath);
}
private boolean checkNextUri(String uri, String websocketPath) {
int len = websocketPath.length();
if (uri.length() > len) {
char nextUri = uri.charAt(len);
return nextUri == '/' || nextUri == '?';
}
return true;
}
private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
ChannelFuture f = ctx.writeAndFlush(res);
if (!isKeepAlive(req) || res.status().code() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
String protocol = "ws";
if (cp.get(SslHandler.class) != null) {
// SSL in use so use Secure WebSockets
protocol = "wss";
}
String host = req.headers().get(HttpHeaderNames.HOST);
return protocol + "://" + host + path;
}
private void applyHandshakeTimeout() {
final ChannelPromise localHandshakePromise = handshakePromise;
final long handshakeTimeoutMillis = serverConfig.handshakeTimeoutMillis();
if (handshakeTimeoutMillis <= 0 || localHandshakePromise.isDone()) {
return;
}
final Future<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (!localHandshakePromise.isDone() &&
localHandshakePromise.tryFailure(new WebSocketServerHandshakeException("handshake timed out"))) {
ctx.flush()
.fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT)
.close();
}
}
}, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
// Cancel the handshake timeout when handshake is finished.
localHandshakePromise.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> f) {
timeoutFuture.cancel(false);
}
});
}
}
| UTF-8 | Java | 7,875 | java | WebSocketServerProtocolHandshakeHandler.java | Java | [
{
"context": " //\n // See https://github.com/netty/netty/issues/9471.\n WebSocketS",
"end": 3680,
"score": 0.9993133544921875,
"start": 3675,
"tag": "USERNAME",
"value": "netty"
}
] | null | [] | /*
* Copyright 2019 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http.websocketx;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.ServerHandshakeStateEvent;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import java.util.concurrent.TimeUnit;
import static io.netty.handler.codec.http.HttpUtil.*;
import static io.netty.util.internal.ObjectUtil.*;
/**
* Handles the HTTP handshake (the HTTP Upgrade request) for {@link WebSocketServerProtocolHandler}.
*/
class WebSocketServerProtocolHandshakeHandler extends ChannelInboundHandlerAdapter {
private final WebSocketServerProtocolConfig serverConfig;
private ChannelHandlerContext ctx;
private ChannelPromise handshakePromise;
private boolean isWebSocketPath;
WebSocketServerProtocolHandshakeHandler(WebSocketServerProtocolConfig serverConfig) {
this.serverConfig = checkNotNull(serverConfig, "serverConfig");
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
this.ctx = ctx;
handshakePromise = ctx.newPromise();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
final HttpObject httpObject = (HttpObject) msg;
if (httpObject instanceof HttpRequest) {
final HttpRequest req = (HttpRequest) httpObject;
isWebSocketPath = isWebSocketPath(req);
if (!isWebSocketPath) {
ctx.fireChannelRead(msg);
return;
}
try {
final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(ctx.pipeline(), req, serverConfig.websocketPath()),
serverConfig.subprotocols(), serverConfig.decoderConfig());
final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
final ChannelPromise localHandshakePromise = handshakePromise;
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
// Ensure we set the handshaker and replace this handler before we
// trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
// before we had a chance to replace it.
//
// See https://github.com/netty/netty/issues/9471.
WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
ctx.pipeline().remove(this);
final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
handshakeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
localHandshakePromise.tryFailure(future.cause());
ctx.fireExceptionCaught(future.cause());
} else {
localHandshakePromise.trySuccess();
// Kept for compatibility
ctx.fireUserEventTriggered(
WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
ctx.fireUserEventTriggered(
new WebSocketServerProtocolHandler.HandshakeComplete(
req.uri(), req.headers(), handshaker.selectedSubprotocol()));
}
}
});
applyHandshakeTimeout();
}
} finally {
ReferenceCountUtil.release(req);
}
} else if (!isWebSocketPath) {
ctx.fireChannelRead(msg);
} else {
ReferenceCountUtil.release(msg);
}
}
private boolean isWebSocketPath(HttpRequest req) {
String websocketPath = serverConfig.websocketPath();
String uri = req.uri();
boolean checkStartUri = uri.startsWith(websocketPath);
boolean checkNextUri = "/".equals(websocketPath) || checkNextUri(uri, websocketPath);
return serverConfig.checkStartsWith() ? (checkStartUri && checkNextUri) : uri.equals(websocketPath);
}
private boolean checkNextUri(String uri, String websocketPath) {
int len = websocketPath.length();
if (uri.length() > len) {
char nextUri = uri.charAt(len);
return nextUri == '/' || nextUri == '?';
}
return true;
}
private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
ChannelFuture f = ctx.writeAndFlush(res);
if (!isKeepAlive(req) || res.status().code() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
String protocol = "ws";
if (cp.get(SslHandler.class) != null) {
// SSL in use so use Secure WebSockets
protocol = "wss";
}
String host = req.headers().get(HttpHeaderNames.HOST);
return protocol + "://" + host + path;
}
private void applyHandshakeTimeout() {
final ChannelPromise localHandshakePromise = handshakePromise;
final long handshakeTimeoutMillis = serverConfig.handshakeTimeoutMillis();
if (handshakeTimeoutMillis <= 0 || localHandshakePromise.isDone()) {
return;
}
final Future<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (!localHandshakePromise.isDone() &&
localHandshakePromise.tryFailure(new WebSocketServerHandshakeException("handshake timed out"))) {
ctx.flush()
.fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT)
.close();
}
}
}, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
// Cancel the handshake timeout when handshake is finished.
localHandshakePromise.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> f) {
timeoutFuture.cancel(false);
}
});
}
}
| 7,875 | 0.628952 | 0.626921 | 179 | 42.994415 | 31.509243 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564246 | false | false | 1 |
e1d3e66232183c5ee937ef735341218f30afb169 | 13,907,104,142,013 | 287a3ac57f57bf88454f6abe2d195635780154c1 | /app/src/main/java/com/app/diceroid/nerede/Activities/KidsAddActivity.java | 15dc8c88456163e1f9970088cd85bdab166f629a | [] | no_license | oguzzarci/AndroidLoginFireBase | https://github.com/oguzzarci/AndroidLoginFireBase | dcc1eb5cf5244c26102803be75849a5583d67ab8 | 93371019f361a8bcd4233b8c5b14783914c2ef93 | refs/heads/master | 2021-05-05T06:09:41.810000 | 2018-01-24T15:49:13 | 2018-01-24T15:49:13 | 118,784,435 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.app.diceroid.nerede.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.app.diceroid.nerede.R;
import com.app.diceroid.nerede.UserInformation;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class KidsAddActivity extends AppCompatActivity implements View.OnClickListener {
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private RadioButton timeOne;
private RadioButton timeFive;
private RadioButton timeThree;
private RadioButton timeEight;
private Button kidsAddButon;
private EditText editTextName;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kids_add);
firebaseAuth = FirebaseAuth.getInstance();
timeOne = (RadioButton) findViewById(R.id.timeOne);
timeThree = (RadioButton) findViewById(R.id.timeThree);
timeFive = (RadioButton) findViewById(R.id.timeFive);
timeEight = (RadioButton) findViewById(R.id.timeEight);
kidsAddButon = (Button) findViewById(R.id.kidsAddButon);
editTextName = (EditText) findViewById(R.id.editTextName);
textView = (TextView) findViewById(R.id.textView);
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
kidsAddButon.setOnClickListener(this);
}
private void kidsAdd(){
String name = editTextName.getText().toString().trim();
UserInformation userInformation = new UserInformation(name);
FirebaseUser user = firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
Toast.makeText(this,"Kayıt Başarılı",Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
if(view == kidsAddButon){
kidsAdd();
}
}
}
| UTF-8 | Java | 2,486 | java | KidsAddActivity.java | Java | [] | null | [] | package com.app.diceroid.nerede.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.app.diceroid.nerede.R;
import com.app.diceroid.nerede.UserInformation;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class KidsAddActivity extends AppCompatActivity implements View.OnClickListener {
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private RadioButton timeOne;
private RadioButton timeFive;
private RadioButton timeThree;
private RadioButton timeEight;
private Button kidsAddButon;
private EditText editTextName;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kids_add);
firebaseAuth = FirebaseAuth.getInstance();
timeOne = (RadioButton) findViewById(R.id.timeOne);
timeThree = (RadioButton) findViewById(R.id.timeThree);
timeFive = (RadioButton) findViewById(R.id.timeFive);
timeEight = (RadioButton) findViewById(R.id.timeEight);
kidsAddButon = (Button) findViewById(R.id.kidsAddButon);
editTextName = (EditText) findViewById(R.id.editTextName);
textView = (TextView) findViewById(R.id.textView);
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
kidsAddButon.setOnClickListener(this);
}
private void kidsAdd(){
String name = editTextName.getText().toString().trim();
UserInformation userInformation = new UserInformation(name);
FirebaseUser user = firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
Toast.makeText(this,"Kayıt Başarılı",Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
if(view == kidsAddButon){
kidsAdd();
}
}
}
| 2,486 | 0.72361 | 0.723207 | 83 | 28.903614 | 24.983664 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578313 | false | false | 1 |
f1124580a1370aee047bb2561ef8f4f73e5f457a | 11,570,641,895,486 | e3c14dca31d741f7b4e6341f32a9d8a6d232d254 | /stream-compare-server/src/main/java/com/sugon/gsq/scs/entity/LocalPasswordEntity.java | 09ce46fce5e8dd23e9c9852608837c516f8b50a0 | [] | no_license | fengzhongfeixu/stream-compare | https://github.com/fengzhongfeixu/stream-compare | b2e65f8304606318d536da622a7540a5436bc73e | 2181020097f8bbf2c4239f197368c5d5a3852933 | refs/heads/master | 2022-11-08T06:55:43.607000 | 2019-11-06T02:03:36 | 2019-11-06T02:03:36 | 219,890,582 | 1 | 0 | null | false | 2022-11-04T22:49:51 | 2019-11-06T02:01:55 | 2019-11-06T02:04:16 | 2022-11-04T22:49:51 | 3,406 | 0 | 0 | 5 | Java | false | false | package com.sugon.gsq.scs.entity;
import java.util.Date;
public class LocalPasswordEntity {
private Integer id;
private Integer localUserId;
private String password;
private Date expiresAt;
/*默认为 false*/
private Boolean selfService = false;
private Date createdAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getLocalUserId() {
return localUserId;
}
public void setLocalUserId(Integer localUserId) {
this.localUserId = localUserId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public Date getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
public Boolean getSelfService() {
return selfService;
}
public void setSelfService(Boolean selfService) {
this.selfService = selfService;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
}
| UTF-8 | Java | 1,275 | java | LocalPasswordEntity.java | Java | [
{
"context": "this.password = password == null ? null : password.trim();\n }\n\n public Date getExpiresAt() {\n ",
"end": 771,
"score": 0.5697118639945984,
"start": 767,
"tag": "PASSWORD",
"value": "trim"
}
] | null | [] | package com.sugon.gsq.scs.entity;
import java.util.Date;
public class LocalPasswordEntity {
private Integer id;
private Integer localUserId;
private String password;
private Date expiresAt;
/*默认为 false*/
private Boolean selfService = false;
private Date createdAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getLocalUserId() {
return localUserId;
}
public void setLocalUserId(Integer localUserId) {
this.localUserId = localUserId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.<PASSWORD>();
}
public Date getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
public Boolean getSelfService() {
return selfService;
}
public void setSelfService(Boolean selfService) {
this.selfService = selfService;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
}
| 1,281 | 0.628054 | 0.628054 | 66 | 18.227272 | 17.638453 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.30303 | false | false | 1 |
8df333417f86c31851f9032dbdd9b63d1d57f931 | 20,469,814,172,711 | 65aee608515bb994f9779741d564fc60fbe9432f | /base/src/main/java/com/flb/base/http/PassportUtils.java | 6ef2fceb5f2969bb1037bf3fa6c8053e99805bb9 | [] | no_license | flb775141545/base | https://github.com/flb775141545/base | 8624498ae07d61a2c28d6046b767fe8e180cd78d | 180973bd77606f886204f8696fe4730f6a7e1eac | refs/heads/master | 2021-01-11T04:00:22.831000 | 2016-10-19T14:09:01 | 2016-10-19T14:09:01 | 71,259,840 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.flb.base.http;
import javax.servlet.http.HttpServletRequest;
public abstract class PassportUtils
{
public static String getRemoteAddr(HttpServletRequest request)
{
String remoteAddr = request.getHeader("x-forwarded-for");
if (remoteAddr == null
|| "".equals(remoteAddr)
|| "unknown".equalsIgnoreCase(remoteAddr))
{
remoteAddr = request.getHeader("Proxy-Client-IP");
}
if (remoteAddr == null
|| "".equals(remoteAddr)
|| "unknown".equalsIgnoreCase(remoteAddr))
{
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
}
if (remoteAddr == null
|| "".equals(remoteAddr)
|| "unknown".equalsIgnoreCase(remoteAddr))
{
remoteAddr = request.getRemoteAddr();
}
if (remoteAddr != null && !"".equals(remoteAddr))
{
int index = remoteAddr.indexOf(",");
if (index != -1)
{
remoteAddr = remoteAddr.substring(0, index);
}
}
return remoteAddr;
}
} | UTF-8 | Java | 972 | java | PassportUtils.java | Java | [] | null | [] | package com.flb.base.http;
import javax.servlet.http.HttpServletRequest;
public abstract class PassportUtils
{
public static String getRemoteAddr(HttpServletRequest request)
{
String remoteAddr = request.getHeader("x-forwarded-for");
if (remoteAddr == null
|| "".equals(remoteAddr)
|| "unknown".equalsIgnoreCase(remoteAddr))
{
remoteAddr = request.getHeader("Proxy-Client-IP");
}
if (remoteAddr == null
|| "".equals(remoteAddr)
|| "unknown".equalsIgnoreCase(remoteAddr))
{
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
}
if (remoteAddr == null
|| "".equals(remoteAddr)
|| "unknown".equalsIgnoreCase(remoteAddr))
{
remoteAddr = request.getRemoteAddr();
}
if (remoteAddr != null && !"".equals(remoteAddr))
{
int index = remoteAddr.indexOf(",");
if (index != -1)
{
remoteAddr = remoteAddr.substring(0, index);
}
}
return remoteAddr;
}
} | 972 | 0.632716 | 0.630658 | 44 | 20.136364 | 20.675623 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.340909 | false | false | 1 |
1f2eb3e5d9c8684c405fee46b4e0f1e019176b0e | 19,524,921,332,551 | f823f023ce0835c62a35c3fad6f03df26802b0cf | /apps/dolly-backend/src/main/java/no/nav/dolly/bestilling/arenaforvalter/ArenaForvalterClient.java | 6bea324edab7e9926e1aaf597e54832922e609dd | [
"MIT"
] | permissive | abdukerim/testnorge | https://github.com/abdukerim/testnorge | b4778f97f9a51d3591aa29d7ef8bfb1c1f11cdd9 | 31ea38d2286db6de244eb1ab71c4751cc01f8d05 | refs/heads/master | 2023-08-23T11:49:12.549000 | 2021-11-03T14:10:23 | 2021-11-03T14:10:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package no.nav.dolly.bestilling.arenaforvalter;
import io.swagger.v3.core.util.Json;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import no.nav.dolly.bestilling.ClientRegister;
import no.nav.dolly.domain.jpa.BestillingProgress;
import no.nav.dolly.domain.resultset.RsDollyUtvidetBestilling;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaArbeidssokerBruker;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaDagpenger;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaNyBruker;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaNyeBrukere;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaNyeBrukereResponse;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaNyeDagpengerResponse;
import no.nav.dolly.domain.resultset.tpsf.DollyPerson;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
@Slf4j
@Service
@RequiredArgsConstructor
public class ArenaForvalterClient implements ClientRegister {
private final ArenaForvalterConsumer arenaForvalterConsumer;
private final MapperFacade mapperFacade;
@Override
public void gjenopprett(RsDollyUtvidetBestilling bestilling, DollyPerson dollyPerson, BestillingProgress progress, boolean isOpprettEndre) {
if (nonNull(bestilling.getArenaforvalter())) {
StringBuilder status = new StringBuilder();
List<String> environments = arenaForvalterConsumer.getEnvironments();
List<String> availEnvironments = new ArrayList<>(environments);
availEnvironments.retainAll(bestilling.getEnvironments());
if (!availEnvironments.isEmpty()) {
if (!isOpprettEndre) {
deleteServicebruker(dollyPerson.getHovedperson(), availEnvironments);
}
ArenaNyeBrukere arenaNyeBrukere = new ArenaNyeBrukere();
List<ArenaDagpenger> dagpengerListe = new ArrayList<>();
availEnvironments.forEach(environment -> {
ArenaNyBruker arenaNyBruker = mapperFacade.map(bestilling.getArenaforvalter(), ArenaNyBruker.class);
arenaNyBruker.setPersonident(dollyPerson.getHovedperson());
arenaNyBruker.setMiljoe(environment);
arenaNyeBrukere.getNyeBrukere().add(arenaNyBruker);
if (!bestilling.getArenaforvalter().getDagpenger().isEmpty()) {
ArenaDagpenger arenaDagpenger = mapperFacade.map(bestilling.getArenaforvalter(), ArenaDagpenger.class);
arenaDagpenger.setPersonident(dollyPerson.getHovedperson());
arenaDagpenger.setMiljoe(environment);
dagpengerListe.add(arenaDagpenger);
}
});
sendArenadata(arenaNyeBrukere, status, dagpengerListe.isEmpty());
dagpengerListe.forEach(dagpenger -> sendArenadagpenger(dagpenger, status));
}
List<String> notSupportedEnvironments = new ArrayList<>(bestilling.getEnvironments());
notSupportedEnvironments.removeAll(environments);
notSupportedEnvironments.forEach(environment ->
status.append(',')
.append(environment)
.append("$Feil: Miljø ikke støttet"));
if (status.length() > 1) {
progress.setArenaforvalterStatus(status.substring(1));
}
}
}
@Override
public void release(List<String> identer) {
identer.forEach(ident -> {
ResponseEntity<ArenaArbeidssokerBruker> existingServicebruker = arenaForvalterConsumer.getIdent(ident);
if (existingServicebruker.hasBody()) {
existingServicebruker.getBody().getArbeidsokerList().forEach(list -> {
if (nonNull(list.getMiljoe())) {
List.of(list.getMiljoe().split(",")).forEach(
environment -> arenaForvalterConsumer.deleteIdent(ident, environment));
}
});
}
});
}
private void deleteServicebruker(String ident, List<String> availEnvironments) {
try {
availEnvironments.forEach(environment ->
arenaForvalterConsumer.deleteIdent(ident, environment));
} catch (RuntimeException e) {
log.error("Feilet å inaktivere testperson: {} i ArenaForvalter: ", ident, e);
}
}
private void sendArenadagpenger(ArenaDagpenger arenaNyeDagpenger, StringBuilder status) {
try {
log.info("Sender dagpenger: \n" + Json.pretty(arenaNyeDagpenger));
ResponseEntity<ArenaNyeDagpengerResponse> response = arenaForvalterConsumer.postArenaDagpenger(arenaNyeDagpenger);
log.info("Dagpenger mottatt: \n" + Json.pretty(response));
if (response.hasBody()) {
if (nonNull(response.getBody().getNyeDagpFeilList()) && !response.getBody().getNyeDagpFeilList().isEmpty()) {
response.getBody().getNyeDagpFeilList().forEach(brukerfeil -> {
log.info("Brukerfeil dagpenger: " + Json.pretty(brukerfeil));
status.append(',')
.append(brukerfeil.getMiljoe())
.append("$Feilstatus dagpenger: \"")
.append(brukerfeil.getNyDagpFeilstatus())
.append("\". Se detaljer i logg.");
log.error("Feilet å opprette dagpenger for testperson {} i ArenaForvalter på miljø: {}, feilstatus: {}, melding: \"{}\"",
brukerfeil.getPersonident(), brukerfeil.getMiljoe(), brukerfeil.getNyDagpFeilstatus(), brukerfeil.getMelding());
});
} else if (nonNull(response.getBody().getNyeDagp()) && !response.getBody().getNyeDagp().isEmpty()
&& (nonNull(response.getBody().getNyeDagp().get(0).getNyeDagpResponse()))) {
status.append(',')
.append(arenaNyeDagpenger.getMiljoe())
.append(
response.getBody().getNyeDagp().get(0).getNyeDagpResponse().getUtfall().equals("JA")
? "$OK"
: "$Feil dagpenger: " + response.getBody().getNyeDagp().get(0).getNyeDagpResponse().getBegrunnelse());
} else {
status.append(',')
.append(arenaNyeDagpenger.getMiljoe())
.append("$OK");
}
} else {
status.append(',')
.append(arenaNyeDagpenger.getMiljoe())
.append("Feilstatus: Mottok ugyldig dagpenge respons fra Arena");
}
} catch (RuntimeException e) {
status.append(',')
.append(arenaNyeDagpenger.getMiljoe())
.append('$');
appendErrorText(status, e);
log.error("Feilet å legge til dagpenger i Arena: ", e);
}
}
private void sendArenadata(ArenaNyeBrukere arenaNyeBrukere, StringBuilder status, boolean harIkkeDagpenger) {
try {
ArenaNyeBrukere filtrerteBrukere = filtrerEksisterendeBrukere(arenaNyeBrukere);
if (filtrerteBrukere.getNyeBrukere().isEmpty()) {
log.info("Alle brukere eksisterer i Arena allerede.");
return;
}
ResponseEntity<ArenaNyeBrukereResponse> response = arenaForvalterConsumer.postArenadata(arenaNyeBrukere);
if (response.hasBody()) {
if (nonNull((response.getBody().getArbeidsokerList()))) {
response.getBody().getArbeidsokerList().forEach(arbeidsoker -> {
if ("OK".equals(arbeidsoker.getStatus()) && harIkkeDagpenger) {
status.append(',')
.append(arbeidsoker.getMiljoe())
.append('$')
.append(arbeidsoker.getStatus());
}
});
}
if (nonNull(response.getBody().getNyBrukerFeilList())) {
response.getBody().getNyBrukerFeilList().forEach(brukerfeil -> {
status.append(',')
.append(brukerfeil.getMiljoe())
.append("$Feilstatus: \"")
.append(brukerfeil.getNyBrukerFeilstatus())
.append("\". Se detaljer i logg.");
log.error("Feilet å opprette testperson {} i ArenaForvalter på miljø: {}, feilstatus: {}, melding: \"{}\"",
brukerfeil.getPersonident(), brukerfeil.getMiljoe(), brukerfeil.getNyBrukerFeilstatus(), brukerfeil.getMelding());
});
}
}
} catch (WebClientResponseException e) {
arenaNyeBrukere.getNyeBrukere().forEach(bruker -> {
status.append(',')
.append(bruker.getMiljoe())
.append('$');
appendErrorText(status, e);
});
log.error("Feilet å legge inn ny testperson i Arena: ", e);
}
}
private ArenaNyeBrukere filtrerEksisterendeBrukere(ArenaNyeBrukere arenaNyeBrukere) {
return new ArenaNyeBrukere(arenaNyeBrukere.getNyeBrukere().stream()
.filter(arenaNyBruker ->
(!isNull(arenaNyBruker.getKvalifiseringsgruppe()) || !isNull(arenaNyBruker.getUtenServicebehov())))
.collect(Collectors.toList()));
}
private static void appendErrorText(StringBuilder status, RuntimeException e) {
status.append("Feil: ")
.append(nonNull(e.getMessage()) ? e.getMessage().replace(',', ';') : e);
if (e instanceof HttpClientErrorException) {
status.append(" (")
.append(((HttpClientErrorException) e).getResponseBodyAsString().replace(',', '='))
.append(')');
}
}
}
| UTF-8 | Java | 10,796 | java | ArenaForvalterClient.java | Java | [] | null | [] | package no.nav.dolly.bestilling.arenaforvalter;
import io.swagger.v3.core.util.Json;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import no.nav.dolly.bestilling.ClientRegister;
import no.nav.dolly.domain.jpa.BestillingProgress;
import no.nav.dolly.domain.resultset.RsDollyUtvidetBestilling;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaArbeidssokerBruker;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaDagpenger;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaNyBruker;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaNyeBrukere;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaNyeBrukereResponse;
import no.nav.dolly.domain.resultset.arenaforvalter.ArenaNyeDagpengerResponse;
import no.nav.dolly.domain.resultset.tpsf.DollyPerson;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
@Slf4j
@Service
@RequiredArgsConstructor
public class ArenaForvalterClient implements ClientRegister {
private final ArenaForvalterConsumer arenaForvalterConsumer;
private final MapperFacade mapperFacade;
@Override
public void gjenopprett(RsDollyUtvidetBestilling bestilling, DollyPerson dollyPerson, BestillingProgress progress, boolean isOpprettEndre) {
if (nonNull(bestilling.getArenaforvalter())) {
StringBuilder status = new StringBuilder();
List<String> environments = arenaForvalterConsumer.getEnvironments();
List<String> availEnvironments = new ArrayList<>(environments);
availEnvironments.retainAll(bestilling.getEnvironments());
if (!availEnvironments.isEmpty()) {
if (!isOpprettEndre) {
deleteServicebruker(dollyPerson.getHovedperson(), availEnvironments);
}
ArenaNyeBrukere arenaNyeBrukere = new ArenaNyeBrukere();
List<ArenaDagpenger> dagpengerListe = new ArrayList<>();
availEnvironments.forEach(environment -> {
ArenaNyBruker arenaNyBruker = mapperFacade.map(bestilling.getArenaforvalter(), ArenaNyBruker.class);
arenaNyBruker.setPersonident(dollyPerson.getHovedperson());
arenaNyBruker.setMiljoe(environment);
arenaNyeBrukere.getNyeBrukere().add(arenaNyBruker);
if (!bestilling.getArenaforvalter().getDagpenger().isEmpty()) {
ArenaDagpenger arenaDagpenger = mapperFacade.map(bestilling.getArenaforvalter(), ArenaDagpenger.class);
arenaDagpenger.setPersonident(dollyPerson.getHovedperson());
arenaDagpenger.setMiljoe(environment);
dagpengerListe.add(arenaDagpenger);
}
});
sendArenadata(arenaNyeBrukere, status, dagpengerListe.isEmpty());
dagpengerListe.forEach(dagpenger -> sendArenadagpenger(dagpenger, status));
}
List<String> notSupportedEnvironments = new ArrayList<>(bestilling.getEnvironments());
notSupportedEnvironments.removeAll(environments);
notSupportedEnvironments.forEach(environment ->
status.append(',')
.append(environment)
.append("$Feil: Miljø ikke støttet"));
if (status.length() > 1) {
progress.setArenaforvalterStatus(status.substring(1));
}
}
}
@Override
public void release(List<String> identer) {
identer.forEach(ident -> {
ResponseEntity<ArenaArbeidssokerBruker> existingServicebruker = arenaForvalterConsumer.getIdent(ident);
if (existingServicebruker.hasBody()) {
existingServicebruker.getBody().getArbeidsokerList().forEach(list -> {
if (nonNull(list.getMiljoe())) {
List.of(list.getMiljoe().split(",")).forEach(
environment -> arenaForvalterConsumer.deleteIdent(ident, environment));
}
});
}
});
}
private void deleteServicebruker(String ident, List<String> availEnvironments) {
try {
availEnvironments.forEach(environment ->
arenaForvalterConsumer.deleteIdent(ident, environment));
} catch (RuntimeException e) {
log.error("Feilet å inaktivere testperson: {} i ArenaForvalter: ", ident, e);
}
}
private void sendArenadagpenger(ArenaDagpenger arenaNyeDagpenger, StringBuilder status) {
try {
log.info("Sender dagpenger: \n" + Json.pretty(arenaNyeDagpenger));
ResponseEntity<ArenaNyeDagpengerResponse> response = arenaForvalterConsumer.postArenaDagpenger(arenaNyeDagpenger);
log.info("Dagpenger mottatt: \n" + Json.pretty(response));
if (response.hasBody()) {
if (nonNull(response.getBody().getNyeDagpFeilList()) && !response.getBody().getNyeDagpFeilList().isEmpty()) {
response.getBody().getNyeDagpFeilList().forEach(brukerfeil -> {
log.info("Brukerfeil dagpenger: " + Json.pretty(brukerfeil));
status.append(',')
.append(brukerfeil.getMiljoe())
.append("$Feilstatus dagpenger: \"")
.append(brukerfeil.getNyDagpFeilstatus())
.append("\". Se detaljer i logg.");
log.error("Feilet å opprette dagpenger for testperson {} i ArenaForvalter på miljø: {}, feilstatus: {}, melding: \"{}\"",
brukerfeil.getPersonident(), brukerfeil.getMiljoe(), brukerfeil.getNyDagpFeilstatus(), brukerfeil.getMelding());
});
} else if (nonNull(response.getBody().getNyeDagp()) && !response.getBody().getNyeDagp().isEmpty()
&& (nonNull(response.getBody().getNyeDagp().get(0).getNyeDagpResponse()))) {
status.append(',')
.append(arenaNyeDagpenger.getMiljoe())
.append(
response.getBody().getNyeDagp().get(0).getNyeDagpResponse().getUtfall().equals("JA")
? "$OK"
: "$Feil dagpenger: " + response.getBody().getNyeDagp().get(0).getNyeDagpResponse().getBegrunnelse());
} else {
status.append(',')
.append(arenaNyeDagpenger.getMiljoe())
.append("$OK");
}
} else {
status.append(',')
.append(arenaNyeDagpenger.getMiljoe())
.append("Feilstatus: Mottok ugyldig dagpenge respons fra Arena");
}
} catch (RuntimeException e) {
status.append(',')
.append(arenaNyeDagpenger.getMiljoe())
.append('$');
appendErrorText(status, e);
log.error("Feilet å legge til dagpenger i Arena: ", e);
}
}
private void sendArenadata(ArenaNyeBrukere arenaNyeBrukere, StringBuilder status, boolean harIkkeDagpenger) {
try {
ArenaNyeBrukere filtrerteBrukere = filtrerEksisterendeBrukere(arenaNyeBrukere);
if (filtrerteBrukere.getNyeBrukere().isEmpty()) {
log.info("Alle brukere eksisterer i Arena allerede.");
return;
}
ResponseEntity<ArenaNyeBrukereResponse> response = arenaForvalterConsumer.postArenadata(arenaNyeBrukere);
if (response.hasBody()) {
if (nonNull((response.getBody().getArbeidsokerList()))) {
response.getBody().getArbeidsokerList().forEach(arbeidsoker -> {
if ("OK".equals(arbeidsoker.getStatus()) && harIkkeDagpenger) {
status.append(',')
.append(arbeidsoker.getMiljoe())
.append('$')
.append(arbeidsoker.getStatus());
}
});
}
if (nonNull(response.getBody().getNyBrukerFeilList())) {
response.getBody().getNyBrukerFeilList().forEach(brukerfeil -> {
status.append(',')
.append(brukerfeil.getMiljoe())
.append("$Feilstatus: \"")
.append(brukerfeil.getNyBrukerFeilstatus())
.append("\". Se detaljer i logg.");
log.error("Feilet å opprette testperson {} i ArenaForvalter på miljø: {}, feilstatus: {}, melding: \"{}\"",
brukerfeil.getPersonident(), brukerfeil.getMiljoe(), brukerfeil.getNyBrukerFeilstatus(), brukerfeil.getMelding());
});
}
}
} catch (WebClientResponseException e) {
arenaNyeBrukere.getNyeBrukere().forEach(bruker -> {
status.append(',')
.append(bruker.getMiljoe())
.append('$');
appendErrorText(status, e);
});
log.error("Feilet å legge inn ny testperson i Arena: ", e);
}
}
private ArenaNyeBrukere filtrerEksisterendeBrukere(ArenaNyeBrukere arenaNyeBrukere) {
return new ArenaNyeBrukere(arenaNyeBrukere.getNyeBrukere().stream()
.filter(arenaNyBruker ->
(!isNull(arenaNyBruker.getKvalifiseringsgruppe()) || !isNull(arenaNyBruker.getUtenServicebehov())))
.collect(Collectors.toList()));
}
private static void appendErrorText(StringBuilder status, RuntimeException e) {
status.append("Feil: ")
.append(nonNull(e.getMessage()) ? e.getMessage().replace(',', ';') : e);
if (e instanceof HttpClientErrorException) {
status.append(" (")
.append(((HttpClientErrorException) e).getResponseBodyAsString().replace(',', '='))
.append(')');
}
}
}
| 10,796 | 0.584886 | 0.584052 | 230 | 45.891304 | 37.138302 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582609 | false | false | 1 |
f4f7ada5a8964a3d049d2dccc48e158f1f96e40b | 26,697,516,726,575 | e138c05a75b2d9c464b4d22c0024c53a462f0894 | /src/main/java/pl/infoshare/nine/model/Car.java | 58bb7a835f0912cc96d5d4a78db7955c84ea8c3e | [] | no_license | lewis657/warsztaty-java-gdansk2-eu | https://github.com/lewis657/warsztaty-java-gdansk2-eu | 9268ddc9bb5d39f2b589695ffdc6e5e2dd754c2e | bed7b7269bbdb3fc5de576afdc80e6621d19b4a3 | refs/heads/master | 2020-04-04T11:12:29.618000 | 2018-11-14T19:06:09 | 2018-11-14T19:06:09 | 155,882,381 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.infoshare.nine.model;
import pl.infoshare.nine.impl.Fiat;
import pl.infoshare.nine.impl.Mercedes;
public class Car {
int kola = 4 ;
int szyby = 6;
public Car() {
System.out.println("Tworze klase Car");
}
public Car(int kola, int szyby) {
this.kola = kola;
this.szyby = szyby;
}
}
| UTF-8 | Java | 349 | java | Car.java | Java | [] | null | [] | package pl.infoshare.nine.model;
import pl.infoshare.nine.impl.Fiat;
import pl.infoshare.nine.impl.Mercedes;
public class Car {
int kola = 4 ;
int szyby = 6;
public Car() {
System.out.println("Tworze klase Car");
}
public Car(int kola, int szyby) {
this.kola = kola;
this.szyby = szyby;
}
}
| 349 | 0.598854 | 0.593123 | 24 | 13.541667 | 15.340522 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 1 |
3e30282d1954d506dfc5f3416215fdc124d87f0b | 23,416,161,760,296 | c2f9f0720e822ec1d1127db6d57ebd8220fb4182 | /dbProject/src/com/example/test/MyListAdapter.java | 68cf1364e427c7ba80d72fc8c4e5097098eb4b7a | [] | no_license | parkjinyoung/2014dbProject | https://github.com/parkjinyoung/2014dbProject | ddaff8854f8ba54429115ee2d7db8a14767bf391 | eb1925fef94f60a22fe45f153b9cdcefd1bc6aca | refs/heads/master | 2021-01-10T21:07:40.993000 | 2020-12-08T16:48:23 | 2020-12-08T16:48:23 | 18,587,967 | 0 | 0 | null | false | 2014-04-11T10:45:11 | 2014-04-09T06:43:10 | 2014-04-09T14:44:27 | 2014-04-09T14:44:26 | 0 | 0 | 1 | 2 | Java | null | null | package com.example.test;
import java.util.ArrayList;
import object.Comment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<Comment>{
private ArrayList<Comment> items;
private int rsrc;
public MyListAdapter(Context context, int resource, int textViewResourceId,
ArrayList<Comment> objects) {
super(context, resource, textViewResourceId, objects);
this.items = objects;
this.rsrc = resource;
// TODO Auto-generated constructor stub
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(rsrc, null);
}
Comment e = items.get(position);
if (e != null) {
((TextView)v.findViewById(R.id.snumenu_detail_comment_text)).setText(e.getComment());
}
return v;
}
}
| UTF-8 | Java | 1,211 | java | MyListAdapter.java | Java | [] | null | [] | package com.example.test;
import java.util.ArrayList;
import object.Comment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<Comment>{
private ArrayList<Comment> items;
private int rsrc;
public MyListAdapter(Context context, int resource, int textViewResourceId,
ArrayList<Comment> objects) {
super(context, resource, textViewResourceId, objects);
this.items = objects;
this.rsrc = resource;
// TODO Auto-generated constructor stub
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(rsrc, null);
}
Comment e = items.get(position);
if (e != null) {
((TextView)v.findViewById(R.id.snumenu_detail_comment_text)).setText(e.getComment());
}
return v;
}
}
| 1,211 | 0.668869 | 0.668869 | 38 | 29.789474 | 25.721338 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.105263 | false | false | 1 |
2b9aac56a745a9480ee438acf309414622f3087f | 31,705,448,580,907 | f545498f9a0741a9e45340ce4843646846cce59a | /Netty/exer-netty/spring-netty-common/src/main/java/com/briskhu/exercize/springnetty/common/util/ApplicationContextUtil.java | 02e45cb150ee5fd4923efc05ec3befa923fda741 | [] | no_license | BriskHu/exercise-java-web | https://github.com/BriskHu/exercise-java-web | 7ab71c5b198ee6f16ce0fbb060d5aa06adfcac84 | 50fba20d8e7b0f244678b69f040f18b293790c40 | refs/heads/master | 2022-11-24T05:27:29.433000 | 2021-03-14T06:08:22 | 2021-03-14T06:08:22 | 209,778,208 | 0 | 0 | null | false | 2022-11-15T23:56:17 | 2019-09-20T11:48:32 | 2021-03-14T06:13:02 | 2022-11-15T23:56:14 | 155 | 0 | 0 | 8 | Java | false | false | package com.briskhu.exercize.springnetty.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* <p/>
*
* @author Brisk Hu
* created on 2019-12-09
**/
public class ApplicationContextUtil implements ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextUtil.class);
/* ---------------------------------------- fileds ---------------------------------------- */
private static ApplicationContext applicationContext;
/* ---------------------------------------- methods ---------------------------------------- */
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName, Class<T> beanClass){
return ApplicationContextUtil.applicationContext.getBean(beanName, beanClass);
}
}
| UTF-8 | Java | 1,240 | java | ApplicationContextUtil.java | Java | [
{
"context": "pplicationContextAware;\n\n/**\n * <p/>\n *\n * @author Brisk Hu\n * created on 2019-12-09\n **/\npublic class Applic",
"end": 311,
"score": 0.999523937702179,
"start": 303,
"tag": "NAME",
"value": "Brisk Hu"
}
] | null | [] | package com.briskhu.exercize.springnetty.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* <p/>
*
* @author <NAME>
* created on 2019-12-09
**/
public class ApplicationContextUtil implements ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextUtil.class);
/* ---------------------------------------- fileds ---------------------------------------- */
private static ApplicationContext applicationContext;
/* ---------------------------------------- methods ---------------------------------------- */
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName, Class<T> beanClass){
return ApplicationContextUtil.applicationContext.getBean(beanName, beanClass);
}
}
| 1,238 | 0.665323 | 0.657258 | 38 | 31.578947 | 34.592842 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.342105 | false | false | 1 |
f3845edcf128579c0ce573318d28f769fb8c686b | 26,637,387,184,587 | c6d807c0c0272f7a564a2818c1a70b9f816b2520 | /src/main/java/com/wkk/everyday/june/WordBreak.java | 5b1994463f48e3c88f7ff38fc0a182eeaf0d59c3 | [] | no_license | lcaczk/LuckCode | https://github.com/lcaczk/LuckCode | d645e7d763a2bda648656ba65ba68f280d510985 | 478962b9ed778ffc02950eb73b2488a68b578390 | refs/heads/master | 2023-05-03T13:07:11.197000 | 2021-05-29T02:39:00 | 2021-05-29T02:39:00 | 200,884,339 | 0 | 0 | null | false | 2020-10-14T09:27:18 | 2019-08-06T16:06:26 | 2020-10-11T15:04:29 | 2020-10-14T09:27:17 | 5,520 | 0 | 0 | 0 | Java | false | false | package com.wkk.everyday.june;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @Time: 2020/6/25上午9:12
* @Author: kongwiki
* @Email: kongwiki@163.com
*/
public class WordBreak {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
Set<String> word = new HashSet<>(wordDict);
for(int i = 1; i<=s.length(); i++){
for(int j = 0; j< i; j++){
if(dp[j] && word.contains(s.substring(j, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
public static void main(String[] args) {
String s = "leetcode";
List<String> wordDict = new ArrayList(){{
add("leet");
add("code");
}};
WordBreak wordBreak = new WordBreak();
boolean b = wordBreak.wordBreak(s, wordDict);
System.out.println(b);
}
}
| UTF-8 | Java | 1,048 | java | WordBreak.java | Java | [
{
"context": "il.Set;\n\n/**\n * @Time: 2020/6/25上午9:12\n * @Author: kongwiki\n * @Email: kongwiki@163.com\n */\npublic class Word",
"end": 182,
"score": 0.9996272921562195,
"start": 174,
"tag": "USERNAME",
"value": "kongwiki"
},
{
"context": "e: 2020/6/25上午9:12\n * @Author: kongwiki\n * @Email: kongwiki@163.com\n */\npublic class WordBreak {\n public boolean w",
"end": 210,
"score": 0.9999215602874756,
"start": 194,
"tag": "EMAIL",
"value": "kongwiki@163.com"
}
] | null | [] | package com.wkk.everyday.june;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @Time: 2020/6/25上午9:12
* @Author: kongwiki
* @Email: <EMAIL>
*/
public class WordBreak {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length()+1];
dp[0] = true;
Set<String> word = new HashSet<>(wordDict);
for(int i = 1; i<=s.length(); i++){
for(int j = 0; j< i; j++){
if(dp[j] && word.contains(s.substring(j, i))){
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
public static void main(String[] args) {
String s = "leetcode";
List<String> wordDict = new ArrayList(){{
add("leet");
add("code");
}};
WordBreak wordBreak = new WordBreak();
boolean b = wordBreak.wordBreak(s, wordDict);
System.out.println(b);
}
}
| 1,039 | 0.517241 | 0.500958 | 40 | 25.1 | 17.653328 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 1 |
a744df2ba6030505c8d25d3c0dd9dcf194995af8 | 11,673,721,118,258 | 10cdd064a8e754c506de18d413bba4c928254903 | /src/main/java/cn/bdqn/gph/service/impl/SellerServiceImpl.java | 3cec305a0736dcc3a524c5326f35293daba334e6 | [] | no_license | Wu-2464/gph | https://github.com/Wu-2464/gph | 78de25ad727cab5ed2eab2a94b1752e3a1f3217c | 2289a01994190de9ccb1221e95425740cd5678fa | refs/heads/master | 2022-06-24T14:35:27.250000 | 2020-04-09T07:43:53 | 2020-04-09T07:43:53 | 254,304,618 | 0 | 0 | null | false | 2021-04-26T20:09:03 | 2020-04-09T07:43:36 | 2020-04-09T07:45:16 | 2021-04-26T20:09:03 | 12,969 | 0 | 0 | 1 | CSS | false | false | package cn.bdqn.gph.service.impl;
import cn.bdqn.gph.entity.Seller;
import cn.bdqn.gph.mapper.SellerMapper;
import cn.bdqn.gph.service.ISellerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ljh
* @since 2020-03-18
*/
@Service
public class SellerServiceImpl extends ServiceImpl<SellerMapper, Seller> implements ISellerService {
}
| UTF-8 | Java | 463 | java | SellerServiceImpl.java | Java | [
{
"context": "rvice;\n\n/**\n * <p>\n * 服务实现类\n * </p>\n *\n * @author ljh\n * @since 2020-03-18\n */\n@Service\npublic class Se",
"end": 314,
"score": 0.999497652053833,
"start": 311,
"tag": "USERNAME",
"value": "ljh"
}
] | null | [] | package cn.bdqn.gph.service.impl;
import cn.bdqn.gph.entity.Seller;
import cn.bdqn.gph.mapper.SellerMapper;
import cn.bdqn.gph.service.ISellerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ljh
* @since 2020-03-18
*/
@Service
public class SellerServiceImpl extends ServiceImpl<SellerMapper, Seller> implements ISellerService {
}
| 463 | 0.766004 | 0.748344 | 20 | 21.65 | 26.021673 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 1 |
4e25b0208908c240ef50792dcc1fa35a931b6078 | 24,068,996,728,309 | 07099dfefc09bd3293b53671be6691063dd5cf30 | /BackEnd/themis-notice/src/main/java/com/oxchains/themis/notice/domain/BTCResult.java | cde6831ba8ee7a6caedebe8e51f46a8985b102d4 | [
"MIT"
] | permissive | themis-network/themis-otc | https://github.com/themis-network/themis-otc | 7206ea645106ca6904a3ffb391a8b8a0471fe319 | d1a69ed0aa36f264e0deff6b1e31a1d76705d072 | refs/heads/master | 2018-10-15T02:45:58.388000 | 2018-09-14T10:28:58 | 2018-09-14T10:28:58 | 113,821,976 | 6 | 6 | MIT | false | 2018-08-31T02:58:26 | 2017-12-11T06:37:02 | 2018-07-20T08:10:25 | 2018-08-31T02:58:25 | 30,177 | 3 | 4 | 0 | Java | false | null | package com.oxchains.themis.notice.domain;
import lombok.Data;
import javax.persistence.*;
/**
* @author luoxuri
* @create 2017-10-24 19:01
**/
@Entity
@Data
@Table(name = "btc_result")
public class BTCResult {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String des;
@Column(name = "issuc")
private String isSuc;
@Transient
private BTCMarket datas;
}
| UTF-8 | Java | 428 | java | BTCResult.java | Java | [
{
"context": "Data;\n\nimport javax.persistence.*;\n\n/**\n * @author luoxuri\n * @create 2017-10-24 19:01\n **/\n@Entity\n@Data\n@T",
"end": 116,
"score": 0.999565839767456,
"start": 109,
"tag": "USERNAME",
"value": "luoxuri"
}
] | null | [] | package com.oxchains.themis.notice.domain;
import lombok.Data;
import javax.persistence.*;
/**
* @author luoxuri
* @create 2017-10-24 19:01
**/
@Entity
@Data
@Table(name = "btc_result")
public class BTCResult {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String des;
@Column(name = "issuc")
private String isSuc;
@Transient
private BTCMarket datas;
}
| 428 | 0.670561 | 0.642523 | 29 | 13.75862 | 14.063048 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.241379 | false | false | 1 |
5908fc3fdcbca1a8ba72f9b8a55464a5a64a8657 | 28,458,453,371,589 | 9627aa196b5518fa3226a48c8bf4db9a830fc951 | /Project/src/main/java/com/asgdrones/drones/enums/Courses.java | fc473c26b25c86815724570516b2cf24785ff68c | [] | no_license | JamesBuckland98/security_project | https://github.com/JamesBuckland98/security_project | b2ab294c419a136c853640c30b1babf23dc272eb | b506cfda31f222975b98c2d7bca7a527f2e864b4 | refs/heads/master | 2022-07-19T09:34:52.362000 | 2019-05-09T19:17:13 | 2019-05-09T19:17:13 | 264,645,312 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asgdrones.drones.enums;
public enum Courses {
COURSE_1("type1"),
COURSE_2("type2"),
COURSE_3("type3");
private final String name;
private Courses(String s) {
name = s;
}
public String toString() {
return this.name;
}
}
| UTF-8 | Java | 284 | java | Courses.java | Java | [] | null | [] | package com.asgdrones.drones.enums;
public enum Courses {
COURSE_1("type1"),
COURSE_2("type2"),
COURSE_3("type3");
private final String name;
private Courses(String s) {
name = s;
}
public String toString() {
return this.name;
}
}
| 284 | 0.580986 | 0.559859 | 18 | 14.777778 | 12.721616 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 1 |
ac1386c0ac837686174764fcac66db21a7c28fe3 | 8,169,027,809,917 | 2fdb3b716f7803b190f409513d0a28b3a32943f5 | /sayhello-spring-boot-starter/src/main/java/com/zdy/mystarter/spring/core/ZDYAttributeAccessor.java | 786372042bbfc66f53ffebf1537a2066f3ade5f9 | [] | no_license | xiaofengwl/learn-zdystarter | https://github.com/xiaofengwl/learn-zdystarter | a9da8b6db56041ed02da24048c17a7f3998879bb | 52f158b15117812cb9d9f11df7942e221f16a6f5 | refs/heads/master | 2023-01-31T19:16:06.175000 | 2020-12-18T15:23:25 | 2020-12-18T15:23:25 | 322,627,103 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zdy.mystarter.spring.core;
/**
* TODO IOC容器学习·AttributeAccessor
* <pre>
* 定义了一些关于属性的操作方法
* </pre>
*
* @author lvjun
* @version 1.0
* @date 2020/3/22 14:15
* @desc
*/
public interface ZDYAttributeAccessor {
/**
* 设置属性
* @param var1
* @param var2
*/
void setAttribute(String var1, Object var2);
/**
* 获取属性
* @param var1
* @return
*/
Object getAttribute(String var1);
/**
* 移除属性
* @param var1
* @return
*/
Object removeAttribute(String var1);
/**
* 判断是否有某种属性
* @param var1
* @return
*/
boolean hasAttribute(String var1);
/**
* 获取属性的名称
*
* @return
*/
String[] attributeNames();
}
| UTF-8 | Java | 842 | java | ZDYAttributeAccessor.java | Java | [
{
"context": "pre>\n * 定义了一些关于属性的操作方法\n * </pre>\n *\n * @author lvjun\n * @version 1.0\n * @date 2020/3/22 14:15\n * @desc",
"end": 138,
"score": 0.9996641278266907,
"start": 133,
"tag": "USERNAME",
"value": "lvjun"
}
] | null | [] | package com.zdy.mystarter.spring.core;
/**
* TODO IOC容器学习·AttributeAccessor
* <pre>
* 定义了一些关于属性的操作方法
* </pre>
*
* @author lvjun
* @version 1.0
* @date 2020/3/22 14:15
* @desc
*/
public interface ZDYAttributeAccessor {
/**
* 设置属性
* @param var1
* @param var2
*/
void setAttribute(String var1, Object var2);
/**
* 获取属性
* @param var1
* @return
*/
Object getAttribute(String var1);
/**
* 移除属性
* @param var1
* @return
*/
Object removeAttribute(String var1);
/**
* 判断是否有某种属性
* @param var1
* @return
*/
boolean hasAttribute(String var1);
/**
* 获取属性的名称
*
* @return
*/
String[] attributeNames();
}
| 842 | 0.52737 | 0.496662 | 51 | 13.686275 | 12.20172 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.137255 | false | false | 1 |
775e1e7c56e6ce0c63529d67dd3868c3572d8853 | 3,564,822,863,724 | 772f24413f72be40867a93c56b6d147b58f1d5f3 | /app/src/main/java/com/chs/appbancoafv/db/MunicipioDAO.java | 93d1a3731dd4c2a471da0f73a7a3082f076ed434 | [] | no_license | H3nr1q/appbancoafv | https://github.com/H3nr1q/appbancoafv | 391b30a1f0cb92eee6ae0287707eb83a04271979 | a4a4f0a962fde39caf9f714445512d900d226660 | refs/heads/master | 2023-06-17T01:23:59.747000 | 2021-07-16T12:05:50 | 2021-07-16T12:05:50 | 373,630,985 | 0 | 0 | null | false | 2021-07-01T14:48:20 | 2021-06-03T20:20:06 | 2021-07-01T02:26:45 | 2021-07-01T14:48:20 | 212 | 0 | 0 | 1 | Java | false | false | package com.chs.appbancoafv.db;
import android.content.ContentValues;
import android.database.Cursor;
import com.chs.appbancoafv.model.Municipio;
import java.util.List;
public class MunicipioDAO extends DAO<Municipio> {
public static MunicipioDAO instance;
public synchronized static MunicipioDAO getInstance(){
if (instance == null){
instance = new MunicipioDAO();
}
return instance;
}
public MunicipioDAO(){
}
@Override
public boolean saveOrEdit(Municipio object) {
return false;
}
@Override
public List<Municipio> searchByName(String name) {
return null;
}
@Override
public boolean deletar(Municipio object) {
return false;
}
@Override
public List<Municipio> listar() {
return null;
}
@Override
public Municipio searchContactById(int id) {
return null;
}
@Override
protected ContentValues bindValues(Municipio municipio) {
return null;
}
@Override
protected Municipio bind(Cursor c) {
return null;
}
}
| UTF-8 | Java | 1,119 | java | MunicipioDAO.java | Java | [] | null | [] | package com.chs.appbancoafv.db;
import android.content.ContentValues;
import android.database.Cursor;
import com.chs.appbancoafv.model.Municipio;
import java.util.List;
public class MunicipioDAO extends DAO<Municipio> {
public static MunicipioDAO instance;
public synchronized static MunicipioDAO getInstance(){
if (instance == null){
instance = new MunicipioDAO();
}
return instance;
}
public MunicipioDAO(){
}
@Override
public boolean saveOrEdit(Municipio object) {
return false;
}
@Override
public List<Municipio> searchByName(String name) {
return null;
}
@Override
public boolean deletar(Municipio object) {
return false;
}
@Override
public List<Municipio> listar() {
return null;
}
@Override
public Municipio searchContactById(int id) {
return null;
}
@Override
protected ContentValues bindValues(Municipio municipio) {
return null;
}
@Override
protected Municipio bind(Cursor c) {
return null;
}
}
| 1,119 | 0.63807 | 0.63807 | 61 | 17.344263 | 17.880188 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.245902 | false | false | 1 |
2584184afde62ff4a954efcc542d416dc0e1ce06 | 25,941,602,497,519 | fa3fe4273eefa7a5bfe0d6d73421dc990fbc23a9 | /src/main/java/com/demo/chan23/singleton/Singleton.java | 3a6db582a34c591397c82eb7b47e0fa5c6079b1f | [] | no_license | doxyang/demo | https://github.com/doxyang/demo | ac930835a01adef94403eadf2de3d25a3b36cf76 | 17eb05cb1c6d8086b4929b75a3ea0e2db09d3902 | refs/heads/master | 2023-04-20T00:52:13.628000 | 2021-04-24T16:47:09 | 2021-04-24T16:47:09 | 356,904,808 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.chan23.singleton;
/**
* 1) 单例模式保证了 系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使
* 用单例模式可以提高系统性能
* 2) 当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用 new
* 3) 单例模式 使用的场景:需要 频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多(即:重量级
* 对象),但又经常用到的对象、 工具类对象、频繁访问数据库或文件的对象(比如 数据源、session 工厂等)
*
* @author panda
*/
public class Singleton {
private String string;
//region 双重校验
/*
其实在jvm里面的执行分为三步:
1.在堆内存开辟内存空间。
2.在堆内存中实例化SingleTon里面的各个参数。
3.把对象指向堆内存空间。
由于jvm存在乱序执行功能,
所以可能在2还没执行时就先执行了3,
如果此时再被切换到线程B上,由于执行了3,INSTANCE 已经非空了,会被直接拿出来用,
这样的话,就会出现异常。这个就是著名的DCL失效问题。
volatile确保INSTANCE每次均在主内存中读取,就可解决DCL失效问题。
这样虽然会牺牲一点效率,但也无伤大雅。
*/
private volatile static Singleton singleton = null;
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
//endregion
private Singleton() {
}
// region [懒汉 线程安全]
private static Singleton singleton2;
public static synchronized Singleton getInstance2() {
if (singleton2 == null) {
singleton2 = new Singleton();
}
return singleton2;
}
// region
}
| UTF-8 | Java | 2,024 | java | Singleton.java | Java | [
{
"context": "对象、频繁访问数据库或文件的对象(比如 数据源、session 工厂等)\n *\n * @author panda\n */\npublic class Singleton {\n\n private String ",
"end": 294,
"score": 0.9924396872520447,
"start": 289,
"tag": "USERNAME",
"value": "panda"
}
] | null | [] | package com.demo.chan23.singleton;
/**
* 1) 单例模式保证了 系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使
* 用单例模式可以提高系统性能
* 2) 当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用 new
* 3) 单例模式 使用的场景:需要 频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多(即:重量级
* 对象),但又经常用到的对象、 工具类对象、频繁访问数据库或文件的对象(比如 数据源、session 工厂等)
*
* @author panda
*/
public class Singleton {
private String string;
//region 双重校验
/*
其实在jvm里面的执行分为三步:
1.在堆内存开辟内存空间。
2.在堆内存中实例化SingleTon里面的各个参数。
3.把对象指向堆内存空间。
由于jvm存在乱序执行功能,
所以可能在2还没执行时就先执行了3,
如果此时再被切换到线程B上,由于执行了3,INSTANCE 已经非空了,会被直接拿出来用,
这样的话,就会出现异常。这个就是著名的DCL失效问题。
volatile确保INSTANCE每次均在主内存中读取,就可解决DCL失效问题。
这样虽然会牺牲一点效率,但也无伤大雅。
*/
private volatile static Singleton singleton = null;
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
//endregion
private Singleton() {
}
// region [懒汉 线程安全]
private static Singleton singleton2;
public static synchronized Singleton getInstance2() {
if (singleton2 == null) {
singleton2 = new Singleton();
}
return singleton2;
}
// region
}
| 2,024 | 0.646875 | 0.634375 | 60 | 20.333334 | 18.034843 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.133333 | false | false | 1 |
2f4edeba8967c27d0a20d1784eb784cf436dede4 | 23,055,384,461,177 | b4652206bbb4bfa3a2c43dc735ec4626da466b8a | /jining/customermanage/customermanage-api/src/main/java/com/xinhai/caiyun/customermanage/api/Resouce.java | 34a6003e9dfb2447e94e40af4ecf5d01eb8f21f3 | [] | no_license | likungithub/jining | https://github.com/likungithub/jining | 7dce8d11ade69fc1bf5c74f9ec385427422af024 | 46c814831471970792c0ad3306b242129fad4f34 | refs/heads/master | 2022-12-25T07:43:53.554000 | 2019-12-14T11:27:26 | 2019-12-14T11:27:26 | 228,010,689 | 1 | 0 | null | false | 2022-12-16T02:44:25 | 2019-12-14T11:21:01 | 2022-04-10T13:10:16 | 2022-12-16T02:44:25 | 37,226 | 1 | 0 | 257 | Java | false | false | package com.xinhai.caiyun.customermanage.api;
public class Resouce {
//验证用户身份获取手机号码的请求url
public static String AUTHCURL="https://sst.qd-n-tax.gov.cn/dzswj/yzSfzhm.do";
//获取登录短信验证码的url
public static String SMGURL="https://sst.qd-n-tax.gov.cn/dzswj/sjtzmSend.do";
//验证身份的链接url
public static String LOGINURL="https://sst.qd-n-tax.gov.cn/dzswj/getNsrList.do";
//登录链接url
public static String DOLOGINURL="https://sst.qd-n-tax.gov.cn/dzswj/login.do";
//实名登录
public static String LOGINMAINURL="https://sst.qd-n-tax.gov.cn/dzswj/initQxJsMenu.do";
}
| UTF-8 | Java | 631 | java | Resouce.java | Java | [] | null | [] | package com.xinhai.caiyun.customermanage.api;
public class Resouce {
//验证用户身份获取手机号码的请求url
public static String AUTHCURL="https://sst.qd-n-tax.gov.cn/dzswj/yzSfzhm.do";
//获取登录短信验证码的url
public static String SMGURL="https://sst.qd-n-tax.gov.cn/dzswj/sjtzmSend.do";
//验证身份的链接url
public static String LOGINURL="https://sst.qd-n-tax.gov.cn/dzswj/getNsrList.do";
//登录链接url
public static String DOLOGINURL="https://sst.qd-n-tax.gov.cn/dzswj/login.do";
//实名登录
public static String LOGINMAINURL="https://sst.qd-n-tax.gov.cn/dzswj/initQxJsMenu.do";
}
| 631 | 0.754991 | 0.754991 | 14 | 38.357143 | 33.068344 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142857 | false | false | 1 |
167d1fefed2c262212064b86494853e5777bc885 | 1,554,778,175,153 | 9e943d0887d68d32f8f5e98193c523a39332a083 | /PlayState.java | 2d2bc6e34a4fa859809e3fa919655a2ea87a3a98 | [] | no_license | Nurassyl-lab/NYCU-JAVA-2021 | https://github.com/Nurassyl-lab/NYCU-JAVA-2021 | 6cbe1f58efa80e5b96ed3846497dca3d64827945 | efe5f21200c50f5c451dcea5dd796c4756c75ef2 | refs/heads/master | 2023-07-07T21:08:39.162000 | 2021-08-14T06:01:56 | 2021-08-14T06:01:56 | 395,908,046 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.*;
import java.util.*;
import java.util.Date;
public class PlayState extends GameState{
private int c = 0;
private Font font;
private Player player;
private TileManager tm;
private Enemy enemy0;
private Enemy enemy1;
private Enemy enemy2;
private Enemy enemy3;
private Enemy enemy4;
private Enemy enemy5;
private Enemy enemy6;
private Enemy enemy7;
private Enemy enemy8;
private Enemy enemy9;
public static Vector2f map;
private Camera cam;
private int LEVEL = 0;
private long lastTime = 0;
private Entity entity;
public PlayState(GameStateManager gsm)
{
super(gsm);
enemy6 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(0 + (GamePanel.width/2) - 32 + 500, 0 + (GamePanel.width/2) - 32 + 500), 80, 0.5f, 1000, 2);
map = new Vector2f();
Vector2f.setWorldVar(map.x, map.y);
cam = new Camera(new AABB(new Vector2f(2420, 2819), 600, 600));
tm = new TileManager("cave2.xml", cam);
font = new Font("Letters3.png", 18, 22);
enemy0 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(1413, 695), 80, 0.5f, 1000, 2);
enemy1 = new Enemy( new Sprite("elfEnemySmall.png"), new Vector2f(2098, 1007), 40, 2.7f, 1000, 1);
enemy2 = new Enemy( new Sprite("elfEnemySmall.png"), new Vector2f(1186, 1007), 40, 2.7f, 1000, 1);
enemy3 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(790, 1343), 80, 1f, 750, 1);
enemy4 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(1492, 1301), 100, 0.3f, 1000, 3);
enemy5 = new Enemy( new Sprite("elfEnemySmall.png"), new Vector2f(2356, 1325), 80, 3f, 1000, 2);
enemy6 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(1646, 1595), 80, 0.5f, 1000, 2);
enemy7 = new Enemy( new Sprite("elfEnemySmall.png"), new Vector2f(2990, 1805), 80, 4f, 1000, 2);
enemy8 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(593, 2026), 80, 0.5f, 1000, 2);
enemy9 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(1592, 2912), 80, 0.5f, 1000, 2);
player = new Player(new Sprite("elfMain.png"), new Vector2f(2811,281), 60, 0f, 1000, 20);
cam.target(player);
}
public void update(){
if(player.PLEV == 5 && c == 0){
tm = new TileManager("cave2_1.xml", cam);
c = 1;
}else if(player.PLEV == 3 && c == 1){
tm = new TileManager("cave2_2.xml", cam);
c = 2;
}else if(player.PLEV == 1 && c == 0){
c = 3;
tm = new TileManager("cave3.xml", cam);
}
Vector2f.setWorldVar(map.x, map.y);
player.update(enemy0);
player.update(enemy1);
player.update(enemy2);
player.update(enemy3);
player.update(enemy4);
player.update(enemy5);
player.update(enemy6);
player.update(enemy7);
player.update(enemy8);
player.update(enemy9);
enemy0.update(player);
enemy1.update(player);
enemy2.update(player);
enemy3.update(player);
enemy4.update(player);
enemy5.update(player);
enemy6.update(player);
enemy7.update(player);
enemy8.update(player);
enemy9.update(player);
cam.update();
}
public void input(MouseHandler mouse, KeyHandler key)
{
player.input(mouse, key);
cam.input(mouse, key);
}
private String test = "public static void main(String args[]){}";
public void render(Graphics2D g)
{
tm.render(g);
Sprite.drawArray(g, font, GamePanel.oldFrameCount + " FPS", new Vector2f(480, 18), 18,18);
Sprite.drawArray(g, font, player.PLEV + " LEVEL", new Vector2f(240, 18), 18,18);
if(player.PLEV == 1){
Sprite.drawArray(g, font, "Help blue stranger release", new Vector2f(0, 40), 10,10);
Sprite.drawArray(g, font, "his friends!", new Vector2f(0, 50), 10,10);
Sprite.drawArray(g, font, "Survive 15 minutes, kill all enemies", new Vector2f(0, 90), 10,10);
}
Sprite.drawArray(g, font, "x: " + player.pos.x, new Vector2f(500, 550), 10,10);
Sprite.drawArray(g, font, "y: " + player.pos.y, new Vector2f(500, 560), 10,10);
player.render(g);
enemy1.render(g);
enemy0.render(g);
enemy2.render(g);
enemy3.render(g);
enemy4.render(g);
enemy5.render(g);
enemy6.render(g);
enemy7.render(g);
enemy8.render(g);
enemy9.render(g);
cam.render(g);
}
}
| UTF-8 | Java | 4,146 | java | PlayState.java | Java | [] | null | [] | import java.awt.*;
import java.util.*;
import java.util.Date;
public class PlayState extends GameState{
private int c = 0;
private Font font;
private Player player;
private TileManager tm;
private Enemy enemy0;
private Enemy enemy1;
private Enemy enemy2;
private Enemy enemy3;
private Enemy enemy4;
private Enemy enemy5;
private Enemy enemy6;
private Enemy enemy7;
private Enemy enemy8;
private Enemy enemy9;
public static Vector2f map;
private Camera cam;
private int LEVEL = 0;
private long lastTime = 0;
private Entity entity;
public PlayState(GameStateManager gsm)
{
super(gsm);
enemy6 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(0 + (GamePanel.width/2) - 32 + 500, 0 + (GamePanel.width/2) - 32 + 500), 80, 0.5f, 1000, 2);
map = new Vector2f();
Vector2f.setWorldVar(map.x, map.y);
cam = new Camera(new AABB(new Vector2f(2420, 2819), 600, 600));
tm = new TileManager("cave2.xml", cam);
font = new Font("Letters3.png", 18, 22);
enemy0 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(1413, 695), 80, 0.5f, 1000, 2);
enemy1 = new Enemy( new Sprite("elfEnemySmall.png"), new Vector2f(2098, 1007), 40, 2.7f, 1000, 1);
enemy2 = new Enemy( new Sprite("elfEnemySmall.png"), new Vector2f(1186, 1007), 40, 2.7f, 1000, 1);
enemy3 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(790, 1343), 80, 1f, 750, 1);
enemy4 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(1492, 1301), 100, 0.3f, 1000, 3);
enemy5 = new Enemy( new Sprite("elfEnemySmall.png"), new Vector2f(2356, 1325), 80, 3f, 1000, 2);
enemy6 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(1646, 1595), 80, 0.5f, 1000, 2);
enemy7 = new Enemy( new Sprite("elfEnemySmall.png"), new Vector2f(2990, 1805), 80, 4f, 1000, 2);
enemy8 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(593, 2026), 80, 0.5f, 1000, 2);
enemy9 = new Enemy( new Sprite("elfEnemyFat.png"), new Vector2f(1592, 2912), 80, 0.5f, 1000, 2);
player = new Player(new Sprite("elfMain.png"), new Vector2f(2811,281), 60, 0f, 1000, 20);
cam.target(player);
}
public void update(){
if(player.PLEV == 5 && c == 0){
tm = new TileManager("cave2_1.xml", cam);
c = 1;
}else if(player.PLEV == 3 && c == 1){
tm = new TileManager("cave2_2.xml", cam);
c = 2;
}else if(player.PLEV == 1 && c == 0){
c = 3;
tm = new TileManager("cave3.xml", cam);
}
Vector2f.setWorldVar(map.x, map.y);
player.update(enemy0);
player.update(enemy1);
player.update(enemy2);
player.update(enemy3);
player.update(enemy4);
player.update(enemy5);
player.update(enemy6);
player.update(enemy7);
player.update(enemy8);
player.update(enemy9);
enemy0.update(player);
enemy1.update(player);
enemy2.update(player);
enemy3.update(player);
enemy4.update(player);
enemy5.update(player);
enemy6.update(player);
enemy7.update(player);
enemy8.update(player);
enemy9.update(player);
cam.update();
}
public void input(MouseHandler mouse, KeyHandler key)
{
player.input(mouse, key);
cam.input(mouse, key);
}
private String test = "public static void main(String args[]){}";
public void render(Graphics2D g)
{
tm.render(g);
Sprite.drawArray(g, font, GamePanel.oldFrameCount + " FPS", new Vector2f(480, 18), 18,18);
Sprite.drawArray(g, font, player.PLEV + " LEVEL", new Vector2f(240, 18), 18,18);
if(player.PLEV == 1){
Sprite.drawArray(g, font, "Help blue stranger release", new Vector2f(0, 40), 10,10);
Sprite.drawArray(g, font, "his friends!", new Vector2f(0, 50), 10,10);
Sprite.drawArray(g, font, "Survive 15 minutes, kill all enemies", new Vector2f(0, 90), 10,10);
}
Sprite.drawArray(g, font, "x: " + player.pos.x, new Vector2f(500, 550), 10,10);
Sprite.drawArray(g, font, "y: " + player.pos.y, new Vector2f(500, 560), 10,10);
player.render(g);
enemy1.render(g);
enemy0.render(g);
enemy2.render(g);
enemy3.render(g);
enemy4.render(g);
enemy5.render(g);
enemy6.render(g);
enemy7.render(g);
enemy8.render(g);
enemy9.render(g);
cam.render(g);
}
}
| 4,146 | 0.657019 | 0.565847 | 126 | 31.904762 | 30.681526 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.301587 | false | false | 1 |
13abe4757b57372f9b00105dbf24dfbeabd49e0b | 3,143,916,084,388 | d9dcd287acb2c6cc15d06991d67385482ce20e3c | /WebApi/api/src/test/java/pt/wastemanagement/api/requester_implementations/CollectRequesterImplementation.java | 7fcdd06aa3d17ef6d4839610ada532460891f4fe | [] | no_license | tiagobluiz/intelligent_garbage_collection | https://github.com/tiagobluiz/intelligent_garbage_collection | ee20a534244f8eca246db24370a57b99f000f95c | 3920efa9399b5d8a6a60e82ee9f44b10ea996b8b | refs/heads/master | 2021-06-30T03:10:12.524000 | 2019-09-10T19:08:46 | 2019-09-10T19:08:46 | 207,633,587 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pt.wastemanagement.api.requester_implementations;
import pt.wastemanagement.api.exceptions.SQLInvalidDependencyException;
import pt.wastemanagement.api.exceptions.SQLNonExistentEntryException;
import pt.wastemanagement.api.exceptions.SQLWrongDateException;
import pt.wastemanagement.api.model.Collect;
import pt.wastemanagement.api.model.utils.PaginatedList;
import pt.wastemanagement.api.requesters.CollectRequester;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class CollectRequesterImplementation implements CollectRequester {
public final static int
NORMAL_STATE = 0, // Normal usage of the requester
WRONG_PARAMETERS_STATE = 1, // Wrong parameters
BAD_REQUEST_STATE = 2; // Unpredictable usage of the requester
public final int implementation_state;
public CollectRequesterImplementation(int implementation_state) {
this.implementation_state = implementation_state;
}
@Override
public void createCollect(int containerId, LocalDateTime collectDate) throws Exception {
if (implementation_state == WRONG_PARAMETERS_STATE) {
throw new SQLWrongDateException(); // //SQL couldn't interpret the date format
} else if (implementation_state == BAD_REQUEST_STATE) {
throw new SQLInvalidDependencyException(); //E.g: Container Id is invalid
}
return;
}
@Override
public void collectCollectZoneContainers(int collectZoneId, LocalDateTime collectDate, String containerType) throws Exception {
if (implementation_state == WRONG_PARAMETERS_STATE || implementation_state == BAD_REQUEST_STATE) {
throw new SQLInvalidDependencyException(); // Collect Zone didn't exists
}
return;
}
@Override
public void updateCollect(int containerId, LocalDateTime actualCollectDate, LocalDateTime newCollectDate) throws Exception {
if (implementation_state == WRONG_PARAMETERS_STATE) {
throw new SQLWrongDateException(); //SQL couldn't interpret the date format
} else if (implementation_state == BAD_REQUEST_STATE) {
throw new SQLNonExistentEntryException(); //Container Id is invalid
}
return;
}
public static final int TOTAL_COLLECTS = 1;
public static final String
DATE_1 = "2018-05-05T20:56:57",
CONFIRMED = "T";
@Override
public PaginatedList<Collect> getContainerCollects(int pageNumber, int rowsPerPage, int containerId) throws Exception {
List<Collect> collects = new ArrayList<>(TOTAL_COLLECTS);
collects.add(new Collect(containerId, LocalDateTime.parse(DATE_1), CONFIRMED));
return new PaginatedList<>(TOTAL_COLLECTS, collects);
}
@Override
public Collect getContainerCollect(int containerId, LocalDateTime collectDate) throws Exception {
return new Collect(containerId, collectDate, CONFIRMED);
}
}
| UTF-8 | Java | 3,009 | java | CollectRequesterImplementation.java | Java | [] | null | [] | package pt.wastemanagement.api.requester_implementations;
import pt.wastemanagement.api.exceptions.SQLInvalidDependencyException;
import pt.wastemanagement.api.exceptions.SQLNonExistentEntryException;
import pt.wastemanagement.api.exceptions.SQLWrongDateException;
import pt.wastemanagement.api.model.Collect;
import pt.wastemanagement.api.model.utils.PaginatedList;
import pt.wastemanagement.api.requesters.CollectRequester;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class CollectRequesterImplementation implements CollectRequester {
public final static int
NORMAL_STATE = 0, // Normal usage of the requester
WRONG_PARAMETERS_STATE = 1, // Wrong parameters
BAD_REQUEST_STATE = 2; // Unpredictable usage of the requester
public final int implementation_state;
public CollectRequesterImplementation(int implementation_state) {
this.implementation_state = implementation_state;
}
@Override
public void createCollect(int containerId, LocalDateTime collectDate) throws Exception {
if (implementation_state == WRONG_PARAMETERS_STATE) {
throw new SQLWrongDateException(); // //SQL couldn't interpret the date format
} else if (implementation_state == BAD_REQUEST_STATE) {
throw new SQLInvalidDependencyException(); //E.g: Container Id is invalid
}
return;
}
@Override
public void collectCollectZoneContainers(int collectZoneId, LocalDateTime collectDate, String containerType) throws Exception {
if (implementation_state == WRONG_PARAMETERS_STATE || implementation_state == BAD_REQUEST_STATE) {
throw new SQLInvalidDependencyException(); // Collect Zone didn't exists
}
return;
}
@Override
public void updateCollect(int containerId, LocalDateTime actualCollectDate, LocalDateTime newCollectDate) throws Exception {
if (implementation_state == WRONG_PARAMETERS_STATE) {
throw new SQLWrongDateException(); //SQL couldn't interpret the date format
} else if (implementation_state == BAD_REQUEST_STATE) {
throw new SQLNonExistentEntryException(); //Container Id is invalid
}
return;
}
public static final int TOTAL_COLLECTS = 1;
public static final String
DATE_1 = "2018-05-05T20:56:57",
CONFIRMED = "T";
@Override
public PaginatedList<Collect> getContainerCollects(int pageNumber, int rowsPerPage, int containerId) throws Exception {
List<Collect> collects = new ArrayList<>(TOTAL_COLLECTS);
collects.add(new Collect(containerId, LocalDateTime.parse(DATE_1), CONFIRMED));
return new PaginatedList<>(TOTAL_COLLECTS, collects);
}
@Override
public Collect getContainerCollect(int containerId, LocalDateTime collectDate) throws Exception {
return new Collect(containerId, collectDate, CONFIRMED);
}
}
| 3,009 | 0.712861 | 0.706215 | 72 | 40.791668 | 36.903378 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 1 |
12b5d6fe183f370bbfad691c03fc185bbd5cc9ec | 29,996,051,602,050 | 84ac55eddc0af690732d28fdab6d7ba5cdbe9d88 | /src/main/java/com/altugcagri/smep/controller/dto/response/UserProfile.java | 64386c7547f3f728bcfe7b2ece3f505f2adbbe04 | [
"Apache-2.0"
] | permissive | altugcagri/boun-swe-573 | https://github.com/altugcagri/boun-swe-573 | db2da5b9a43da5976a548979d44c425327d41f26 | 94b062fffc076a72ea8a7709398eb2d0db9fa881 | refs/heads/dev | 2021-06-23T15:28:56.994000 | 2019-05-27T19:34:12 | 2019-05-27T19:34:12 | 170,499,885 | 1 | 4 | Apache-2.0 | false | 2021-01-05T08:07:21 | 2019-02-13T11:54:18 | 2019-09-25T13:16:18 | 2021-01-05T08:07:20 | 9,285 | 1 | 2 | 29 | Java | false | false | package com.altugcagri.smep.controller.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.Instant;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserProfile {
private Long id;
private String username;
private String name;
private Instant joinedAt;
private Long topicCount;
}
| UTF-8 | Java | 445 | java | UserProfile.java | Java | [] | null | [] | package com.altugcagri.smep.controller.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.Instant;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserProfile {
private Long id;
private String username;
private String name;
private Instant joinedAt;
private Long topicCount;
}
| 445 | 0.786517 | 0.786517 | 24 | 17.541666 | 13.434964 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
58259ebebdaba70b2a4c023c81fdcc95b9f77f09 | 14,963,666,075,824 | 1867f7a9edc6c6ecad6be3f1298545fcd8e8a162 | /src/main/java/com/iancui/exeception/AppointException.java | f088aa95919496f1ce7e864aa8fbe5241ea07cc2 | [] | no_license | iancui/bookManagement | https://github.com/iancui/bookManagement | cffce82f484cc6142521b6931bc5b126817594fe | a797d6ba453cdf252dfe2bab10f405fdcc299834 | refs/heads/master | 2021-06-21T19:27:59.125000 | 2017-08-16T07:02:21 | 2017-08-16T07:02:21 | 100,451,643 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.iancui.exeception;
/**
* 预约业务异常
* @author S.Murata
* @version $Id$
* @since JDK5.0
*/
public class AppointException extends RuntimeException {
public AppointException(String message) {
super(message);
}
public AppointException(String message, Throwable cause) {
super(message, cause);
}
}
| UTF-8 | Java | 367 | java | AppointException.java | Java | [
{
"context": " com.iancui.exeception;\n\n/**\n * 预约业务异常\n * @author S.Murata\n * @version $Id$\n * @since JDK5.0\n */\npublic clas",
"end": 78,
"score": 0.9998846054077148,
"start": 70,
"tag": "NAME",
"value": "S.Murata"
}
] | null | [] | /**
*
*/
package com.iancui.exeception;
/**
* 预约业务异常
* @author S.Murata
* @version $Id$
* @since JDK5.0
*/
public class AppointException extends RuntimeException {
public AppointException(String message) {
super(message);
}
public AppointException(String message, Throwable cause) {
super(message, cause);
}
}
| 367 | 0.639437 | 0.633803 | 22 | 15.136364 | 18.293802 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false | 1 |
09e1c91a8aeca40dd71a32868461f44f84ab9022 | 26,817,775,862,786 | 4a14e81379ed7cb2990c20fd61d4b698d58e4ec5 | /src/kozossegi/view/elements/KozossegiSuggestBox.java | fa9098583e02dc93910fa4d3ce14b913ebef7b88 | [] | no_license | rerobika/AdatB_Kozossegi | https://github.com/rerobika/AdatB_Kozossegi | 61826adcdf16751a0832cc76318f9fedf72498b5 | 83228c5382557402b8bd69866333707c42c68d7d | refs/heads/master | 2020-05-20T08:24:02.708000 | 2017-05-06T19:58:34 | 2017-05-06T19:58:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kozossegi.view.elements;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import kozossegi.Labels;
import kozossegi.bean.KozossegiProfileMiniatureBean;
import kozossegi.view.KozossegiMainFrame;
import kozossegi.view.elements.maincontent.KozossegiClubProfile;
import kozossegi.view.elements.maincontent.KozossegiUserProfile;
public class KozossegiSuggestBox extends JPanel {
private static final long serialVersionUID = -7611266213286581278L;
private JPanel suggestClubPanel;
private JPanel suggestFriendPanel;
private JLabel suggestClubLabel;
private JLabel suggestFriendLabel;
private JScrollPane suggestClubScroll;
private JScrollPane suggestFriendScroll;
public KozossegiSuggestBox() {
KozossegiMainFrame mainFrame = KozossegiMainFrame.getInstance();
suggestClubPanel = new JPanel();
suggestFriendPanel = new JPanel();
suggestClubLabel = new JLabel(Labels.CLUB_SUGGESTION);
suggestFriendLabel = new JLabel(Labels.FRINED_SUGGESTION);
suggestClubScroll = new JScrollPane(suggestClubPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
suggestFriendScroll = new JScrollPane(suggestFriendPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
suggestClubPanel.setLayout(new GridLayout(0, 1));
for(KozossegiProfileMiniatureBean c : mainFrame.getSuggestedClubList()){
KozossegiProfileMiniature miniature = new KozossegiProfileMiniature(c);
miniature.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
mainFrame.setMainContent(new KozossegiClubProfile(mainFrame.getController().getClub(c.getId())));
}
});
suggestClubPanel.add(miniature);
}
suggestFriendPanel.setLayout(new GridLayout(0, 1));
for(KozossegiProfileMiniatureBean c : mainFrame.getSuggestedFriendList()){
KozossegiProfileMiniature miniature =new KozossegiProfileMiniature(c);
miniature.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
mainFrame.setMainContent(new KozossegiUserProfile(mainFrame.getController().getProfile(c.getId())));
}
});
suggestFriendPanel.add(miniature);
}
setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
setBorder(BorderFactory.createLineBorder(Color.black));
add(suggestClubLabel);
add(suggestClubScroll);
add(suggestFriendLabel);
add(suggestFriendScroll);
}
}
| UTF-8 | Java | 2,782 | java | KozossegiSuggestBox.java | Java | [] | null | [] | package kozossegi.view.elements;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import kozossegi.Labels;
import kozossegi.bean.KozossegiProfileMiniatureBean;
import kozossegi.view.KozossegiMainFrame;
import kozossegi.view.elements.maincontent.KozossegiClubProfile;
import kozossegi.view.elements.maincontent.KozossegiUserProfile;
public class KozossegiSuggestBox extends JPanel {
private static final long serialVersionUID = -7611266213286581278L;
private JPanel suggestClubPanel;
private JPanel suggestFriendPanel;
private JLabel suggestClubLabel;
private JLabel suggestFriendLabel;
private JScrollPane suggestClubScroll;
private JScrollPane suggestFriendScroll;
public KozossegiSuggestBox() {
KozossegiMainFrame mainFrame = KozossegiMainFrame.getInstance();
suggestClubPanel = new JPanel();
suggestFriendPanel = new JPanel();
suggestClubLabel = new JLabel(Labels.CLUB_SUGGESTION);
suggestFriendLabel = new JLabel(Labels.FRINED_SUGGESTION);
suggestClubScroll = new JScrollPane(suggestClubPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
suggestFriendScroll = new JScrollPane(suggestFriendPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
suggestClubPanel.setLayout(new GridLayout(0, 1));
for(KozossegiProfileMiniatureBean c : mainFrame.getSuggestedClubList()){
KozossegiProfileMiniature miniature = new KozossegiProfileMiniature(c);
miniature.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
mainFrame.setMainContent(new KozossegiClubProfile(mainFrame.getController().getClub(c.getId())));
}
});
suggestClubPanel.add(miniature);
}
suggestFriendPanel.setLayout(new GridLayout(0, 1));
for(KozossegiProfileMiniatureBean c : mainFrame.getSuggestedFriendList()){
KozossegiProfileMiniature miniature =new KozossegiProfileMiniature(c);
miniature.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
mainFrame.setMainContent(new KozossegiUserProfile(mainFrame.getController().getProfile(c.getId())));
}
});
suggestFriendPanel.add(miniature);
}
setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
setBorder(BorderFactory.createLineBorder(Color.black));
add(suggestClubLabel);
add(suggestClubScroll);
add(suggestFriendLabel);
add(suggestFriendScroll);
}
}
| 2,782 | 0.784328 | 0.77606 | 72 | 36.638889 | 32.575256 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.291667 | false | false | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.