blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13b26cb9bdf7875b3cf4a81693c38f1fa52846e8 | c6992ce8db7e5aab6fd959c0c448659ab91b16ce | /sdk/resourcegraph/azure-resourcemanager-resourcegraph/src/main/java/com/azure/resourcemanager/resourcegraph/models/ResourcePropertyChange.java | 1f56ba56ae716a02c83ff1683f23ebb712314a0c | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"CC0-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later"
] | permissive | g2vinay/azure-sdk-for-java | ae6d94d583cc2983a5088ec8f6146744ee82cb55 | b88918a2ba0c3b3e88a36c985e6f83fc2bae2af2 | refs/heads/master | 2023-09-01T17:46:08.256214 | 2021-09-23T22:20:20 | 2021-09-23T22:20:20 | 161,234,198 | 3 | 1 | MIT | 2020-01-16T20:22:43 | 2018-12-10T20:44:41 | Java | UTF-8 | Java | false | false | 5,139 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.resourcegraph.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The resource property change. */
@Fluent
public final class ResourcePropertyChange {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ResourcePropertyChange.class);
/*
* The property name
*/
@JsonProperty(value = "propertyName", required = true)
private String propertyName;
/*
* The property value in before snapshot
*/
@JsonProperty(value = "beforeValue")
private String beforeValue;
/*
* The property value in after snapshot
*/
@JsonProperty(value = "afterValue")
private String afterValue;
/*
* The change category.
*/
@JsonProperty(value = "changeCategory", required = true)
private ChangeCategory changeCategory;
/*
* The property change Type
*/
@JsonProperty(value = "propertyChangeType", required = true)
private PropertyChangeType propertyChangeType;
/**
* Get the propertyName property: The property name.
*
* @return the propertyName value.
*/
public String propertyName() {
return this.propertyName;
}
/**
* Set the propertyName property: The property name.
*
* @param propertyName the propertyName value to set.
* @return the ResourcePropertyChange object itself.
*/
public ResourcePropertyChange withPropertyName(String propertyName) {
this.propertyName = propertyName;
return this;
}
/**
* Get the beforeValue property: The property value in before snapshot.
*
* @return the beforeValue value.
*/
public String beforeValue() {
return this.beforeValue;
}
/**
* Set the beforeValue property: The property value in before snapshot.
*
* @param beforeValue the beforeValue value to set.
* @return the ResourcePropertyChange object itself.
*/
public ResourcePropertyChange withBeforeValue(String beforeValue) {
this.beforeValue = beforeValue;
return this;
}
/**
* Get the afterValue property: The property value in after snapshot.
*
* @return the afterValue value.
*/
public String afterValue() {
return this.afterValue;
}
/**
* Set the afterValue property: The property value in after snapshot.
*
* @param afterValue the afterValue value to set.
* @return the ResourcePropertyChange object itself.
*/
public ResourcePropertyChange withAfterValue(String afterValue) {
this.afterValue = afterValue;
return this;
}
/**
* Get the changeCategory property: The change category.
*
* @return the changeCategory value.
*/
public ChangeCategory changeCategory() {
return this.changeCategory;
}
/**
* Set the changeCategory property: The change category.
*
* @param changeCategory the changeCategory value to set.
* @return the ResourcePropertyChange object itself.
*/
public ResourcePropertyChange withChangeCategory(ChangeCategory changeCategory) {
this.changeCategory = changeCategory;
return this;
}
/**
* Get the propertyChangeType property: The property change Type.
*
* @return the propertyChangeType value.
*/
public PropertyChangeType propertyChangeType() {
return this.propertyChangeType;
}
/**
* Set the propertyChangeType property: The property change Type.
*
* @param propertyChangeType the propertyChangeType value to set.
* @return the ResourcePropertyChange object itself.
*/
public ResourcePropertyChange withPropertyChangeType(PropertyChangeType propertyChangeType) {
this.propertyChangeType = propertyChangeType;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (propertyName() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property propertyName in model ResourcePropertyChange"));
}
if (changeCategory() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property changeCategory in model ResourcePropertyChange"));
}
if (propertyChangeType() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property propertyChangeType in model ResourcePropertyChange"));
}
}
}
| [
"[email protected]"
] | |
c8e4e7689a07733976543ae5a5fa7df812d9fc0b | bd3a050d1bdc3fee647c843942955cefe2d38114 | /gulimall-product/src/main/java/com/study/gulimall/product/service/impl/CategoryBrandRelationServiceImpl.java | d7abe85aeab8a65f85020da1037db7830e3cb4d9 | [
"Apache-2.0"
] | permissive | czytc/gulimall | 0fc241f4bb7088944e39fec2ae2f86b1df5161ff | cfd89d7af4c531f662663ea998c5cfa6fa4ca359 | refs/heads/main | 2023-05-28T22:06:57.975661 | 2021-06-03T01:18:17 | 2021-06-03T01:18:17 | 372,669,553 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,130 | java | package com.study.gulimall.product.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.common.utils.PageUtils;
import com.study.common.utils.Query;
import com.study.gulimall.product.dao.CategoryBrandRelationDao;
import com.study.gulimall.product.entity.CategoryBrandRelationEntity;
import com.study.gulimall.product.service.CategoryBrandRelationService;
@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<CategoryBrandRelationEntity> page = this.page(
new Query<CategoryBrandRelationEntity>().getPage(params),
new QueryWrapper<CategoryBrandRelationEntity>()
);
return new PageUtils(page);
}
} | [
"[email protected]"
] | |
936813e49b60eda02638170b84aec56057d8321f | 1ca86d5d065372093c5f2eae3b1a146dc0ba4725 | /spring-boot-rest/src/test/java/com/surya/controllers/ExamplePostControllerResponseIntegrationTest.java | 0804e5d2f53745f773f8a080564e66494f9b4d01 | [] | no_license | Suryakanta97/DemoExample | 1e05d7f13a9bc30f581a69ce811fc4c6c97f2a6e | 5c6b831948e612bdc2d9d578a581df964ef89bfb | refs/heads/main | 2023-08-10T17:30:32.397265 | 2021-09-22T16:18:42 | 2021-09-22T16:18:42 | 391,087,435 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,266 | java | package com.surya.controllers;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.surya.SpringBootRestApplication;
import com.surya.requestresponsebody.ExamplePostController;
import com.surya.requestresponsebody.LoginForm;
import com.surya.services.ExampleService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootRestApplication.class)
public class ExamplePostControllerResponseIntegrationTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;
@InjectMocks private ExamplePostController exampleController;
private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}";
private LoginForm lf = new LoginForm();
@Before
public void preTest() {
MockitoAnnotations.openMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(exampleController)
.build();
lf.setPassword("password");
lf.setUsername("username");
}
@Test
public void requestBodyTest() {
try {
when(exampleService.fakeAuthenticate(lf)).thenReturn(true);
mockMvc
.perform(post("/post/response")
.content(jsonBody)
.contentType("application/json"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().json("{\"text\":\"Thanks For Posting!!!\"}"));
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
} | [
"[email protected]"
] | |
043588a010560e9ad85235bbc67443acffecb2bc | d7e6708c342c09852d99dd79814aacebcc3953da | /android/ToPlay_Next/app/src/main/java/com/oneme/toplay/base/DownloadNodes.java | 3b406f81a912c1d5c9bd45a877b1c1c25d3387fc | [] | no_license | ozzie00/Playround | f2182bfb96fc9bda0eb2694e2c906a21cd5e88e8 | f18ba557a1dbb13f19f5a0ac529c6c0b05a46253 | refs/heads/master | 2021-03-16T06:19:51.259534 | 2018-02-03T10:32:55 | 2018-02-03T10:32:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,593 | java | package com.oneme.toplay.base;
import android.content.Context;
import android.os.AsyncTask;
//import android.util.Log;
import com.oneme.toplay.Application;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
public class DownloadNodes extends AsyncTask<Void, Void, Void> {
private static class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
}
final String[] nodeDetails = new String[7];
final String TAG = "DHTNODEDETAILS";
Context mcontext;
public DownloadNodes(Context context) {
this.mcontext = context;
}
@Override
protected Void doInBackground(Void... params) {
try {
/* Get nodes from json-formatted data */
JSONObject json = JsonReader.readJsonFromUrl("https://dist-build.tox.im/Nodefile.json");//"https://s3.amazonaws.com/www.onemee.net/Nodefile.json");//"https://dist-build.tox.im/Nodefile.json");//"https://s3.amazonaws.com/www.onemee.net/Nodefile.json");
if (Application.APPDEBUG) {
//Log.d(TAG, json.toString());
}
JSONArray serverArray = json.getJSONArray("servers");
for(int i = 0; i < serverArray.length(); i++) {
JSONObject jsonObject = serverArray.getJSONObject(i);
DHTNodes.owner.add(jsonObject.getString("owner"));
DHTNodes.ipv6.add(jsonObject.getString("ipv6"));
DHTNodes.key.add(jsonObject.getString("pubkey"));
DHTNodes.ipv4.add(jsonObject.getString("ipv4"));
DHTNodes.port.add(String.valueOf(jsonObject.getInt("port")));
}
if (Application.APPDEBUG) {
//Log.d(TAG, "Nodes fetched from online");
}
} catch (Exception exp) {
if (Application.APPDEBUG) {
// Log.d(TAG, "Failed to connect to Tox CDN for nodes");
}
DHTNodes.ipv4.add("192.254.75.98");
com.oneme.toplay.base.DHTNodes.ipv6.add("2607:5600:284::2");
DHTNodes.owner.add("stqism");
DHTNodes.port.add("33445");
com.oneme.toplay.base.DHTNodes.key.add("951C88B7E75C867418ACDB5D273821372BB5BD652740BCDF623A4FA293E75D2F");
com.oneme.toplay.base.DHTNodes.ipv4.add("144.76.60.215");
com.oneme.toplay.base.DHTNodes.ipv6.add("2a01:4f8:191:64d6::1");
DHTNodes.owner.add("sonofra");
DHTNodes.port.add("33445");
DHTNodes.key.add("04119E835DF3E78BACF0F84235B300546AF8B936F035185E2A8E9E0A67C8924F");
DHTNodes.ipv4.add("37.187.46.132");
DHTNodes.ipv6.add("2001:41d0:0052:0300::0507");
DHTNodes.owner.add("mouseym");
com.oneme.toplay.base.DHTNodes.port.add("33445");
DHTNodes.key.add("A9D98212B3F972BD11DA52BEB0658C326FCCC1BFD49F347F9C2D3D8B61E1B927");
DHTNodes.ipv4.add("37.59.102.176");
DHTNodes.ipv6.add("2001:41d0:51:1:0:0:0:cc");
com.oneme.toplay.base.DHTNodes.owner.add("astonex");
com.oneme.toplay.base.DHTNodes.port.add("33445");
com.oneme.toplay.base.DHTNodes.key.add("B98A2CEAA6C6A2FADC2C3632D284318B60FE5375CCB41EFA081AB67F500C1B0B");
DHTNodes.ipv4.add("54.199.139.199");
DHTNodes.ipv6.add("");
DHTNodes.owner.add("aitjcize");
DHTNodes.port.add("33445");
DHTNodes.key.add("7F9C31FE850E97CEFD4C4591DF93FC757C7C12549DDD55F8EEAECC34FE76C029");
}
if (Application.APPDEBUG) {
//Log.d(TAG, "DhtNode size: " + DHTNodes.ipv4.size());
}
return null;
}
}
| [
"[email protected]"
] | |
8ea2b8ccde87c66b765fe3e7939d1beb54eeb742 | 86941b3ed58e2619f414cf6c71df244d4f37a603 | /_yisheng/yisheng-core/javafans-framework/src/main/java/org/javafans/dto/page/Page.java | f0b613c4d4b7636925e40d5459796bf873795ec9 | [] | no_license | hl343169728/huanglei | 79c00bf8d4b4fe96e5fc0f9f444dbc7083dd2004 | c81c594bc6a367f09ee564e0788b72f68bad176a | refs/heads/master | 2022-12-27T09:46:05.833797 | 2020-11-13T07:14:55 | 2020-11-13T07:14:55 | 33,716,900 | 1 | 0 | null | 2022-12-16T00:41:57 | 2015-04-10T08:16:17 | JavaScript | UTF-8 | Java | false | false | 5,814 | java | /**
* Copyright (c) 2005-2010 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* $Id: Page.java 1183 2010-08-28 08:05:49Z calvinxiu $
*/
package org.javafans.dto.page;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.google.common.collect.Lists;
/**
* 与具体ORM实现无关的分页参数及查询结果封装.
*
* 注意所有序号从1开始.
*
* @param <T> Page中记录的类型.
*
* @author calvin
*/
public class Page<T> {
//-- 公共变量 --//
public static final String ASC = "asc";
public static final String DESC = "desc";
//-- 分页参数 --//
protected int pageNo = 1;
protected int pageSize = -1;
protected String orderBy = null;
protected String order = null;
protected boolean autoCount = true;
//-- 返回结果 --//
protected List<T> result = Lists.newArrayList();
protected long totalCount = -1;
//-- 构造函数 --//
public Page() {
}
public Page(int pageSize) {
this.pageSize = pageSize;
}
public Page(int pageNo,int pageSize,long totalCount) {
this.totalCount=totalCount;
this.pageSize = pageSize;
this.pageNo=pageNo;
}
public Page(List<T> result ,int pageNo,int pageSize,long totalCount) {
this.totalCount=totalCount;
this.pageSize = pageSize;
this.pageNo=pageNo;
this.result=result;
}
//-- 分页参数访问函数 --//
/**
* 获得当前页的页号,序号从1开始,默认为1.
*/
public int getPageNo() {
return pageNo;
}
/**
* 设置当前页的页号,序号从1开始,低于1时自动调整为1.
*/
public void setPageNo(final int pageNo) {
this.pageNo = pageNo;
if (pageNo < 1) {
this.pageNo = 1;
}
}
/**
* 返回Page对象自身的setPageNo函数,可用于连续设置。
*/
public Page<T> pageNo(final int thePageNo) {
setPageNo(thePageNo);
return this;
}
/**
* 获得每页的记录数量, 默认为-1.
*/
public int getPageSize() {
return pageSize;
}
/**
* 设置每页的记录数量.
*/
public void setPageSize(final int pageSize) {
this.pageSize = pageSize;
}
/**
* 返回Page对象自身的setPageSize函数,可用于连续设置。
*/
public Page<T> pageSize(final int thePageSize) {
setPageSize(thePageSize);
return this;
}
/**
* 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从1开始.
*/
public Long getFirst() {
return Long.valueOf(((pageNo - 1) * pageSize) + 1);
}
/**
* 获得排序字段,无默认值. 多个排序字段时用','分隔.
*/
public String getOrderBy() {
return orderBy;
}
/**
* 设置排序字段,多个排序字段时用','分隔.
*/
public void setOrderBy(final String orderBy) {
this.orderBy = orderBy;
}
/**
* 返回Page对象自身的setOrderBy函数,可用于连续设置。
*/
public Page<T> orderBy(final String theOrderBy) {
setOrderBy(theOrderBy);
return this;
}
/**
* 获得排序方向, 无默认值.
*/
public String getOrder() {
return order;
}
/**
* 设置排序方式向.
*
* @param order 可选值为desc或asc,多个排序字段时用','分隔.
*/
public void setOrder(final String order) {
String lowcaseOrder = StringUtils.lowerCase(order);
//检查order字符串的合法值
String[] orders = StringUtils.split(lowcaseOrder, ',');
for (String orderStr : orders) {
if (!StringUtils.equals(DESC, orderStr) && !StringUtils.equals(ASC, orderStr)) {
throw new IllegalArgumentException("排序方向" + orderStr + "不是合法值");
}
}
this.order = lowcaseOrder;
}
/**
* 返回Page对象自身的setOrder函数,可用于连续设置。
*/
public Page<T> order(final String theOrder) {
setOrder(theOrder);
return this;
}
/**
* 是否已设置排序字段,无默认值.
*/
public boolean isOrderBySetted() {
return (StringUtils.isNotBlank(orderBy) && StringUtils.isNotBlank(order));
}
/**
* 获得查询对象时是否先自动执行count查询获取总记录数, 默认为false.
*/
public boolean isAutoCount() {
return autoCount;
}
/**
* 设置查询对象时是否自动先执行count查询获取总记录数.
*/
public void setAutoCount(final boolean autoCount) {
this.autoCount = autoCount;
}
/**
* 返回Page对象自身的setAutoCount函数,可用于连续设置。
*/
public Page<T> autoCount(final boolean theAutoCount) {
setAutoCount(theAutoCount);
return this;
}
//-- 访问查询结果函数 --//
/**
* 获得页内的记录列表.
*/
public List<T> getResult() {
return result;
}
/**
* 设置页内的记录列表.
*/
public void setResult(final List<T> result) {
this.result = result;
}
/**
* 获得总记录数, 默认值为-1.
*/
public long getTotalCount() {
return totalCount;
}
/**
* 设置总记录数.
*/
public void setTotalCount(final long totalCount) {
this.totalCount = totalCount;
}
/**
* 根据pageSize与totalCount计算总页数, 默认值为-1.
*/
public long getTotalPages() {
if (totalCount < 0) {
return -1;
}
long count = totalCount / pageSize;
if (totalCount % pageSize > 0) {
count++;
}
return count;
}
/**
* 是否还有下一页.
*/
public boolean isHasNext() {
return (pageNo + 1 <= getTotalPages());
}
/**
* 取得下页的页号, 序号从1开始.
* 当前页为尾页时仍返回尾页序号.
*/
public int getNextPage() {
if (isHasNext()) {
return pageNo + 1;
} else {
return pageNo;
}
}
/**
* 是否还有上一页.
*/
public boolean isHasPre() {
return (pageNo - 1 >= 1);
}
/**
* 取得上页的页号, 序号从1开始.
* 当前页为首页时返回首页序号.
*/
public int getPrePage() {
if (isHasPre()) {
return pageNo - 1;
} else {
return pageNo;
}
}
}
| [
"[email protected]"
] | |
85fb97d6b05c895858de02bcadbc2544dab26664 | c4c34173dd5a15f23c41836f1388feb276e36f74 | /app/src/main/java/com/zhang/javabase/day20/test/Test1.java | 5a8469014c877021027208998c90eb56e405e0de | [] | no_license | keeponZhang/JavaBase | dded4a6c9191b35679df2871d231b0c5618d2380 | c4fe1eeadbc35052c4e36b7bbf983d8eab23b23f | refs/heads/master | 2020-09-15T11:32:06.246228 | 2019-11-24T12:14:21 | 2019-11-24T12:14:21 | 223,432,550 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | package com.zhang.javabase.day20.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
/**
* @param args
* @throws IOException
* 将写出的字节异或上一个数,这个数就是密钥,解密的时候再次异或就可以了
*/
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("copy.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy2.jpg"));
int b;
while((b = bis.read()) != -1) {
bos.write(b ^ 123);
}
bis.close();
bos.close();
}
}
| [
"[email protected]"
] | |
5e3f6684794833d5f5eab3ba94e8e3bb5623eb65 | efcf7f50ba4af1314602d3a41f5b80a084b9efa9 | /part-4/exercise-6/SpringCurrencyConversion/src/main/java/com/springmvc/currencyconversion/controller/CurrencyConversionController.java | 333f22f6b798df80359d6dfc3706372925d46565 | [] | no_license | SamuliRukkila/Java-EE-Exercises | 1ed592a49ed7abf80d8ea4d2a6fc3874a49a5b60 | 659f097b50f7647ade5687cfe4dc2c97ee24fbc7 | refs/heads/master | 2022-07-02T14:25:02.856955 | 2019-08-14T16:11:14 | 2019-08-14T16:11:14 | 187,354,749 | 0 | 0 | null | 2022-06-21T01:27:52 | 2019-05-18T12:23:26 | Java | UTF-8 | Java | false | false | 3,587 | java | package com.springmvc.currencyconversion.controller;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.springmvc.currencyconversion.model.CurrencyConversionBean;
import com.springmvc.currencyconversion.proxy.CurrencyExchangeServiceProxy;
/**
* Normaali REST-kontrolleri, joka toteuttaa muutaman
* GET-funktion.
*/
@RestController
public class CurrencyConversionController {
// Automaattisesti injektoi proxy-palvelu
@Autowired
private CurrencyExchangeServiceProxy proxy;
// Haluttujen tietojen loggaus konsoliin
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Normaali tapa, jolla voidaan olla yhteydessä Forex-palveluun. Kun tätä funktiota
* kutsutaan, se kutsuu Forex-palvelun GET-kyselyä, mikä tuottaa valuutanvaihtoarvon.
* Kun arvo sekä portti palautuu. Se luo vastauksen käyttämällä CurrencyConversinBean
* -beania, jonka se palauttaa.
*
* @param from - Mistä valuutasta käännetään
* @param to - Mihin valuuttaan käännetän
* @param quantity - Rahamäärä, mikä käännetään
* @return - Vastaus mikä kertoo kaikki metatiedot kyselystä, sekä valuutanvaihtoarvon sekä määrän
*/
@GetMapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}")
public CurrencyConversionBean convertCurrency(@PathVariable String from, @PathVariable String to,
@PathVariable BigDecimal quantity) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("from", from);
uriVariables.put("to", to);
ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().getForEntity(
"http://localhost:8000/currency-exchange/from/{from}/to/{to}", CurrencyConversionBean.class,
uriVariables);
CurrencyConversionBean response = responseEntity.getBody();
return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity,
quantity.multiply(response.getConversionMultiple()), response.getPort());
}
/**
* Feignin tapa tehdä REST-kysely ylemmän sijaan. Se kutsuu repositoryä, joka tekee Feignin avulla REST-kyselyn
* Forex-mikropalveluun. Palautetut tiedot laitetaan väliaikaisesti CurrencyConversionBean -objektiin. Lopuksi
* luomme uuden bean-objektin, joka palautetaan käyttäjälle.
*
* @param from - Mistä valuutasta käännetään
* @param to - Mihin valuuttaan käännetän
* @param quantity - Rahamäärä, mikä käännetään
* @return - Vastaus mikä kertoo kaikki metatiedot kyselystä, sekä valuutanvaihtoarvon sekä määrän
*/
@GetMapping("/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}")
public CurrencyConversionBean convertCurrencyFeign(@PathVariable String from, @PathVariable String to,
@PathVariable BigDecimal quantity) {
CurrencyConversionBean response = proxy.retrieveExchangeValue(from, to);
logger.info("{}", response);
return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity,
quantity.multiply(response.getConversionMultiple()), response.getPort());
}
}
| [
"[email protected]"
] | |
ffb2e357691b7be8f80537ad86f4f6f585408311 | ba05ff90eedb578495751474fac1c877f2297396 | /app/src/main/java/ca/idea/user1/ideaca/MenuAdapter.java | 015d2a8be05aa06e9f7563ad23f414d03b09d7b6 | [] | no_license | JehanX/Idea.ca-Android- | c3f21e1b7a9ffd5db18559d49978000816764da4 | 6fc6a31848d81d4903420030dc046b78efb417d0 | refs/heads/master | 2020-12-25T22:36:13.025938 | 2016-06-20T20:11:59 | 2016-06-20T20:11:59 | 58,751,879 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,951 | java | package ca.idea.user1.ideaca;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.idea.user1.ideaca.R;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Vector;
/**
* Created by user1 on 5/4/2016.
*/
public class MenuAdapter extends BaseExpandableListAdapter{
//Variables definition
private Context ctx;
private LinkedHashMap<String, List<String>> Menu_Category;
private List<String> Movies_List;
Vector<Integer> Color_List;
//Constructor
public MenuAdapter(Context ctx, LinkedHashMap<String, List<String>> Menu_Category, List<String> Movies_List, Vector<Integer> Color_List) {
this.ctx = ctx;
this.Menu_Category = Menu_Category;
this.Movies_List = Movies_List;
this.Color_List = Color_List;
}
@Override
public int getGroupCount() {
return Movies_List.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return Menu_Category.get(Movies_List.get(groupPosition)).size();
}
@Override
public Object getGroup(int groupPosition) {
return Movies_List.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return Menu_Category.get(Movies_List.get(groupPosition)).get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView) {
String group_title = (String) getGroup(groupPosition);
if (convertView== null) {
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.parent_layout, parentView, false);
}
TextView parent_textview = (TextView) convertView.findViewById(R.id.parent_txt);
parent_textview.setTypeface(null, Typeface.BOLD);
parent_textview.setText(group_title);
if (Color_List.size()>=3) {
parent_textview.setTextColor(Color.rgb(Color_List.get(0), Color_List.get(1), Color_List.get(2)));
}
ImageView img_selection=(ImageView) convertView.findViewById(R.id.imageView);
int imgResourceId = isExpanded? R.drawable.arrowright : R.drawable.arrowdown;
img_selection.setImageResource(imgResourceId);
if (getChildrenCount(groupPosition)==0) {
img_selection.setImageResource(android.R.color.transparent);
}
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parentView) {
String child_title = (String) getChild(groupPosition,childPosition);
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.child_layout, parentView, false);
}
TextView child_textview = (TextView) convertView.findViewById(R.id.child_txt);
child_textview.setText(child_title);
if (Color_List.size()==6) {
child_textview.setTextColor(Color.rgb(Color_List.get(3), Color_List.get(4), Color_List.get(5)));
}
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
| [
"[email protected]"
] | |
d6a27813ac5f5637d7fe9c12caf15a371e430a4c | 7e011de11f5b0745a35272c7eb8ca24ada63580b | /spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java | 15b8bdc8e9c67f836a57afa281c1eb54791ed437 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | sixgodx/spring-cloud-config | 3440036266cb52fd2ac8b01180a11c0ae07bf7c4 | 25b24e640644377d6fa5ace757776a4d5a93d24a | refs/heads/master | 2021-05-30T07:53:30.370120 | 2015-12-30T15:06:15 | 2015-12-30T15:06:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,099 | java | /*
* Copyright 2015 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 org.springframework.cloud.config.monitor;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.http.HttpHeaders;
/**
* @author Dave Syer
*
*/
public class PropertyPathEndpointTests {
private PropertyPathEndpoint endpoint = new PropertyPathEndpoint(
new CompositePropertyPathNotificationExtractor(
Collections.<PropertyPathNotificationExtractor> emptyList()));
@Before
public void init() {
StaticApplicationContext publisher = new StaticApplicationContext();
this.endpoint.setApplicationEventPublisher(publisher);
publisher.refresh();
}
@Test
public void testNotifyByForm() throws Exception {
assertEquals(0, this.endpoint
.notifyByForm(new HttpHeaders(), new ArrayList<String>()).size());
}
@Test
public void testNotifySeveral() throws Exception {
List<String> request = new ArrayList<String>();
request.add("/foo/bar.properties");
request.add("/application.properties");
assertEquals("[bar, *]",
this.endpoint.notifyByForm(new HttpHeaders(), request).toString());
}
@Test
public void testNotifyAll() throws Exception {
assertEquals("[*]",
this.endpoint
.notifyByPath(new HttpHeaders(), Collections
.<String, Object> singletonMap("path", "application.yml"))
.toString());
}
}
| [
"[email protected]"
] | |
03a18c5f7e2d4965a4ea77078cb28fa15ef66302 | 789fc4f608d6b94ed57153f91bd61e6284a450dd | /src/com/unit3/algs3_4RedBlackBST/TestRBBST.java | 0952dee30634e68d7de6d40dd90678cd1c6ddeda | [] | no_license | Kou1688/Algorithms | 161969e350fd612038fc1bbd0fb1a534c824efb8 | 1607549d4a3daf56bc821faec288a4e8de57eef7 | refs/heads/master | 2023-06-23T18:44:44.017614 | 2021-07-14T11:31:20 | 2021-07-14T11:31:20 | 354,233,566 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 470 | java | package com.unit3.algs3_4RedBlackBST;
import java.util.Scanner;
public class TestRBBST {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
RedBlackBST<String, Integer> redBlackBST = new RedBlackBST<>();
for (int i = 0; in.hasNext(); i++) {
String key = in.next();
redBlackBST.put(key, i);
}
System.out.println();
System.out.println(redBlackBST.get("X"));
}
}
| [
"[email protected]"
] | |
79d437ee173d6d29317a0b1dd65ec184182693d1 | 92b9b75a1c7ba8ad25927489b99ad3f18fe99b36 | /Lab_2/src/Romb.java | 5d5cf3148852fe6dd1daf16ab9b10f86ae827137 | [] | no_license | iljakononenko/Kurs_Programowania | abb2f71414c340b190208905eb45a6a74b3ab78c | cc72ef5f18025efc7f4fa6481714dae6fb4d481f | refs/heads/main | 2023-07-12T02:03:20.610014 | 2021-08-01T17:02:32 | 2021-08-01T17:02:32 | 349,814,755 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 402 | java | public class Romb extends Czworokat
{
Romb(double bok1, double kat)
{
super(bok1, bok1, bok1, bok1, kat);
}
@Override
public double count_Pole()
{
pole = Math.pow(bok1, 2) * Math.sin(Math.toRadians(kat));
pole = Math.round(pole * 10.0) / 10.0;
return pole;
}
@Override
public String get_name()
{
return "Romb";
}
}
| [
"[email protected]"
] | |
b4c79e19ea0de60a792f97551f49b2af14a70160 | fd49852c3426acf214b390c33927b5a30aeb0e0a | /aosp/javalib/android/hardware/location/IActivityRecognitionHardwareWatcher$Stub$Proxy.java | be84a71ae1fec6532c98dccf5c41c5187673028b | [] | no_license | HanChangHun/MobilePlus-Prototype | fb72a49d4caa04bce6edb4bc060123c238a6a94e | 3047c44a0a2859bf597870b9bf295cf321358de7 | refs/heads/main | 2023-06-10T19:51:23.186241 | 2021-06-26T08:28:58 | 2021-06-26T08:28:58 | 333,411,414 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,685 | java | package android.hardware.location;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
class Proxy implements IActivityRecognitionHardwareWatcher {
public static IActivityRecognitionHardwareWatcher sDefaultImpl;
private IBinder mRemote;
Proxy(IBinder paramIBinder) {
this.mRemote = paramIBinder;
}
public IBinder asBinder() {
return this.mRemote;
}
public String getInterfaceDescriptor() {
return "android.hardware.location.IActivityRecognitionHardwareWatcher";
}
public void onInstanceChanged(IActivityRecognitionHardware paramIActivityRecognitionHardware) throws RemoteException {
Parcel parcel1 = Parcel.obtain();
Parcel parcel2 = Parcel.obtain();
try {
IBinder iBinder;
parcel1.writeInterfaceToken("android.hardware.location.IActivityRecognitionHardwareWatcher");
if (paramIActivityRecognitionHardware != null) {
iBinder = paramIActivityRecognitionHardware.asBinder();
} else {
iBinder = null;
}
parcel1.writeStrongBinder(iBinder);
if (!this.mRemote.transact(1, parcel1, parcel2, 0) && IActivityRecognitionHardwareWatcher.Stub.getDefaultImpl() != null) {
IActivityRecognitionHardwareWatcher.Stub.getDefaultImpl().onInstanceChanged(paramIActivityRecognitionHardware);
return;
}
parcel2.readException();
return;
} finally {
parcel2.recycle();
parcel1.recycle();
}
}
}
/* Location: /home/chun/Desktop/temp/!/android/hardware/location/IActivityRecognitionHardwareWatcher$Stub$Proxy.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | [
"[email protected]"
] | |
59ec7b5e30bd3e6788f9e8050a64888362d2f15c | 5d04670d930cb5ee13d0cef31e45a839c7fe2ace | /YehuiUtils/easemob/src/main/java/com/alsfox/chatlibrary/widget/EaseChatExtendPrompt.java | 2997ca58fc97f89c2f534edcb0d99ef082251fe3 | [] | no_license | yehuijifeng/YehuiUtils | 5eded3518373d525b920a465aa96dec7932d4ae9 | 876936d1162a9e69b4471b0486249d79eee47a6d | refs/heads/master | 2021-01-10T01:12:36.970300 | 2017-12-13T09:44:26 | 2017-12-13T09:44:26 | 48,544,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,227 | java | package com.alsfox.chatlibrary.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.alsfox.chatlibrary.R;
import com.easemob.util.DensityUtil;
import java.util.ArrayList;
import java.util.List;
/**
* 按?按钮出来的扩展按钮
*
*/
public class EaseChatExtendPrompt extends GridView {
protected Context context;
private List<ChatPromptItemModel> itemModels = new ArrayList<ChatPromptItemModel>();
public EaseChatExtendPrompt(Context context, AttributeSet attrs, int defStyle) {
this(context, attrs);
}
public EaseChatExtendPrompt(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public EaseChatExtendPrompt(Context context) {
super(context);
init(context, null);
}
private void init(Context context, AttributeSet attrs) {
this.context = context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.EaseChatExtendMenu);
int numColumns = ta.getInt(R.styleable.EaseChatExtendMenu_numColumns, 3);
ta.recycle();
setNumColumns(numColumns);
// setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
setGravity(Gravity.CENTER_VERTICAL);
setVerticalSpacing(DensityUtil.dip2px(context, 6));
}
/**
* 初始化
*/
public void init() {
setAdapter(new ItemAdapterX(context, itemModels));
}
/**
* 注册常用语 prompt item
*
* @param name
* item的名字
*
* @param itemId
* id
*
* @param listener
* item的点击事件
*/
public void registerPromptItem(String name, int itemId, EaseChatExtendPromptItemClickListener listener) {
ChatPromptItemModel item = new ChatPromptItemModel();
item.name = name;
item.id = itemId;
item.clickListener = listener;
itemModels.add(item);
}
/**
* 注册常用语 prompt item
*
* @param nameRes
* item名字的resource id
*
* @param itemId
* id
*
* @param listener
* item的点击事件
*/
public void registerPromptItem(int nameRes, int itemId, EaseChatExtendPromptItemClickListener listener) {
registerPromptItem(context.getString(nameRes), itemId, listener);
}
private class ItemAdapterX extends ArrayAdapter<ChatPromptItemModel> {
private Context context;
public ItemAdapterX(Context context, List<ChatPromptItemModel> objects) {
super(context, 0, objects);
this.context = context;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ChatPromptItem promptItem = null;
if (convertView == null) {
convertView = new ChatPromptItem(context);
}
promptItem = (ChatPromptItem) convertView;
promptItem.setText(getItem(position).name);
promptItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (getItem(position).clickListener != null) {
getItem(position).clickListener.onClick(getItem(position).id, v);
}
}
});
return convertView;
}
}
public interface EaseChatExtendPromptItemClickListener {
void onClick(int itemId, View view);
}
class ChatPromptItemModel {
String name;
int id;
EaseChatExtendPromptItemClickListener clickListener;
}
class ChatPromptItem extends LinearLayout {
private TextView textView;
public ChatPromptItem(Context context, AttributeSet attrs, int defStyle) {
this(context, attrs);
}
public ChatPromptItem(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public ChatPromptItem(Context context) {
super(context);
init(context, null);
}
private void init(Context context, AttributeSet attrs) {
LayoutInflater.from(context).inflate(R.layout.easex_chat_prompt_item, this);
textView = (TextView) findViewById(R.id.text);
}
public void setText(int resid) {
textView.setText(resid);
}
public void setText(String text) {
textView.setText(text);
}
}
}
| [
"[email protected]"
] | |
42f0b6418c66e5134eab8a07d0baebbee7976ff8 | 86a79485dc361e33ea34908b032e1447b9889033 | /itsource-service/src/main/java/cn/itsource/crm/service/impl/RoleServiceImpl.java | 15f08aefa7f15c61601bb01d28f55733338f6199 | [] | no_license | solargen/itsource-parent | 21a01764ce513b9fc98cebbb7435246c41ff8a5d | 8d2fe9336555acebb166a12f4668451aee2c9d45 | refs/heads/master | 2022-12-22T19:56:37.232362 | 2019-06-10T02:48:05 | 2019-06-10T02:48:05 | 190,404,830 | 3 | 2 | null | 2022-12-16T03:36:36 | 2019-06-05T13:56:25 | Java | UTF-8 | Java | false | false | 317 | java | package cn.itsource.crm.service.impl;
import cn.itsource.crm.domain.Role;
import cn.itsource.crm.service.impl.BaseServiceImpl;
import cn.itsource.crm.service.IRoleService;
import org.springframework.stereotype.Service;
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService{
}
| [
"[email protected]"
] | |
52d4d461c0fa2a3702fffc4f25d41ff980b36cd9 | 041ac8b3aaa2dee732d9fdefee30500673a7d186 | /de.dc.fx.ui.renderer.model.edit/src-gen/de/dc/fx/ui/renderer/model/provider/FXEventsItemProvider.java | b46d692063b495091561fac48a55c28a176ec672 | [
"Apache-2.0"
] | permissive | chqu1012/FXDesigner | 23185fa6ae87291583728ecd2ea047dc67c33d96 | 55acdcbb1bd3d5bf692727d0fc681c3ada76582d | refs/heads/master | 2020-09-13T12:54:42.733651 | 2019-11-28T06:52:31 | 2019-11-28T06:52:31 | 222,787,152 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,738 | java | /**
*/
package de.dc.fx.ui.renderer.model.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITableItemLabelProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
/**
* This is the item provider adapter for a {@link de.dc.fx.ui.renderer.model.FXEvents} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class FXEventsItemProvider extends ItemProviderAdapter
implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider,
IItemLabelProvider, IItemPropertySource, ITableItemLabelProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FXEventsItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
}
return itemPropertyDescriptors;
}
/**
* This returns FXEvents.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/FXEvents"));
}
/**
* This returns <code>getImage(object)</code> for the column index <code>0</code> or <code>super.getImage(object)</code> otherwise.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getText(Object)
* @see #getColumnText(Object, int)
* @generated
*/
@Override
public Object getColumnImage(Object object, int columnIndex) {
// TODO: implement this method to return appropriate information for each column.
// Ensure that you remove @generated or mark it @generated NOT
return columnIndex == 0 ? getImage(object) : super.getImage(object);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean shouldComposeCreationImage() {
return true;
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
return getString("_UI_FXEvents_type");
}
/**
* This returns <code>getText(object)</code> for the column index <code>0</code> or <code>super.getText(object)</code> otherwise.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImage(Object)
* @see #getColumnImage(Object, int)
* @generated
*/
@Override
public String getColumnText(Object object, int columnIndex) {
// TODO: implement this method to return appropriate information for each column.
// Ensure that you remove @generated or mark it @generated NOT
return columnIndex == 0 ? getText(object) : super.getText(object);
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return UIEditPlugin.INSTANCE;
}
}
| [
"[email protected]"
] | |
a00ba1cdd904e1f47b4ee0ca0b317fe73673c9c1 | 694af613f3d2c33649cfc8cf2701361c699d7aa5 | /ble/src/main/java/com/sitech/crmpd/idmm/ble/main/spring/SpringActorProducer.java | f950b3461d0113474c839c8b0f494005a6ebd71c | [] | no_license | lulugyf/idmm4 | cc72237115fb63364817e16891a0ed84595eb968 | 8f2b022456613e2ca019bd6a69dc3665793f58ba | refs/heads/master | 2020-12-30T16:28:25.274837 | 2017-11-02T09:58:38 | 2017-11-02T09:58:38 | 90,992,561 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 986 | java | package com.sitech.crmpd.idmm.ble.main.spring;
import akka.actor.Actor;
import akka.actor.IndirectActorProducer;
import org.springframework.context.ApplicationContext;
/**
* Created by guanyf on 7/6/2017.
*/
public class SpringActorProducer implements IndirectActorProducer {
private ApplicationContext applicationContext;
private Class<? extends Actor> beanClass;
private Object[] args;
public SpringActorProducer(ApplicationContext applicationContext,
Class<? extends Actor> v, Object...args) {
this.applicationContext = applicationContext;
this.beanClass = v;
this.args = args;
}
@Override
public Actor produce() {
return (Actor) applicationContext.getBean(beanClass, args);
}
@Override
public Class<? extends Actor> actorClass() {
// return (Class<? extends Actor>) applicationContext
// .getType(beanActorName);
return beanClass;
}
} | [
"[email protected]"
] | |
679bac450890fb40d3e8962e2f7b06174a751e57 | 0d9bbf5dca5572f68aab89abc1fbc1795f3e8f32 | /src/main/java/com/waheedtechblog/covid/domain/StateWise.java | cacf33e5a56ab54499e7edb31845661fcc2fc6e4 | [] | no_license | abdulwaheed18/covidtracker | 40b88a8d1762143eee5873d0e854bc9c3ea116b5 | e1a4a5db94ec6e51390efa8a2a9e0417198139cc | refs/heads/master | 2023-04-29T07:23:19.521735 | 2020-05-02T09:09:36 | 2020-05-02T09:09:36 | 259,688,779 | 0 | 0 | null | 2023-04-14T17:56:12 | 2020-04-28T16:14:29 | Java | UTF-8 | Java | false | false | 2,223 | java | package com.waheedtechblog.covid.domain;
public class StateWise {
private String active;
private String confirmed;
private String deaths;
private String deltaconfirmed;
private String deltadeaths;
private String deltarecovered;
private String lastupdatedtime;
private String recovered;
private String state;
private String statecode;
private String statenotes;
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getConfirmed() {
return confirmed;
}
public void setConfirmed(String confirmed) {
this.confirmed = confirmed;
}
public String getDeaths() {
return deaths;
}
public void setDeaths(String deaths) {
this.deaths = deaths;
}
public String getDeltaconfirmed() {
return deltaconfirmed;
}
public void setDeltaconfirmed(String deltaconfirmed) {
this.deltaconfirmed = deltaconfirmed;
}
public String getDeltadeaths() {
return deltadeaths;
}
public void setDeltadeaths(String deltadeaths) {
this.deltadeaths = deltadeaths;
}
public String getDeltarecovered() {
return deltarecovered;
}
public void setDeltarecovered(String deltarecovered) {
this.deltarecovered = deltarecovered;
}
public String getLastupdatedtime() {
return lastupdatedtime;
}
public void setLastupdatedtime(String lastupdatedtime) {
this.lastupdatedtime = lastupdatedtime;
}
public String getRecovered() {
return recovered;
}
public void setRecovered(String recovered) {
this.recovered = recovered;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getStatecode() {
return statecode;
}
public void setStatecode(String statecode) {
this.statecode = statecode;
}
public String getStatenotes() {
return statenotes;
}
public void setStatenotes(String statenotes) {
this.statenotes = statenotes;
}
}
| [
"[email protected]"
] | |
df8d6d3a8ea24dc6c3bc0e3604f5cfe8a5242e87 | 54459304e5cdee530eb74cfc42a37590cfa32202 | /src/com/atuldwivedi/carcentre/learn/spring/carapp/v5_ann/HondaJazz.java | d1e767dc914508686afdbf8aeab9a5e0dbafaf9e | [] | no_license | AtulDwivedi/car-centre | 329c72cb69be1b89f66d3926a79aa13b289e0529 | 9d753bbe23f3437ba9efe526ba8ba22c768fb9fd | refs/heads/master | 2021-01-23T21:16:00.739350 | 2018-07-01T15:22:46 | 2018-07-01T15:22:46 | 102,888,069 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,444 | java | package com.atuldwivedi.carcentre.learn.spring.carapp.v5_ann;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class HondaJazz implements Car {
private MusicSystem musicSystem;
@Value("${hondaJazz.mileage}")
private double mileage;
@Value("${hondaJazz.color}")
private String color;
public void setMileage(double mileage) {
this.mileage = mileage;
}
public void setColor(String color) {
this.color = color;
}
public HondaJazz() {
System.out.println(this.getClass().getSimpleName() + " is being constructed.");
}
@Autowired
@Qualifier("boseMusicSystem")
public void setMusicSystem(MusicSystem musicSystem) {
this.musicSystem = musicSystem;
}
@Override
public void driveTheCar() {
System.out.println("Driving " + color + " " + this.getClass().getSimpleName()
+ " at speed of 80KMPH. It gives mileage of " + mileage);
musicSystem.playMusic();
}
@PostConstruct
public void putCarNumber(){
System.out.println("Car number has been placed on "+this.getClass().getSimpleName());
}
@PreDestroy
public void removeCarNumber(){
System.out.println("Car number has been remved on "+this.getClass().getSimpleName());
}
}
| [
"[email protected]"
] | |
9f8167aeeead219451735d976cb6a4a08b442ee2 | 0b8f2152eebc9f3fb195b1f6370577711a6a09f6 | /common/src/main/java/com/sskj/common/box/decoration/DividerLineItemDecoration.java | 0ce4bf02bf113761bf457b5b7f15bfefff4ac025 | [] | no_license | lvzhihao100/SSKJBase | 4e23ba35e974c47aa4e952e9d1c57a3d411958a3 | 23fa9284e72c03f2c25fba2a872ae45ab9d70bbd | refs/heads/master | 2020-04-01T19:31:48.781488 | 2018-10-18T05:58:59 | 2018-10-18T05:58:59 | 153,558,564 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,487 | java | package com.sskj.common.box.decoration;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class DividerLineItemDecoration extends RecyclerView.ItemDecoration {
//分割线画笔
private Paint mPaint;
//分割线距离左边距离
private int leftPadding = 0;
//分割线距离右边距离
private int rightPadding = 0;
private boolean isFirstDraw = true;
private boolean isLastDraw = true;
private int paintWidth = 1;
private int paintColor = 0xfff3f3f3;
public DividerLineItemDecoration setPaintWidth(int paintWidth) {
this.paintWidth = paintWidth;
mPaint.setStrokeWidth(paintWidth);
return this;
}
public DividerLineItemDecoration setPaintColor(int paintColor) {
this.paintColor = paintColor;
mPaint.setColor(paintColor);
return this;
}
public DividerLineItemDecoration setFirstDraw(boolean firstDraw) {
isFirstDraw = firstDraw;
return this;
}
public DividerLineItemDecoration setLastDraw(boolean lastDraw) {
isLastDraw = lastDraw;
return this;
}
public DividerLineItemDecoration setLeftPadding(int leftPadding) {
this.leftPadding = leftPadding;
return this;
}
public DividerLineItemDecoration setRightPadding(int rightPadding) {
this.rightPadding = rightPadding;
return this;
}
public DividerLineItemDecoration(Context context) {
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(paintWidth);
mPaint.setColor(paintColor);
mPaint.setAntiAlias(true);
}
public DividerLineItemDecoration setDividerColor(int dividerColor) {
mPaint.setColor(dividerColor);
return this;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDrawOver(c, parent, state);
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = parent.getChildAt(i);
int position = parent.getChildAdapterPosition(view);
if (!isFirstDraw && position == 0) {
} else {
c.drawLine(left + leftPadding, view.getTop() - paintWidth, right - rightPadding, view.getTop()-paintWidth, mPaint);
}
if (isLastDraw && parent.getAdapter().getItemCount() == position + 1) {
c.drawLine(left + leftPadding, view.getBottom(), right - rightPadding, view.getBottom(), mPaint);
}
}
}
/**
* 设置item分割线的size
*
* @param outRect outRect
* @param view view
* @param parent parent
* @param state state
*/
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
outRect.set(0, !isFirstDraw && position == 0 ? 0 : paintWidth, 0, isLastDraw && parent.getAdapter().getItemCount() == position + 1 ? paintWidth : 0);
}
} | [
"[email protected]"
] | |
0d532e204812326f90cb47c5f4832c0d545f991f | e00b9dda9fce2ee1904ee8c64061cfcc391be812 | /06-pos/src/main/java/com/github/wenhao/tdd/pos/domain/ShoppingItem.java | a2daf9449614357fa07328bf7a84573fbeb53895 | [
"Apache-2.0",
"Apache-1.1"
] | permissive | wenhao/tdd-workshop | 1e9cc9b7c9d84293fb3deecbe2c7fc1199432143 | 54fda92b64b3ae5649d234fd95fe81fa42114566 | refs/heads/master | 2023-05-27T13:38:50.634248 | 2023-05-26T01:53:37 | 2023-05-26T01:53:37 | 22,065,628 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,835 | java | /*
* Copyright © 2019, Wen Hao <[email protected]>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.wenhao.tdd.pos.domain;
public class ShoppingItem {
private String name;
private Double price;
private Double amount;
public ShoppingItem(String name, Double price) {
this.name = name;
this.price = price;
}
public ShoppingItem(String name, double price, Double amount) {
this.name = name;
this.price = price;
this.amount = amount;
}
public ShoppingItem() {
}
public Double getPrice() {
return price;
}
public Double getAmount() {
return amount;
}
public Double cost() {
return price * amount;
}
public String getName() {
return name;
}
}
| [
"[email protected]"
] | |
c58434c14178d5eccade262090d2652d7856635d | 92b8720e73d3d99b419a8c047acbe56d90ace3ee | /src/main/java/org/rg/messenger/service/CommentService.java | 550d0d82930fc673de7c6b2b395d87d503187bde | [] | no_license | Rgns/Messanger-rest-api-basic | 46301842747fb90284020f4e9fa9f41285f745f2 | 9d8ad057507d2fd4c9569a545af6829ab94ef185 | refs/heads/master | 2022-12-21T20:41:58.055837 | 2020-09-29T13:42:18 | 2020-09-29T13:42:18 | 299,624,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,991 | java | package org.rg.messenger.service;
import org.rg.messenger.database.DatabaseClass;
import org.rg.messenger.model.Comment;
import org.rg.messenger.model.ErrorMessage;
import org.rg.messenger.model.Message;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class CommentService {
private final Map<Long, Message> messageMap = DatabaseClass.getMessageMap();
public List<Comment> getAllComments(long messageId) {
Map<Long, Comment> commentMap = getCommentMap(messageId);
return new ArrayList<Comment>(commentMap.values());
}
public Comment addComment(long messageId, Comment comment) {
comment.setId(getCommentMap(messageId).size() + 1);
getCommentMap(messageId).put(comment.getId(), comment);
return comment;
}
public Comment updateComment(long messageId, long commentId, Comment comment) {
if (messageId > 0 && commentId > 0) {
getCommentMap(messageId).put(commentId, comment);
return comment;
}
return null;
}
public void removeComment(long messageId, long id) {
if (getCommentMap(messageId).get(id) == null) {
// another way of throwing the exception, its not business code so not preferred , so better to have separate Mapper class
ErrorMessage errorMessage = new ErrorMessage(Response.Status.NOT_FOUND.getStatusCode(),
"https://github.com/Rgns",
"Id to be deleted not present");
throw new WebApplicationException(
Response.status(Response.Status.NOT_FOUND)
.entity(errorMessage)
.build()
);
}
getCommentMap(messageId).remove(id);
}
private Map<Long, Comment> getCommentMap(long messageId) {
return messageMap.get(messageId).getComments();
}
}
| [
"[email protected]"
] | |
827bfdf0bdf05055a45b4f4927976070dfaf2829 | 803cd8d4398731a5e4bf47e37cb138ee2ea289cd | /src/main/java/uvsq/pglp_4_2/pglp_4_2/SaisieRPN.java | 48de0f241e30000e1e30f9b10f2f577822c8db4d | [] | no_license | uvsq21606879/pglp_4.2 | 86f1e7d7ce57b6890981ea2b96da79a87c4f6f5c | 416b6c2afd6563695e84cdcb11dd893c93b5a41a | refs/heads/master | 2021-05-17T03:28:21.739875 | 2020-05-23T18:01:00 | 2020-05-23T18:01:00 | 250,598,750 | 0 | 0 | null | 2020-10-13T20:42:23 | 2020-03-27T17:23:49 | Java | UTF-8 | Java | false | false | 503 | java | package uvsq.pglp_4_2.pglp_4_2;
import java.util.Scanner;
public class SaisieRPN {
static MoteurRPN MoteurRPN = new MoteurRPN();
static Interpreteur interpreteur = new Interpreteur();
private static Scanner sc;
public static void InputeStart() throws Exception {
sc = new Scanner(System.in);
String str = sc.nextLine();
while (MoteurRPN.getLecture()) {
Interpreteur.exec(MoteurRPN, str);
str = sc.nextLine();
}
System.out.println(MoteurRPN.afficherExpression() + ".");
}
}
| [
"[email protected]"
] | |
e73305121bccfac7fd721d9c6163bdc6b70971b4 | 9bc2e16bd25461ee4fa641aafb268b5029f9b0e2 | /har_reader/src/main/java/example/model/HarCache.java | e13abd9fddc4e3c97a27fba43c083259e38791bf | [] | no_license | sergueik/selenium_java | 775432bb23f418893551d73d82acd210bf07e43c | 18eca29cd2e87b4e0bdf9f450e7608aae97b8e8d | refs/heads/master | 2023-08-31T21:56:41.765828 | 2023-08-28T23:14:28 | 2023-08-28T23:14:28 | 40,056,997 | 25 | 14 | null | 2023-02-22T08:44:35 | 2015-08-01T19:00:35 | Java | UTF-8 | Java | false | false | 4,557 | java | package example.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.Date;
import java.util.Objects;
/**
* Information about a request coming from browser cache.
* @see <a href="http://www.softwareishard.com/blog/har-12-spec/#cache">specification</a>
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class HarCache {
private HarCacheInfo beforeRequest;
private HarCacheInfo afterRequest;
private String comment;
/**
* @return State of the cache entry before the request, null if not present.
*/
public HarCacheInfo getBeforeRequest() {
return beforeRequest;
}
public void setBeforeRequest(HarCacheInfo beforeRequest) {
this.beforeRequest = beforeRequest;
}
/**
* @return State of the cache entry after the request, null if not present.
*/
public HarCacheInfo getAfterRequest() {
return afterRequest;
}
public void setAfterRequest(HarCacheInfo afterRequest) {
this.afterRequest = afterRequest;
}
/**
* @return Comment provided by the user or application, null if not present.
*/
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HarCache harCache = (HarCache) o;
return Objects.equals(beforeRequest, harCache.beforeRequest) &&
Objects.equals(afterRequest, harCache.afterRequest) &&
Objects.equals(comment, harCache.comment);
}
@Override
public int hashCode() {
return Objects.hash(beforeRequest, afterRequest, comment);
}
/**
* Information about a request coming from browser cache.
* @see <a href="http://www.softwareishard.com/blog/har-12-spec/#cache">specification</a>
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public static final class HarCacheInfo {
private Date expires;
private Date lastAccess;
private String eTag;
private Integer hitCount;
private String comment;
/**
* @return Expiration time of entry, null if not present.
*/
@JsonFormat(shape = JsonFormat.Shape.STRING)
public Date getExpires() {
return expires;
}
public void setExpires(Date expires) {
this.expires = expires;
}
/**
* @return Last time the entry was opened, null if not present.
*/
@JsonFormat(shape = JsonFormat.Shape.STRING)
public Date getLastAccess() {
return lastAccess;
}
public void setLastAccess(Date lastAccess) {
this.lastAccess = lastAccess;
}
/**
* @return ETag, null if not present.
*/
public String geteTag() {
return eTag;
}
public void seteTag(String eTag) {
this.eTag = eTag;
}
/**
* @return Number of times the entry has been opened, null if not present.
*/
public Integer getHitCount() {
return hitCount;
}
public void setHitCount(Integer hitCount) {
this.hitCount = hitCount;
}
/**
* @return Comment provided by the user or application, null if not present.
*/
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HarCacheInfo that = (HarCacheInfo) o;
return Objects.equals(expires, that.expires) &&
Objects.equals(lastAccess, that.lastAccess) &&
Objects.equals(eTag, that.eTag) &&
Objects.equals(hitCount, that.hitCount) &&
Objects.equals(comment, that.comment);
}
@Override
public int hashCode() {
return Objects.hash(expires, lastAccess, eTag, hitCount, comment);
}
}
}
| [
"[email protected]"
] | |
727a5dab32cb8dd752db6fdd6e60882c03e91ce6 | 0a5d9bcdfaf3adde8c8b3e7914ac65dd6da277b4 | /JavaWeb/PrjProdutoDBSession/src/prjProdutosDBSession/InserirCarrinhoServlet.java | 3fe4419efd302ae79aa52c335b5d1cf22769b76a | [] | no_license | lucasbenossi/5COP011-Lab | 4ed3967ce4d86a745a1764e09075f3dd075e18cb | 53d592d6a27602fa177eadabb699d4d8d00b22cd | refs/heads/master | 2020-03-27T06:49:36.865776 | 2018-10-30T22:18:39 | 2018-10-30T22:19:15 | 146,138,394 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,336 | java | package prjProdutosDBSession;
import java.io.IOException;
import java.util.LinkedList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/inserir-carrinho")
public class InserirCarrinhoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public InserirCarrinhoServlet() {
super();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProdutoDAO produtoDAO = new ProdutoDAO();
Produto produto = produtoDAO.buscarPorId(Long.parseLong(request.getParameter("id")));
HttpSession session = request.getSession();
Object carrinhoObj = session.getAttribute("carrinho");
if(carrinhoObj == null){
LinkedList<Produto> carrinho = new LinkedList<Produto>();
carrinho.add(produto);
session.setAttribute("carrinho", carrinho);
}
else{
LinkedList<Produto> carrinho = (LinkedList<Produto>)carrinhoObj;
carrinho.add(produto);
}
RequestDispatcher view = request.getRequestDispatcher("index.jsp");
view.forward(request, response);
}
}
| [
"[email protected]"
] | |
5cd237884ca2faac240acc1d4fb88efee3ea653f | 2bcd656775ca3462f1983e0d262d9c6e75484293 | /src/hipster/controller/HipsterRunner.java | 5809e0d1292cc70706ac108e25e7330065a74828 | [] | no_license | isaach0011/ArrayProject | af9464d84564be917cd3c905fb7b297caddd4a7a | 080a59884c3aeb8311c6d4af3a68b74add479eff | refs/heads/master | 2020-07-28T06:32:32.745595 | 2016-12-02T18:35:34 | 2016-12-02T18:35:34 | 73,419,395 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 210 | java | package hipster.controller;
public class HipsterRunner
{
public static void main (String [] args)
{
HipsterAppController arrayAppController = new HipsterAppController();
arrayAppController.start();
}
}
| [
"[email protected]"
] | |
de04a201b409ea40d1e260d9b0d74fca067c8530 | d2ec93e4e9bd4eaa453c64080162131548aeae46 | /src/main/java/com/thedevpiece/api/ResponseObject.java | 1f2b7e95b2409b2ad5b7261b47ead4f9d15073d5 | [
"MIT"
] | permissive | gabfssilva/functional-java-rest-api | 9d98460931d15310c3f4efb7c88b17593df48ff3 | efb515622e11d13fb9c2c467650ce7dd61199123 | refs/heads/master | 2021-01-20T20:53:38.737081 | 2016-06-28T21:14:50 | 2016-06-28T21:14:50 | 62,076,604 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,036 | java | package com.thedevpiece.api;
/**
* @author Gabriel Francisco <[email protected]>
*/
public class ResponseObject {
private int status;
private String location;
private String body;
public ResponseObject() {
}
public static ResponseObject response() {
return new ResponseObject();
}
public ResponseObject(int status, String location, String body) {
this.status = status;
this.location = location;
this.body = body;
}
public ResponseObject withStatus(int status) {
return new ResponseObject(status, location, body);
}
public ResponseObject withLocation(String location) {
return new ResponseObject(status, location, body);
}
public ResponseObject withBody(String body) {
return new ResponseObject(status, location, body);
}
public int getStatus() {
return status;
}
public String getLocation() {
return location;
}
public String getBody() {
return body;
}
}
| [
"[email protected]"
] | |
100299a75879bb5b7c3fb6b8a5ae4aa1d0792acb | 33e569f0dd0662e375438f65826f1883edf3ccca | /4.JavaCollections/src/com/javarush/task/task40/task4010/Solution.java | f863a705f264641724e8cf9c70373f50c6792b66 | [
"MIT"
] | permissive | MariPhoenix/JavaRushTasks | bb288fc0e8517891903b4cb936823ec5b820633d | e56fe4f8926f6afa0b899f812e75b32f69b418b7 | refs/heads/master | 2020-03-21T09:28:13.485928 | 2018-06-28T11:30:53 | 2018-06-28T11:30:53 | 138,401,352 | 0 | 0 | MIT | 2018-06-23T13:01:38 | 2018-06-23T13:01:38 | null | UTF-8 | Java | false | false | 2,193 | java | package com.javarush.task.task40.task4010;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/*
Коды ошибок
В методе main присутствуют ошибки. Исправь их. Постарайся сделать минимум изменений.
Результатом работы программы должно быть отображение JSON документа по ссылке url.
Требования:
1. У соединения должен быть корректно установлен параметр User-Agent с помощью метода setRequestProperty.
2. В случае, если код ответа не равен 200, должно быть выброшено исключение RuntimeException.
3. В случае, если код ответа равен 200, на экран должна быть выведена информация полученная из InputStream соединения.
4. В методе main должен быть создан новый объект типа URL.
*/
public class Solution {
public static void main(String[] args) {
try {
URL url = new URL("http://jsonplaceholder.typicode.com/posts/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
77a61bae13a416da0b54877f09005c253196ff5c | b2dd4c953e4cc305d22c942b68d50582a16cdd3a | /supermarket/target/tomcat/work/Tomcat/localhost/supermarket/org/apache/jsp/WEB_002dINF/jsp/vip/list_jsp.java | 95ec8df1969e6f9eef10ebdb5ef570723d248ce9 | [] | no_license | yldzxz/supermarket | dc3303b350768019456c73bc783d262fa04f7e0e | a4b07a450b892766b2acd3a444bb3a0c2db189d3 | refs/heads/master | 2020-03-27T13:29:43.778420 | 2018-08-29T14:34:09 | 2018-08-29T14:34:09 | 146,612,872 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,243 | java | /*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.47
* Generated at: 2017-04-12 14:35:33 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp.WEB_002dINF.jsp.vip;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class list_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
out.write("<html>\r\n");
out.write("<head>\r\n");
out.write("<title>Insert title here</title>\r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");
out.write("\r\n");
out.write("</body>\r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| [
"[email protected]"
] | |
880ab66b72fd3f7645b1a99c8edb0790a5977bc0 | bde04df06ab34c445bc58ef01656b4a4c2e12e50 | /MavenProj/src/main/resources/Pack/TestMVN.java | 38d0b88ef84cebf4c10d5a5cfb8934b198b7da06 | [] | no_license | manickambe91/JenkinsProject | 7ab8c111720b6e65d86f7ef3c5024f46548f09da | 08723cc568abff0433a7000995bc03d60e3527b8 | refs/heads/master | 2021-10-27T12:15:07.062813 | 2019-04-17T07:26:03 | 2019-04-17T07:26:03 | 181,629,953 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 160 | java | package Pack;
public class TestMVN {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello Manick");
}
}
| [
"[email protected]"
] | |
a74062b71aac1f8ab4796ca48424cd3fe96c273b | 3a929fb2aa2b87936ead8c26ce753ef6f5c58273 | /LightDSTest/test/general/TestObjectsToEntity.java | ae14bac8e9136c95e5cffcf8b3ef84366224554b | [] | no_license | M-jerez/jemsDS | 5be974efd2965815c0cc3efac7d6aabc3bb14a91 | 6401684a486ab8026cc0d1b5cbbab94861745ecc | refs/heads/master | 2020-04-14T03:00:29.852144 | 2012-11-29T12:33:56 | 2012-11-29T12:33:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,604 | java | package general;
import mjerez.jmicrobench.JMicrobench;
import mjerez.jmicrobench.Registry;
import mjerez.jmicrobench.TimeProfiler;
import models.Car;
import models.Estudent;
import models.House;
import models.Worker;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.jems.datastore.DsEntityBuilder;
public class TestObjectsToEntity implements JMicrobench{
@SuppressWarnings("unchecked")
@Override
public void runBench() {
DatastoreService dsService = DatastoreServiceFactory.getDatastoreService();
TimeProfiler tp = Registry.getTimeProfiler("objects to entity.");
tp.startCount("init");
Estudent antony = new Estudent("Antony", "Phyton university");
Estudent peter = new Estudent("Peter", "Java university");
Worker mary = new Worker("Mary", "MegaSoft");
Worker harry = new Worker("Harry", "Megasoft");
House sharedHouse = new House();
House marysHouse = new House();
Car marysCar = new Car();
/* establish relationships */
peter.friends.add(harry);
harry.boss = mary;
mary.friends.add(harry);
mary.friends.add(antony);
mary.possessions.add(marysHouse);
mary.possessions.add(marysCar);
marysHouse.owners.add(mary);
marysCar.owners.add(mary);
sharedHouse.occupants.add(harry);
dsService.put(new DsEntityBuilder(
peter, harry, mary, marysHouse,
marysCar, sharedHouse, antony).simpleBuild()
);
tp.stopCount("init");
}
}
| [
"mjerez@mjerez-PC"
] | mjerez@mjerez-PC |
1d9e9c0cfa2c610abb14503ddee38e85b159b35d | 0f78eb1bd70ee3ea0cbd7b795d7e946255366efd | /src-common/com/qfw/common/bizservice/permission/impl/UserBSImpl.java | 1c8e73e2c2790e9a2161f03eb372eaaacc0e579d | [] | no_license | xie-summer/sjct | b8484bc4ee7d61b3713fa2e88762002f821045a6 | 4674af9a0aa587b5765e361ecaa6a07f966f0edb | refs/heads/master | 2021-06-16T22:06:06.646687 | 2017-05-12T09:24:52 | 2017-05-12T09:24:52 | 92,924,351 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 30,331 | java | package com.qfw.common.bizservice.permission.impl;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.qfw.bizservice.credit.report.ICreditReportBS;
import com.qfw.bizservice.custinfo.ICustInfoBS;
import com.qfw.bizservice.custinfo.account.ICustAccountBS;
import com.qfw.bizservice.custinfo.recommendation.IRecommendationBS;
import com.qfw.common.bizservice.PromotionService.PromotionService;
import com.qfw.common.bizservice.impl.BaseServiceImpl;
import com.qfw.common.bizservice.permission.IUserBS;
import com.qfw.common.bizservice.permission.IUserInfoSyncBS;
import com.qfw.common.dao.permission.IUserDAO;
import com.qfw.common.exception.BizException;
import com.qfw.common.log.LogFactory;
import com.qfw.common.model.BussConst;
import com.qfw.common.model.permission.SysRole;
import com.qfw.common.model.permission.SysUser;
import com.qfw.common.model.permission.vo.SysUserVO;
import com.qfw.common.util.CollectionUtil;
import com.qfw.common.util.DateUtils;
import com.qfw.common.util.MD5Utils;
import com.qfw.common.util.RamdomUtil;
import com.qfw.common.util.StringUtils;
import com.qfw.common.util.web.ViewOper;
import com.qfw.model.AppConst;
import com.qfw.model.bo.BizAccountBO;
import com.qfw.model.bo.BizCreditLimitBO;
import com.qfw.model.bo.BizCreditReportBO;
import com.qfw.model.bo.BizCreditUseBO;
import com.qfw.model.bo.BizCustomerBO;
import com.qfw.platform.model.vo.LoginInfo;
import com.qfw.platform.model.vo.UserInfo;
public class UserBSImpl extends BaseServiceImpl implements IUserBS {
@Autowired
private ICustInfoBS custInfoBS;
@Autowired
private ICustAccountBS custAccountBS;
@Autowired
private ICreditReportBS creditReportBS;
@Autowired
private PromotionService promotionService;
@Autowired
private IRecommendationBS recommendationBS;
@Resource(name = "userInfoSync")
private IUserInfoSyncBS userInfoSyncBS;
private IUserDAO userDAO;
private Logger log = LogFactory.getInstance().getBusinessLogger();
public List<SysUser> findUsersByVO(SysUserVO userVO) {
StringBuilder sb = new StringBuilder("from SysUser");
sb.append(VO2Condition(userVO));
return userDAO.findByHQL(sb.toString());
}
public int findUsersCountByVO(SysUserVO userVO) {
return commonQuery.findCountByWapSQL(wrapSelectUserSQL(userVO), null);
/*
* StringBuilder sb = new
* StringBuilder("select count(userId) from SysUser");
* sb.append(VO2Condition(userVO)); return userDAO.count(sb.toString());
*/
}
private String VO2Condition(SysUserVO userVO) {
StringBuilder sb = new StringBuilder(" where 1=1");
if (userVO != null) {
if (StringUtils.isNotEmpty(userVO.getUserName())) {
sb.append(" and userName like '%").append(userVO.getUserName())
.append("%'");
}
if (StringUtils.isNotEmpty(userVO.getUserCode())) {
sb.append(" and userCode like '%").append(userVO.getUserCode())
.append("%'");
}
if (StringUtils.isNotEmpty(userVO.getIsAdmin())) {
sb.append(" and is_admin = '").append(userVO.getIsAdmin()).append("'");
}
}
return sb.toString();
}
public SysUser findUserById(Integer id) {
return (SysUser) userDAO.findById(SysUser.class, id);
}
public IUserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(IUserDAO userDAO) {
this.userDAO = userDAO;
}
public void merge(SysUser user) {
this.userDAO.merge(user);
}
@Override
public List<SysUser> findUsersPagesByVO(SysUserVO userVO, int first,
int pageSize) {
return commonQuery.findBySQLByPages(wrapSelectUserSQL(userVO), first,
pageSize, SysUserVO.class);
/*
* StringBuilder sb = new StringBuilder("from SysUser where 1=1");
* if(userVO!=null){ if(StringUtils.isNotEmpty(userVO.getUserName())){
* sb
* .append(" and userName like '%").append(userVO.getUserName()).append
* ("%'"); } if(StringUtils.isNotEmpty(userVO.getUserCode())){
* sb.append(
* " and userCode like '%").append(userVO.getUserCode()).append("%'"); }
* } return userDAO.findByHQLByPages(sb.toString(), first, pageSize);
*/
}
private String wrapSelectUserSQL(SysUserVO userVO) {
StringBuilder sb = new StringBuilder("");
StringBuilder where = new StringBuilder(
" WHERE 1=1 ");
if (StringUtils.isNotEmpty(userVO.getIsAdmin())) {
where.append(" and is_admin = '").append(userVO.getIsAdmin()).append("'");
}
if (StringUtils.isNotEmpty(userVO.getUserName())) {
where.append(" AND U.USER_NAME LIKE '%")
.append(userVO.getUserName()).append("%'");
}
if (StringUtils.isNotEmpty(userVO.getUserCode())) {
where.append(" AND U.USER_CODE LIKE '%")
.append(userVO.getUserCode()).append("%'");
}
if (StringUtils.isNotEmpty(userVO.getRoleIds())) {
where.append(" AND EXISTS (SELECT 1 FROM SYS_USER_ROLE UR WHERE UR.USER_ID = U.USER_ID AND UR.ROLE_ID IN ("
+ userVO.getRoleIds() + "))");
}
if (StringUtils.isNotEmpty(userVO.getDeptIds())) {
// where.append(" AND U.USER_ID = UD.USER_ID AND D.DEPT_ID = UD.DEPT_ID");
where.append(" AND UD.DEPT_ID IN (").append(userVO.getDeptIds())
.append(")");
// sb.append("SELECT U.*,GROUP_CONCAT(D.DEPT_ID) AS DEPT_IDS,GROUP_CONCAT(D.DEPT_NAME) AS DEPT_NAMES FROM SYS_USER U,SYS_USER_DEPT UD,SYS_DEPT D ");
// sb.append(where);
} else {
// sb.append("SELECT U.* FROM SYS_USER U ").append(where);
}
sb.append(" SELECT U.*,GROUP_CONCAT(D.DEPT_ID) AS DEPT_IDS,GROUP_CONCAT(D.DEPT_NAME) AS DEPT_NAMES FROM SYS_USER U LEFT JOIN SYS_USER_DEPT UD ON U.USER_ID = UD.USER_ID LEFT JOIN SYS_DEPT D ON D.DEPT_ID = UD.DEPT_ID");
sb.append(where);
sb.append(" GROUP BY U.USER_ID");
return sb.toString();
}
@Override
public int findUserCount(String userCode) {
// StringBuilder sb = new StringBuilder(
// "select count(userId) from SysUser where lower(userCode) = '"
// + userCode.toLowerCase() + "'");
StringBuilder sb = new StringBuilder(
"select count(u.userId) from SysUser u,BizCustomerBO c where lower(u.userCode) = '"
+ userCode.toLowerCase() + "'"
+ "and u.userId = c.userId ");
return userDAO.count(sb.toString());
}
public int getIsAdminCount(String userCode) {
StringBuilder sb = new StringBuilder(
"select count(u.userId) from SysUser u where lower(u.userCode) = '"
+ userCode.toLowerCase() + "'"
+ "and isAdmin = '1' ");
return userDAO.count(sb.toString());
}
public List<SysUser> findExistUser(String cardId,String tel) {
try {
String queryString = "from SysUser where cardid = ? or tel = ?";
List<SysUser> list = getHibernateTemplate().find(queryString, new Object[]{cardId,tel} );
if (list != null && !list.isEmpty()) {
return list;
}
return null;
} catch (Exception e) {
}
return null;
}
public SysUser findUser(String userCode) {
try {
String queryString = "from SysUser where lower(userCode) = ?";
List list = getHibernateTemplate().find(queryString, userCode.toLowerCase());
if (list != null && !list.isEmpty()) {
return (SysUser) list.get(0);
}
return null;
} catch (Exception e) {
}
return null;
}
@Override
public List<SysRole> getUserRoles(String userID) {
String sql = "select role_id,role_code,role_name from sys_role where role_id in (select role_id from sys_user_role where user_id = '"
+ userID + "')";
// this.getCommonQuery().findObjects(sql, SysRole.class);
return this.getCommonQuery().findObjects(sql, SysRole.class);
}
@Override
public List findObjectsByPages(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, String> filters,
LazyDataModel lazyDataMode) {
StringBuilder hqlString = new StringBuilder(
"from SysUser user where 1=1 ");
if (filters != null && !filters.isEmpty()) {
Set<String> keys = filters.keySet();
for (String key : keys) {
if ("isAllowFriend".equals(key)) {
hqlString.append(" and ").append(key).append(" in (")
.append(filters.get(key)).append(")");
} else {
hqlString.append(" and ").append(key).append(" like '%")
.append(filters.get(key)).append("%'");
}
}
}
int count = this.count("select count(user) " + hqlString.toString());
if (StringUtils.isNotEmpty(sortField)) {
if (!SortOrder.UNSORTED.equals(sortOrder)) {
hqlString.append(" order by ").append(sortField);
if (SortOrder.DESCENDING.equals(sortOrder)) {
hqlString.append(" desc");
}
}
}
lazyDataMode.setRowCount(count);
return userDAO.findByHQLByPages(hqlString.toString(), first, pageSize);
}
public List findObjectsByPages(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, String> filters,
LazyDataModel lazyDataMode, String condition) {
StringBuilder hqlString = new StringBuilder(
"from SysUser user where 1=1" + condition);
if (filters != null && !filters.isEmpty()) {
Set<String> keys = filters.keySet();
for (String key : keys) {
hqlString.append(" and ").append(key).append(" like '%")
.append(filters.get(key)).append("%'");
}
}
int count = this.count("select count(user) " + hqlString.toString());
if (StringUtils.isNotEmpty(sortField)) {
if (!SortOrder.UNSORTED.equals(sortOrder)) {
hqlString.append(" order by ").append(sortField);
if (SortOrder.DESCENDING.equals(sortOrder)) {
hqlString.append(" desc");
}
}
}
lazyDataMode.setRowCount(count);
return userDAO.findByHQLByPages(hqlString.toString(), first, pageSize);
}
public boolean findUsersExist() {
return false;
}
/**
* 保存系统用户机构表
*/
public void saveDept(SysUser user) throws BizException {
try {
String sql = "INSERT INTO SYS_USER_DEPT(USER_ID,DEPT_ID,SYS_CREATE_TIME) VALUES ("
+ user.getUserId() + ",'1',sysdate())";
this.getJdbcTemplate().execute(sql.toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.error(e.getMessage());
}
throw new BizException(e.getMessage());
}
}
/**
* 保存系统用户注册信息
*/
public void saveUser(SysUser user) {
this.save(user);
}
/**
* 用户注册
*/
public void tranRegister(SysUser user) {
this.saveUser(user);
baseDAO.flush();
saveDefaultDeptAndRole(user);
}
/**
* 保存系统用户机构表和用户角色表
*/
private void saveDefaultDeptAndRole(SysUser user) {
String sql = "INSERT INTO SYS_USER_DEPT(USER_ID,DEPT_ID) VALUES ("
+ user.getUserId() + ",'" + BussConst.BUYER_DEPT + "')";
this.getJdbcTemplate().execute(sql.toString());
sql = "INSERT INTO SYS_USER_ROLE(USER_ID,ROLE_ID) VALUES ("
+ user.getUserId() + ",'" + BussConst.BUYER_ROLE + "')";
this.getJdbcTemplate().execute(sql.toString());
}
public void updateUserOfLoginOutTime(SysUser user) {
String sql = "UPDATE SYS_USER SET LOGOUT_TIME = sysdate() WHERE USER_CODE = '"
+ user.getUserCode() + "'";
this.getJdbcTemplate().execute(sql.toString());
}
public SysUser findUserByUserId(Integer userId) {
try {
String queryString = "from SysUser where userId = ?";
List list = getHibernateTemplate().find(queryString, userId);
if (list != null && !list.isEmpty()) {
return (SysUser) list.get(0);
}
return null;
} catch (Exception e) {
}
return null;
}
public SysUser findUserByCustId(Integer custId) {
try {
String queryString = "select s from SysUser s,BizCustomerBO c where s.userId = c.userId and c.id = ?";
List list = getHibernateTemplate().find(queryString, custId);
if (list != null && !list.isEmpty()) {
return (SysUser) list.get(0);
}
return null;
} catch (Exception e) {
}
return null;
}
@Override
public void deleteUserByUserId(Integer userId) {
String sql = "DELETE FROM SYS_USER_DEPT WHERE USER_ID = '" + userId
+ "'";
getJdbcTemplate().execute(sql);
sql = "DELETE FROM SYS_USER_ROLE WHERE USER_ID = '" + userId + "'";
getJdbcTemplate().execute(sql);
sql = "DELETE FROM SYS_USER WHERE USER_ID = '" + userId + "'";
getJdbcTemplate().execute(sql);
// 删除会员信息表
/*sql = "DELETE FROM biz_customer WHERE USER_ID = '" + userId + "'";
getJdbcTemplate().execute(sql);*/ //delete by yangjj
}
@Override
public void saveUserRole(Integer userId, Integer roleId)
throws BizException {
SysUser sysUser = (SysUser) ViewOper.getSession().getAttribute("user");
StringBuilder sb = new StringBuilder(
" INSERT INTO SYS_USER_ROLE(USER_ID, ROLE_ID, SYS_CREATE_TIME, SYS_UPDATE_TIME, SYS_UPDATE_USER)");
sb.append(" VALUES(").append(userId).append(",");
sb.append(roleId).append(",");
sb.append("sysdate(),sysdate(),'");
sb.append(sysUser.getUserCode()).append("')");
this.getJdbcTemplate().execute(sb.toString());
}
@Override
public void saveUserDept(Integer userId, Integer deptId)
throws BizException {
SysUser sysUser = (SysUser) ViewOper.getSession().getAttribute("user");
StringBuilder sb = new StringBuilder(
" INSERT INTO SYS_USER_DEPT(USER_ID, DEPT_ID, SYS_CREATE_TIME, SYS_UPDATE_TIME, SYS_UPDATE_USER)");
sb.append(" VALUES(").append(userId).append(",");
sb.append(deptId).append(",");
sb.append("sysdate(),sysdate(),'");
sb.append(sysUser.getUserCode()).append("')");
this.getJdbcTemplate().execute(sb.toString());
}
/**
* 添加用户
*
* @param user
* @param deptIds
* @throws BizException
* @throws NumberFormatException
*/
public void addUser(SysUser user, String[] deptIds, String[] roleIds)
throws BizException {
getHibernateTemplate().saveOrUpdate(user);
this.saveUserLinkInfo(user);
if (deptIds != null && deptIds.length > 0) {
for (String deptId : deptIds) {
saveUserDept(user.getUserId(), Integer.valueOf(deptId));
}
}
if (roleIds != null && roleIds.length > 0) {
for (String roleId : roleIds) {
saveUserRole(user.getUserId(), Integer.valueOf(roleId));
}
}
}
/**
* 更新用户信息
*
* @param user
* @param deptIds
*/
public void updateUser(SysUser user, String[] deptIds, String[] roleIds)
throws BizException {
getHibernateTemplate().update(user);
this.saveUserLinkInfo(user);
String sql = "DELETE FROM SYS_USER_DEPT WHERE USER_ID = '"
+ user.getUserId() + "'";
getJdbcTemplate().execute(sql);// 删除用户机构信息
sql = "DELETE FROM SYS_USER_ROLE WHERE USER_ID = '" + user.getUserId()
+ "'";
getJdbcTemplate().execute(sql);// 删除角色关联信息
if (deptIds != null && deptIds.length > 0) {
for (String deptId : deptIds) {
saveUserDept(user.getUserId(), Integer.valueOf(deptId));
}
}
if (roleIds != null && roleIds.length > 0) {
for (String roleId : roleIds) {
saveUserRole(user.getUserId(), Integer.valueOf(roleId));
}
}
// SELECT * FROM SYS_USER_ROLE UR WHERE UR.USER_ID = '1' AND NOT EXISTS
// (SELECT 1 FROM SYS_ROLE R,SYS_DEPT D WHERE UR.ROLE_ID = R.ROLE_ID AND
// R.DEPT_ID = D.DEPT_ID AND R.DEPT_ID NOT IN ('3','10001'))
}
@Override
public int findUserCountByTel(String tel) {
// StringBuilder sb = new StringBuilder(
// "select count(userId) from SysUser where tel = '" + tel + "'");
StringBuilder sb = new StringBuilder(
"select count(u.userId) from SysUser u,BizCustomerBO c where u.tel = '" + tel + "'"
+ "and u.userId = c.userId");
return userDAO.count(sb.toString());
}
@Override
public int findUserCountByEmail(String email) {
// StringBuilder sb = new StringBuilder(
// "select count(userId) from SysUser where lower(email) = '" + email.toLowerCase()
// + "'");
StringBuilder sb = new StringBuilder(
"select count(u.userId) from SysUser u,BizCustomerBO c where lower(u.email) = '"
+ email.toLowerCase()+ "'"
+ "and u.userId = c.userId");
//System.out.println("sb.toString() enami =="+sb.toString());
return userDAO.count(sb.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void saveRegisterUser(String mobile, String email,String custCode, String password,
String refereeName) throws BizException {
Integer refCustId = null;
BizCustomerBO refCust = null;
List<BizCustomerBO> customer = custInfoBS.findCustomer(mobile);
if(customer != null && customer.size() > 0){
throw new BizException("重复的手机号码");
}
if(StringUtils.isNotEmpty(refereeName)){
refCust = custInfoBS.findCustByRefereeCode(refereeName);
}else{
refCust = custInfoBS.findCustByRefereeCode(AppConst.DEFALT_REFEREECODE);
}
if(refCust == null){
throw new BizException("获取不到推荐人信息");
}
refCustId = refCust.getId();
try {
String passwordMd5 = MD5Utils.getMD5Str(password);
SysUser user = new SysUser();
user.setUserCode(custCode);
user.setPassword(passwordMd5);
user.setEmail(email);
user.setTel(mobile);
user.setUserReferee(refereeName);
getHibernateTemplate().save(user);
getHibernateTemplate().flush();
BizCustomerBO cust = new BizCustomerBO();
cust.setMobileTelephone(mobile);
cust.setUserId(user.getUserId());
cust.setEmail(email);
// cust.setRefereeName(refereeName);
cust.setRefereeId(refCustId);
//生成推荐码
cust.setRefereeCode(RamdomUtil.getRefereeCode());
cust.setCustTypeCd(AppConst.CUST_TYPE_CD_COMMON);
getHibernateTemplate().save(cust);
// getHibernateTemplate().flush();
BizAccountBO accountBO = new BizAccountBO();
accountBO.setCustId(cust.getId());
accountBO.setAccount(user.getUserCode());
accountBO.setAccountTypeCd(AppConst.ACCOUNT_TYPE_CUST);
accountBO.setAccountBalAmt(BigDecimal.ZERO);
accountBO.setFreezeBalAmt(BigDecimal.ZERO);
accountBO.setUsableBalAmt(BigDecimal.ZERO);
accountBO.setPmAmt(BigDecimal.ZERO);
accountBO.setSysCreateTime(new Date());
accountBO.setSysCreateUser(cust.getId());
accountBO.setSysUpdateUser(cust.getId());
accountBO.setSysUpdateTime(new Date());
getHibernateTemplate().save(accountBO);
BizCreditReportBO reportBO = new BizCreditReportBO();
reportBO.setCustId(cust.getId());
reportBO.setCreditAmt(new BigDecimal(0));//信用额度
// reportBO.setRemainAmt(new BigDecimal(0));//剩余额度
reportBO.setRemainAmt(AppConst.DEFALT_CREDITLIMIT);//剩余额度
reportBO.setApplyLoanNum(new Integer(0));//申请借款笔数
reportBO.setApproveNum(new Integer(0));//成功借款笔数
reportBO.setPayOffNum(new Integer(0));//还清笔数
reportBO.setLoanTolAmt(new BigDecimal(0));//还款总金额
reportBO.setOverdueAmt(new BigDecimal(0));//逾期总额
reportBO.setOverdueNum(new Integer(0));//逾期次数
reportBO.setPrincipaInterestAmt(new BigDecimal(0));//待还本息
reportBO.setSerOverdueNum(new Integer(0));//严重逾期
reportBO.setLoanBal(new BigDecimal(0));//借款余额
getHibernateTemplate().save(reportBO);
//推荐奖励
// recommendationBS.recommendReward(refCustId);
} catch (Exception e) {
log.error("保存用户信息失败:========="+e.getMessage());
throw new BizException("保存用户信息失败:"+e.getMessage());
}
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void saveUserLinkInfo(SysUser user) throws BizException {
BizCustomerBO cust = this.custInfoBS.findCustByUserId(user.getUserId());
boolean isNull = false;
if(null == cust){
cust = new BizCustomerBO();
cust.setUserId(user.getUserId());
cust.setSysCreateTime(new Date());
isNull = true;
}
cust.setCustName(user.getUserName());
cust.setSex(user.getSex());
cust.setQq(user.getQq());
cust.setMobileTelephone(user.getTel());
cust.setEmail(user.getEmail());
cust.setCertificateNum(user.getCardid());
cust.setSysUpdateTime(new Date());
if(StringUtils.isEmpty(cust.getRefereeCode())){
cust.setRefereeCode(RamdomUtil.getRefereeCode());
}
getHibernateTemplate().saveOrUpdate(cust);
BizAccountBO accountBO = this.custAccountBS.findCustAccount(cust.getId());
if(null == accountBO){
accountBO = new BizAccountBO();
accountBO.setCustId(cust.getId());
accountBO.setAccountBalAmt(BigDecimal.ZERO);
accountBO.setFreezeBalAmt(BigDecimal.ZERO);
accountBO.setUsableBalAmt(BigDecimal.ZERO);
accountBO.setAccount(user.getUserCode());
accountBO.setAccountTypeCd(AppConst.ACCOUNT_TYPE_CUST);
accountBO.setPmAmt(new BigDecimal(0));
accountBO.setSysCreateTime(new Date());
accountBO.setSysUpdateTime(new Date());
accountBO.setWorkItemId("0");
getHibernateTemplate().save(accountBO);
}
BizCreditReportBO reportBO = this.creditReportBS.findByCustInfo(cust.getId().toString());
if(null==reportBO.getId()){
getHibernateTemplate().save(reportBO);
}
/*try {
//同步用户信息
UserInfo userInfo = new UserInfo();
userInfo.setMobile(user.getTel());
userInfo.setLoginName(user.getUserCode());
// userInfo.setRefereeName(registerInfo.getRecommender());
userInfo.setBirthday(DateUtils.getDateString("yyyy-MM-dd", user.getBirthDate()));
userInfo.setIdCard(user.getCardid());
userInfo.setMobile(user.getTel());
userInfo.setMail(user.getEmail());
userInfo.setSex("0".equals(cust.getSex()) ? "F" : "M");
if(isNull){
userInfo.setPassword(user.getPassword());
userInfo.setOperate(AppConst.USERINFOSYNC_OPERATE_REG);
}else{
userInfo.setOperate(AppConst.USERINFOSYNC_OPERATE_MOD);
}
this.userInfoSyncBS.userInfoSync(userInfo);
} catch (Exception e) {
log.error("用户信息同步失败");
}*/
}
@Override
public int getUserCountByIdCard(String IdCard) throws BizException {
StringBuilder sb = new StringBuilder(
"select count(userId) from SysUser where CARDID = '" + IdCard
+ "'");
return userDAO.count(sb.toString()) ;
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfIdCard(String name,String idCard,LoginInfo loginInfo) throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET user_name = '"+name+"',cardid='"+idCard+"' "
+ " WHERE USER_CODE = '" + loginInfo.getUserCode()+ "'");
this.getJdbcTemplate().execute(sql.toString());
StringBuilder sqlstr = new StringBuilder("UPDATE biz_customer SET CERTIFICATE_TYPE_CD='0',CUST_NAME = '"+name+"',CERTIFICATE_NUM='"+idCard+"' "
+ "WHERE id = '" + loginInfo.getCustId()+ "'");
this.getJdbcTemplate().execute(sqlstr.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfIdCard(String name,String idCard,String birthDate,LoginInfo loginInfo) throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET user_name = '"+name+"',cardid='"+idCard+"',BIRTH_DATE = '"+birthDate+"'"
+ " WHERE USER_CODE = '" + loginInfo.getUserCode()+ "'");
this.getJdbcTemplate().execute(sql.toString());
StringBuilder sqlstr = new StringBuilder("UPDATE biz_customer SET CERTIFICATE_TYPE_CD='0',CUST_NAME = '"+name+"',CERTIFICATE_NUM='"+idCard+"',BIRTH_DATE = '"+birthDate+"'"
+ " WHERE id = '" + loginInfo.getCustId()+ "'");
this.getJdbcTemplate().execute(sqlstr.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateIdCardByMobile(String name,String idCard,String mobile) throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET user_name = '"+name+"',cardid='"+idCard+"' WHERE TEL = '" + mobile+ "' AND IS_ADMIN IS NULL");
this.getJdbcTemplate().execute(sql.toString());
StringBuilder sqlstr = new StringBuilder("UPDATE biz_customer SET CERTIFICATE_TYPE_CD='0',CUST_NAME = '"+name+"',CERTIFICATE_NUM='"+idCard+"' WHERE MOBILE_TELEPHONE = '" + mobile+ "'");
this.getJdbcTemplate().execute(sqlstr.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfStatus(String status, String userCode)
throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET STATUS = '"+status+"' WHERE lower(USER_CODE) = '" + userCode.toLowerCase() + "'");
this.getJdbcTemplate().execute(sql.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfPassword(String Password, Integer userId)
throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET PASSWORD = '"+Password+"' WHERE USER_ID = " + userId);
this.getJdbcTemplate().execute(sql.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updatePasswordByMobile(String password, String mobile)
throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET PASSWORD = '"+password+"' WHERE TEL = '"+password+"' "
+ "AND IS_ADMIN IS NULL");
this.getJdbcTemplate().execute(sql.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfPhone(String Phone, Integer userId)
throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET tel = '"+Phone+"' WHERE USER_ID = " + userId );
this.getJdbcTemplate().execute(sql.toString());
sql = new StringBuilder("UPDATE biz_customer SET MOBILE_TELEPHONE = '"+Phone+"' WHERE USER_ID = " + userId );
this.getJdbcTemplate().execute(sql.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfCashPassword(String cashPasswrod, Integer userId)
throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET trade_password = '"+cashPasswrod+"' WHERE USER_ID = " + userId );
this.getJdbcTemplate().execute(sql.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfEmail(String email, String status,
String userCode) throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET email = '"+email+"',status='"+status+"' WHERE lower(USER_CODE) = '" + userCode.toLowerCase() + "'" );
this.getJdbcTemplate().execute(sql.toString());
sql = new StringBuilder("SELECT USER_ID FROM SYS_USER WHERE lower(USER_CODE) = ?");
List<SysUser> list = commonQuery.findObjects(sql.toString(), new Object[]{userCode.toLowerCase()},SysUser.class);
if(null == list){
throw new BizException("找不到该客户");
}
sql = new StringBuilder("UPDATE biz_customer SET EMAIL = '"+email+"' WHERE USER_ID = " + list.get(0).getUserId());
this.getJdbcTemplate().execute(sql.toString());
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfpassanswer(String passanswer,Integer userId) throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET PASSANSWER = ? WHERE USER_ID = ?" );
this.getJdbcTemplate().update(sql.toString(),new Object[]{passanswer,userId});
}
@Override
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public void updateUserOfPromotLevel(String promotLevel, Integer userId)
throws BizException {
StringBuilder sql = new StringBuilder("UPDATE SYS_USER SET PASSQUESTION = ?,INTRODUCTION=INTRODUCTION+1 WHERE USER_ID = ?" );
this.getJdbcTemplate().update(sql.toString(),new Object[]{promotLevel,userId});
}
@Override
public SysUser findUserByTel(String tel) {
StringBuilder sb = new StringBuilder(
"from SysUser where tel = ?");
List list = userDAO.findByHQL(sb.toString(), new Object[]{tel}) ;
SysUser sysUser = null;
if(CollectionUtil.isNotEmpty(list)){
sysUser = (SysUser) list.get(0);
}
return sysUser;
}
@Override
public String getMd5Password(String userCode, String password)
throws BizException {
return MD5Utils.getMD5Str(password);
}
@Override
public void updatePwdALL() throws BizException {
SysUser sysUser = new SysUser();
String Md5password = "";
List list = this.findByHQL("From SysUser where userCode is not null");
for(int i=0;i<list.size();i++){
sysUser = (SysUser) list.get(i);
try {
Md5password = this.getMd5Password(sysUser.getUserCode(), "123456");
//System.out.println("userCode=="+sysUser.getUserCode()+"Md5password=="+Md5password);
this.updateUserOfPassword(Md5password, sysUser.getUserId());
} catch (BizException e) {
// TODO Auto-generated catch block
}
}
}
@Override
public SysUser findUserByAll(String userCode) {
try {
String queryString = "from SysUser where lower(userCode) = ? or lower(email) = ? or tel = ?";
List list = getHibernateTemplate().find(queryString, new Object[]{userCode.toLowerCase(),userCode.toLowerCase(),userCode} );
if (list != null && !list.isEmpty()) {
return (SysUser) list.get(0);
}
return null;
} catch (Exception e) {
}
return null;
}
public IUserInfoSyncBS getUserInfoSyncBS() {
return userInfoSyncBS;
}
public void setUserInfoSyncBS(IUserInfoSyncBS userInfoSyncBS) {
this.userInfoSyncBS = userInfoSyncBS;
}
}
| [
"[email protected]"
] | |
40d1a7bd83541ec6a5d27819d78a9ecb05d9f84c | 7bf936a136e8b8aab712304143ab975a2003bbe3 | /testng-core/src/test/java/test/beforegroups/issue2359/ListenerAdapter.java | c2c8f8d1de08179129b8d0a19a84708e12365255 | [
"Apache-2.0"
] | permissive | kdevendraraju/testng | 342045b373a25ec22e8f835fda81be66d9e1c63e | 38279c6deae78cbfe0c616540b869bf69e9c896d | refs/heads/master | 2023-06-08T15:34:40.539124 | 2023-05-30T02:59:47 | 2023-05-30T02:59:47 | 214,407,171 | 0 | 0 | Apache-2.0 | 2019-10-21T17:08:19 | 2019-10-11T10:21:50 | Java | UTF-8 | Java | false | false | 592 | java | package test.beforegroups.issue2359;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
public class ListenerAdapter extends TestListenerAdapter {
private final Collection<ITestResult> passedConfiguration = new ConcurrentLinkedQueue<>();
@Override
public void onConfigurationSuccess(ITestResult itr) {
super.onConfigurationSuccess(itr);
this.passedConfiguration.add(itr);
}
public Collection<ITestResult> getPassedConfiguration() {
return passedConfiguration;
}
}
| [
"[email protected]"
] | |
5563d970785bef97bf72b07258a74e4d1d96cdfb | fb4a36691d850ee107431d56e58b35b8e4d5b0cf | /src/main/java/com/myuoong/appAdmin/model/AuthTrade.java | 66dd84eadb1c24e1676d5c6b3754b14e88733f68 | [] | no_license | parkjungwoong/bootSecurityMybatis | 0514362680c1dc4164b4ada3d0342b70eee05196 | db596ff0c514eee7bd95b2e69ac3fa585179f510 | refs/heads/master | 2020-05-01T11:01:28.886194 | 2019-04-01T00:52:23 | 2019-04-01T00:52:23 | 177,432,405 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 257 | java | package com.myuoong.appAdmin.model;
import lombok.Data;
import org.apache.ibatis.type.Alias;
@Data
@Alias("authTrade")
public class AuthTrade {
private String tradeNo;
private String userId;
private String regDt;
private String autoYn;
}
| [
"[email protected]"
] | |
7414499535ab2c7a2735c01aa7af4ba2947e3c1d | c19b3b218812669cc9882b3cef4be9cd3fe02810 | /src/main/java/com/dbservice1/dbservice1/mongo/model/Product.java | da1cad25d0694cb1ae210c8701653468dadc3a96 | [] | no_license | karthickkm/db-service1 | 1c47238d8a0b840322d382614bec6cac53f4ea88 | a549cca01bbc34e46e91977b62791b054f57445f | refs/heads/master | 2021-04-27T06:15:39.372647 | 2018-02-23T10:58:53 | 2018-02-23T10:58:53 | 122,610,158 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 672 | java | package com.dbservice1.dbservice1.mongo.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "Product")
public class Product {
@Id
private String id;
private String UPC;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUPC() {
return UPC;
}
public void setUPC(String UPC) {
this.UPC = UPC;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"[email protected]"
] | |
7882397e42e78aaaa52d592f4a9a09ea5b3b8b79 | 986483fb78d68924b29625270be57daa5d66163d | /src/main/java/ua/pp/kaeltas/pizzaorders/domain/PercentOfTotalOrderDiscountCalculator.java | 47b153fbdd24678a4f40e0fb6750f54443ad1d2f | [] | no_license | digitalfog/pizzaorders | 7beda1f72b56f698f434dcb73660baedf42f37f2 | 91726e79e25c0f369579a5670f330713e1093e2a | refs/heads/master | 2021-01-23T04:53:40.587723 | 2015-08-25T08:47:17 | 2015-08-25T08:47:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 720 | java | package ua.pp.kaeltas.pizzaorders.domain;
public class PercentOfTotalOrderDiscountCalculator implements DiscountCalculator {
private final int SUM_FOR_10_PERCENT_DISCOUNT = 1000;
private final int SUM_FOR_20_PERCENT_DISCOUNT = 2000;
@Override
public int calculateDiscount(int orderPrice, int accumulativeCardSum) {
if (orderPrice < 0 || accumulativeCardSum < 0) {
throw new IllegalArgumentException("Negative orderPrice or accumulative card sum");
}
int discount = 0;
if (accumulativeCardSum >= SUM_FOR_20_PERCENT_DISCOUNT) {
discount = orderPrice * 20/100;
} else if (accumulativeCardSum >= SUM_FOR_10_PERCENT_DISCOUNT) {
discount = orderPrice * 10/100;
}
return discount;
}
}
| [
"[email protected]"
] | |
61511b9214e485fe24eb30712191b6b9650c82f4 | 1eed90d5ed903573162530fbd615df4e13dc478c | /src/com/test/designPatterns/strategy/PlaneTypeInf.java | 75c2f3d1ffc34c270afebaabfe402e56d473f0f7 | [] | no_license | sysodaocaoren/SpringMVC | 4b47659cbec05ded240be20943b76191f46e59d7 | 36c88635732f3a9076d31ccb71793cb73f38a8b1 | refs/heads/master | 2021-01-19T09:46:42.388837 | 2017-07-25T14:04:01 | 2017-07-25T14:04:01 | 87,785,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 110 | java | package com.test.designPatterns.strategy;
public interface PlaneTypeInf {
public void getPlanType();
}
| [
"zhu7029630541"
] | zhu7029630541 |
dc58d26d817046fa8ef9c62ccb7982d608cc9792 | bedd18983522a9b35a2f397220ac63bbe99f9699 | /src/main/java/com/carecaminnovations/mobile/model/Metrics.java | 4c32e3aea147381186491f8d95edddbebde00c3a | [] | no_license | rfreedman/CCRuleEngine | f5c524577fb19d5adb20b7be65cfadfe871c250e | fe972318d0af0c6999aec7b92995dca619e5341e | refs/heads/master | 2016-08-08T06:30:47.563175 | 2014-10-01T15:26:42 | 2014-10-01T15:26:42 | 24,660,522 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,113 | java | package com.carecaminnovations.mobile.model;
import java.util.List;
public class Metrics {
private String name;
private String icon;
private String label;
private String metricId;
private List<Measure> measures;
private List<Report> reports;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getMetricId() {
return metricId;
}
public void setMetricId(String metricId) {
this.metricId = metricId;
}
public List<Measure> getMeasures() {
return measures;
}
public void setMeasures(List<Measure> measures) {
this.measures = measures;
}
public List<Report> getReports() {
return reports;
}
public void setReports(List<Report> reports) {
this.reports = reports;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
} | [
"[email protected]"
] | |
0e1593ff462d7918f7a8037bfd11aab1a0109494 | a812c3bd0c16498f28f6d530beafe3e124199b2b | /demo/src/main/java/com/nillith/android/app/miscutilsdemo/MatchParentDemo.java | 40da709cbc22a288491ed613cd49bc899f9d6c87 | [
"Apache-2.0"
] | permissive | NethunterJack/AndroidMiscUtils | db805aff285c12ce251e67cc3ec103c4086a5982 | 9f2e65c759a4c00c78ca4cea4f252aa2fe5777ae | refs/heads/master | 2020-04-11T01:41:39.345198 | 2016-08-04T12:57:06 | 2016-08-04T12:57:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 875 | java | package com.nillith.android.app.miscutilsdemo;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.Window;
import com.nillith.android.common.support.widget.MatchParentDialog;
/**
* Created by Nil on 2016/3/5.
*/
public class MatchParentDemo extends MatchParentDialog {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_match_parent);
dialog.getWindow().findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
return dialog;
}
}
| [
"[email protected]"
] | |
b32be0f08461385e8d0a27bc9c26bf01a0dc58b1 | ef4ff6a9f021714dae1003d05f4d914ccaeb7198 | /commonlibary/src/main/java/sun/common/widget/recycler/EmptyItem.java | f9e9472dd1006bca89ff2edc61a256b8ab3432d3 | [] | no_license | SoundYoung/QiLe | 7bf392a08190c7c4d57fb28145d1cb3ccc628ec9 | b6abea0236754846d03816e5a71e885c8a416f5f | refs/heads/master | 2020-04-28T10:05:13.316535 | 2019-03-12T10:49:08 | 2019-03-12T10:49:08 | 175,190,789 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 357 | java | package sun.common.widget.recycler;
import android.view.View;
import android.view.ViewGroup;
/**
* 没数据时候的默认View
*
* @author zzz40500 on 16/1/31.
*/
public abstract class EmptyItem {
CharSequence mEmptyText;
int mEmptyIconRes = -1;
abstract View onCreateView(ViewGroup parent);
abstract void onBindData(View view);
}
| [
"[email protected]"
] | |
007c033fb105db9ba60bf35367243ca2137862bd | ba373b5b5576db00242224e39c4ea471e80aa9d5 | /src/main/java/com/example/restapi/controllers/DoctorController.java | 4b1407ea848a80ae09d1941745e0a8f0a4c65407 | [] | no_license | georgeFulgeanu/RESTExample | 8e79242b8bf05ed4ef63d32f613c2564a4da260b | d70fa0cb7e568bc679a4e6dd71ca4e2f78ff7094 | refs/heads/master | 2020-04-26T04:07:43.914734 | 2019-03-01T12:01:56 | 2019-03-01T12:01:56 | 173,290,940 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,727 | java | package com.example.restapi.controllers;
import com.example.restapi.entities.Doctor;
import com.example.restapi.repositories.DoctorRepository;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
@RestController
public class DoctorController {
private final DoctorRepository doctorRepository;
public DoctorController(DoctorRepository doctorRepository) {
this.doctorRepository = doctorRepository;
}
@GetMapping("/doctors")
Resources<Resource<Doctor>> getAllDoctors() {
List doctors = doctorRepository.findAll().stream()
.map(doctor -> new Resource(doctor,
linkTo(methodOn(DoctorController.class).getDoctor(doctor.getId())).withSelfRel(),
linkTo(methodOn(DoctorController.class).getAllDoctors()).withRel("doctors"))
)
.collect(Collectors.toList());
return new Resources<>(doctors,
linkTo(methodOn(DoctorController.class).getAllDoctors()).withSelfRel());
}
@PostMapping("/doctors")
Doctor addDoctor(@RequestBody Doctor doctor) {
return doctorRepository.save(doctor);
}
@GetMapping("/doctors/{id}")
Resource<Doctor> getDoctor(@PathVariable Long id) {
Doctor doctor = doctorRepository.findById(id)
.orElseThrow(() -> new DoctorNotFoundException(id));
return new Resource<>(doctor,
linkTo(methodOn(DoctorController.class).getDoctor(id)).withSelfRel(),
linkTo(methodOn(DoctorController.class).getAllDoctors()).withRel("doctors"));
}
@PutMapping("/doctors/{id}")
private Doctor replaceDoctor(@RequestBody Doctor newDoctor, @PathVariable Long id) {
return doctorRepository.findById(id)
.map(doctor -> {
doctor.setName(newDoctor.getName());
doctor.setSpecialization(newDoctor.getSpecialization());
return doctorRepository.save(doctor);
})
.orElseGet(
() -> {
newDoctor.setId(id);
return doctorRepository.save(newDoctor);
}
);
}
@DeleteMapping("/doctors/{id}")
void deleteDoctor(@PathVariable Long id){
doctorRepository.deleteById(id);
}
}
| [
"[email protected]"
] | |
5ed44d9d8a67698a60a16d97922d4a05badf85f3 | 10e380714d84d03a3ba134c6d38621b54d73b84c | /src/gc2/intent/book_airplane/plan/BookAirplaneAskBackPlan.java | 22af10e7cdcaf63bae6545b0f45b4917e15ebe42 | [] | no_license | DavinciATeam/GC2DS | ba20d840db8545fcd9f41212f8242b8636627b25 | 516ed6b9fecf3c46500be13c1466560841152d9d | refs/heads/master | 2021-02-27T05:32:08.626366 | 2020-03-07T07:16:53 | 2020-03-07T07:16:53 | 245,583,472 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,440 | java | package gc2.intent.book_airplane.plan;
import java.util.List;
import java.util.Map;
import java.util.Set;
import gc2.ds.module.DSTerm;
import gc2.intent.book_airplane.module.model.AirplanePrice;
import gc2.intent.book_airplane.module.model.AirplaneSchedule;
import gc2.intent.common.module.AskBackTerm;
import gc2.intent.common.module.GoalTerm;
import gc2.intent.common.module.IntentTerm;
import tw.edu.ncu.csie.lab.core.ai.cells.bdi.IAnima;
import tw.edu.ncu.csie.lab.core.ai.cells.communication.InnerPool;
import tw.edu.ncu.csie.lab.core.ai.cells.ligand.ILigand;
import tw.edu.ncu.csie.lab.core.ai.cells.plan.AExecutionPlan;
import tw.edu.ncu.csie.lab.core.ai.cells.re.IListenAndSay;
public class BookAirplaneAskBackPlan extends AExecutionPlan {
public BookAirplaneAskBackPlan(IAnima anima, ILigand ligand) {
super(anima, ligand);
}
@Override
public void execute() throws Exception {
// Get Information
String intent = (String) this.ligand.getReference().get(IntentTerm.Intent);
Map<String, Object> intentMap = (Map<String, Object>) this.ligand.getReference().get(IntentTerm.IntentMap);
Map<String, String> extractMap = (Map<String, String>) intentMap.get(IntentTerm.ExtractMap);
boolean isAchieveGoal = (boolean) intentMap.get(IntentTerm.IsAchieveGoal);
InnerPool pool = (InnerPool) ligand.getReference().get(IntentTerm.IntentPool);
IListenAndSay gui = (IListenAndSay) ligand.getReference().get(DSTerm.SimpleGUI);
// Add Information
// Achieve Goal
if(isAchieveGoal){
String finishAskBack = this.generateFinishAskBack(extractMap);
String exportForm = this.generateExportForm(extractMap);
intentMap.put(IntentTerm.AskBack, finishAskBack);
intentMap.put(IntentTerm.ExportForm, exportForm);
}
pool.getOutPool().put(intent, intentMap);
}
private String generateFinishAskBack(Map<String, String> extractMap){
StringBuffer askBack = new StringBuffer();
for(String key: extractMap.keySet()){
String value = extractMap.get(key);
askBack.append(key+":"+value+"\n");
}
return askBack.toString();
}
private String generateExportForm(Map<String, String> extractMap){
StringBuffer exportForm = new StringBuffer();
for(String key: extractMap.keySet()){
String value = extractMap.get(key);
exportForm.append(key+":"+value+"\n");
}
return exportForm.toString();
}
}
| [
"[email protected]"
] | |
99e69f36e18d1d162a3d2988907a4e109b2f3dcd | ba2e0d4764016ef2426a197717d6350227823147 | /src/main/java/com/example/personalcloud/controller/FileController.java | 21045965228c6e9f452b925e2829e7179f28491c | [] | no_license | Vllblvck/Chmurka | c797c6d35ce40a305c5466ad4cb86bd7e459e712 | 5c264aa72560a379854194592f1dbf1fd2000198 | refs/heads/master | 2023-06-05T19:15:38.051998 | 2021-06-22T11:32:46 | 2021-06-22T11:32:46 | 355,673,411 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,593 | java | package com.example.personalcloud.controller;
import com.example.personalcloud.config.Routes;
import com.example.personalcloud.exception.StorageException;
import com.example.personalcloud.exception.StorageNotMultipartException;
import com.example.personalcloud.model.FileMetadataResponse;
import com.example.personalcloud.model.FileUploadResponse;
import com.example.personalcloud.service.StorageService;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
//TODO Add logger
@RestController
public class FileController {
private final StorageService storageService;
@Autowired
public FileController(StorageService storageService) {
this.storageService = storageService;
}
@PostMapping(Routes.UPLOAD_FILE)
public ResponseEntity<FileUploadResponse> uploadFile(HttpServletRequest request) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
throw new StorageNotMultipartException("Request is not a multipart/form-data");
}
FileItemIterator fileItemIterator;
try {
fileItemIterator = new ServletFileUpload().getItemIterator(request);
} catch (FileUploadException | IOException ex) {
throw new StorageException("Exception while getting file iterator from request", ex);
}
return new ResponseEntity<>(storageService.store(fileItemIterator), HttpStatus.CREATED);
}
@GetMapping(Routes.FILES_METADATA)
public ResponseEntity<List<FileMetadataResponse>> getFilesMetadata() {
return new ResponseEntity<>(storageService.getFilesMetadata(), HttpStatus.OK);
}
@GetMapping(Routes.DOWNLOAD_FILE)
public ResponseEntity<StreamingResponseBody> downloadFile(@PathVariable long fileId) {
return new ResponseEntity<>(storageService.download(fileId), HttpStatus.OK);
}
@DeleteMapping(Routes.DELETE_FILE)
public ResponseEntity deleteFile(@PathVariable long fileId) {
storageService.delete(fileId);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
}
| [
"[email protected]"
] | |
5806bf7e4c92b169a7853bb17d00b0b4b1ffadcd | a42440fd76472cc4c5350d9378d4cb939bf1b9e7 | /app/src/main/java/zhao/siqi/com/androidvideoplayer/activity/SMActivity.java | 3eb020b4f5e726a27fde4a623f329242e02330ef | [] | no_license | luoyiqi/AndroidVideoPlayer | 59828cc61816e815151e4383077ce21469bc1cdf | e66d7f8d7f6a2dffe144ca851cafe37490cce6e7 | refs/heads/master | 2021-07-13T05:40:53.792869 | 2017-10-17T08:03:58 | 2017-10-17T08:03:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,090 | java | package zhao.siqi.com.androidvideoplayer.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.ButterKnife;
import zhao.siqi.com.androidvideoplayer.R;
import zhao.siqi.com.androidvideoplayer.Utils;
import zhao.siqi.com.androidvideoplayer.view.VideoAddress;
import static zhao.siqi.com.androidvideoplayer.Utils.formatTime;
/**
* SurfaceView + MediaPlayer
* <p>
* 后期需要添加自定义控制栏
*/
public class SMActivity extends AppCompatActivity {
private SurfaceView surfaceView = null;
private SurfaceHolder surfaceHolder = null;
private MediaPlayer mediaPlayer = null;
private ImageView imageView_main_show = null;
private PopupWindow popupWindow;
private ImageView imageView_play;
private SeekBar seekBar;
private TextView textView_playTime;
private TextView textView_duration;
private String filePath = null;
// 自动隐藏自定义播放器控制条的时间
private static final int HIDDEN_TIME = 5000;
private float densityRatio = 1.0f; // 密度比值系数(密度比值:一英寸中像素点除以160)
private MyVideoBroadcastReceiver receiver = null;
// 设置定时器
private Timer timer = null;
private final static int WHAT = 0;
private Runnable r = new Runnable() {
@Override
public void run() {
// 又回到了主线程
showOrHiddenController();
}
};
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case WHAT:
if (mediaPlayer != null) {
int currentPlayer = mediaPlayer.getCurrentPosition();
if (currentPlayer > 0) {
mediaPlayer.getCurrentPosition();
textView_playTime.setText(Utils.formatTime(currentPlayer));
// 让seekBar也跟随改变
int progress = (int) ((currentPlayer / (float) mediaPlayer.getDuration()) * 100);
seekBar.setProgress(progress);
} else {
textView_playTime.setText("00:00");
seekBar.setProgress(0);
}
}
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sm);
ButterKnife.bind(this);
initView();
initMediaPlayer();
initController();
// 动态注册广播接受者
receiver = new MyVideoBroadcastReceiver();
registerReceiver(receiver, new IntentFilter("SurfaceViewMediaPlayer"));
}
/**
* 初始化控制器
* popwindow
*/
private void initController() {
View controllerView = getLayoutInflater().inflate(R.layout.layout_pop, null);
// 初始化popopWindow
popupWindow = new PopupWindow(controllerView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
imageView_play = (ImageView) controllerView.findViewById(R.id.imageView_play);
seekBar = (SeekBar) controllerView.findViewById(R.id.seekbar);
textView_playTime = (TextView) controllerView.findViewById(R.id.textView_playtime);
textView_duration = (TextView) controllerView.findViewById(R.id.textView_totaltime);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
// 表示手指拖动seekbar完毕,手指离开屏幕会触发以下方法
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// 让计时器延时执行
handler.postDelayed(r, HIDDEN_TIME);
}
// 在手指正在拖动seekBar,而手指未离开屏幕触发的方法
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// 让计时器取消计时
handler.removeCallbacks(r);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
int playtime = progress * mediaPlayer.getDuration() / 100;
mediaPlayer.seekTo(playtime);
}
}
});
// 点击播放的时候,判断是播放还是暂停
imageView_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (imageView_main_show.getVisibility() == View.VISIBLE) {
imageView_main_show.setVisibility(View.GONE);
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
imageView_play.setImageResource(R.drawable.icon_direct_p);
} else {
mediaPlayer.start();
imageView_play.setImageResource(R.drawable.icon_direct_n);
}
}
});
}
/**
* 显示和隐藏控制器
*/
private void showOrHiddenController() {
if (popupWindow.isShowing()) {
popupWindow.dismiss();
} else {
// 将dp转换为px
int controllerHeightPixel = (int) (densityRatio * 40);
popupWindow.showAsDropDown(surfaceView, 0, -controllerHeightPixel);
// 延时执行
handler.postDelayed(r, HIDDEN_TIME);
}
}
/**
* 初始化mediaPlayer
*/
private void initMediaPlayer() {
// 视频文件路径
filePath = VideoAddress.getInstance().localPath;
if (mediaPlayer == null) {
// 1,创建MediaPlay对象
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
// mediaPlayer.start();
mediaPlayer.setLooping(false);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
// 表示准备完成,设置总的时长,使用时间格式化工具
// String duration = mediaPlayer.getDuration() ;
textView_duration.setText(formatTime(mediaPlayer.getDuration()));
// 初始化定时器
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(WHAT);
}
}, 0, 1000);
}
});
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// 发送广播,播放下一首歌曲
Intent intent = new Intent();
intent.setAction("SurfaceViewMediaPlayer");
sendBroadcast(intent);
}
});
}
/**
* 初始化布局
*/
private void initView() {
densityRatio = getResources().getDisplayMetrics().density; // 表示获取真正的密度
imageView_main_show = (ImageView) findViewById(R.id.imageView_main_play);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView_main);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mediaPlayer != null) {
mediaPlayer.setDisplay(surfaceHolder);
// mediaPlayer.start() ;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
});
// 设置屏幕的触摸监听
surfaceView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// 表示在点击的瞬间就显示控制条
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
showOrHiddenController();
break;
}
return true;
}
});
}
/**
* 设置控件的监听事件
*
* @param v
*/
public void clickButton(View v) {
switch (v.getId()) {
case R.id.imageView_main_play:
imageView_main_show.setVisibility(View.GONE);
mediaPlayer.start();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 解绑广播
unregisterReceiver(receiver);
timer.cancel();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
handler.removeCallbacksAndMessages(null);
}
/**
* 广播接收器
*/
class MyVideoBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("SurfaceViewMediaPlayer")) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.drawable.ic_launcher)
.setTitle("提示")
.setMessage("视屏播放完毕,是否播放")
.setNegativeButton("取消", null)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mediaPlayer.setLooping(false);
mediaPlayer.start();
}
}).show();
}
}
}
}
| [
"[email protected]"
] | |
86b918888b76315f8f567ea26f00bf6f4b9c79c5 | 6cc76ec06196af303d82dac8c124f6b981cda9b0 | /src/H12/opdracht_2.java | e929811d5270673e862ea6d9a09d46fb5131968e | [] | no_license | MaximusTheGitter/Java | 5134d4ef7c0d3e7eca2037be1c9674c32537aad6 | 0d8dd849bc0feae576aa02b4dc5532dbc9143247 | refs/heads/master | 2020-03-29T15:40:54.802831 | 2018-12-03T12:35:36 | 2018-12-03T12:35:36 | 148,472,217 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 369 | java | package H12;
import java.awt.*;
import java.applet.*;
public class opdracht_2 extends Applet{
Button[] button = new Button[100];
public void init(){
for (int teller = 1; teller <= 25; teller++){
button[teller] = new Button("button " + teller);
add(button[teller]);
}
}
public void paint(Graphics g){
}
}
| [
"[email protected]"
] | |
f51d35879077e1768d6b6a0104cf1ea54638d673 | 6313e39559d535ea414f3efd115af36875ad2b6b | /eureka_client1/src/main/java/com/example/eureka_client1/EurekaClient1Application.java | 4bcbf54789e27ce81a2c77b3180eb63b73a293d1 | [] | no_license | haohaodiniyao/springcloud_example | b3fbb6c97c46fd995b8c23ecdf4d83f1b12ed1dc | 931d77b46bf05d95699b65580622fd06b9948d50 | refs/heads/master | 2020-06-01T01:03:55.547489 | 2017-07-06T06:58:27 | 2017-07-06T06:58:27 | 94,056,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 760 | java | package com.example.eureka_client1;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableEurekaClient
@SpringBootApplication
public class EurekaClient1Application {
@Value("${server.port}")
private String port;
public static void main(String[] args) {
SpringApplication.run(EurekaClient1Application.class, args);
}
@RequestMapping("/getPort")
public String getPort(){
return "服务端口:"+port;
}
}
| [
"[email protected]"
] | |
51228f6843cdf44bd538c2b3d095bfee52fb5173 | 3b0ffbd80de3ecbeee585996261f1512e79aca10 | /src/main/java/cn/lwy/mapper/DepartPostionMapper.java | 749b7859924ce128b1a0882cd72b319732763afc | [] | no_license | devinx3/interview | d2ed42610e8ac8a5df8cba0e1a8a7d6826d2d329 | c335ccbc1144bee4121b6f9c046a05f48493c2df | refs/heads/master | 2021-08-29T08:59:01.094270 | 2019-09-24T05:23:29 | 2019-09-24T05:23:29 | 128,600,066 | 0 | 0 | null | 2021-08-25T14:52:47 | 2018-04-08T05:07:11 | Java | UTF-8 | Java | false | false | 951 | java | package cn.lwy.mapper;
import cn.lwy.pojo.DepartPostion;
import cn.lwy.pojo.DepartPostionExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface DepartPostionMapper {
int countByExample(DepartPostionExample example);
int deleteByExample(DepartPostionExample example);
int deleteByPrimaryKey(String content);
int insert(DepartPostion record);
int insertSelective(DepartPostion record);
List<DepartPostion> selectByExample(DepartPostionExample example);
DepartPostion selectByPrimaryKey(String content);
int updateByExampleSelective(@Param("record") DepartPostion record, @Param("example") DepartPostionExample example);
int updateByExample(@Param("record") DepartPostion record, @Param("example") DepartPostionExample example);
int updateByPrimaryKeySelective(DepartPostion record);
int updateByPrimaryKey(DepartPostion record);
} | [
"[email protected]"
] | |
0b6c0a15da7aa4c70b808c3dd399388d7c718d95 | 425c21c36801d4967aac9ae46d5036fb3b6ddf9f | /parasol-common/src/main/java/com/parasol/common/utils/encoder/CEFormatException.java | e82cbb935b2e7749be09be4d07bda0813571dbae | [] | no_license | aliang5025/wutong | c48cc29e8aa77ef88a22bd7847a5b5572a4c1d6b | abecaed859fffc7bfdb3a1bac0d99742c605d97b | refs/heads/master | 2020-02-26T15:14:48.882470 | 2018-10-19T07:27:46 | 2018-10-19T07:27:46 | 83,625,239 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 192 | java | package com.parasol.common.utils.encoder;
import java.io.IOException;
public class CEFormatException extends IOException
{
public CEFormatException(String s)
{
super(s);
}
}
| [
"[email protected]"
] | |
ac7c7680839a851c1194a789877ea919e7f05069 | 306f3da1daafb8feb19c03352745db090772fdb5 | /equipment-api/src/main/java/com/example/equipmentapi/controller/CategoryController.java | 94a011f98da43a95833691bf29262274d6d2f9a9 | [] | no_license | tefedrb/equipped | aa8e476c10ba11faeddd6b4be035291fe2dc9d2a | 8169973970bb68b8c1c1f7d87ba14b6cf0910745 | refs/heads/master | 2023-05-11T20:03:32.945922 | 2021-06-03T19:35:32 | 2021-06-03T19:35:32 | 220,674,961 | 0 | 0 | null | 2023-05-07T06:00:10 | 2019-11-09T17:04:16 | JavaScript | UTF-8 | Java | false | false | 782 | java | package com.example.equipmentapi.controller;
import com.example.equipmentapi.models.Category;
import com.example.equipmentapi.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@GetMapping("/list")
public Iterable<Category> listCategories(){
return categoryService.listCategories();
}
}
| [
"[email protected]"
] | |
8e2112f36005a843a9fe2fb5e7d2d16b6e10b948 | 978a0cab2ead179c032d54c603c601bbf0834a07 | /src/mygame/utils/SimpleEnemy.java | f056dc086e8b93772bbb381b80ef9e69ad481cb7 | [] | no_license | vik24rus/JMonkeyShooter | 55c1057d90247eddfbaedbb3ea075cf281c3a41e | ff3a633ad4e0161957f8bcd6318c9f83442f4ec1 | refs/heads/master | 2020-03-27T09:01:26.329227 | 2018-08-30T14:30:08 | 2018-08-30T14:30:08 | 146,307,519 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,456 | java | /*
* 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 mygame.utils;
import com.jme3.app.SimpleApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.math.Vector3f;
import com.jme3.scene.Spatial;
/**
*
* @author vik24rus
*/
public class SimpleEnemy {
Spatial objectSimpleEnemy;
SimpleApplication app;
RigidBodyControl phySimpleEnemy;
BulletAppState bulletApp;
public SimpleEnemy(SimpleApplication app , BulletAppState bulletApp){
this.app = app;
this.bulletApp= bulletApp;
objectSimpleEnemy = app.getAssetManager().loadModel("Models/cubic/cubic.j3o");
objectSimpleEnemy.setLocalTranslation(new Vector3f(3,5,1));
addPhysics();
}
private void addPhysics(){
phySimpleEnemy = new RigidBodyControl( 1.0f );
objectSimpleEnemy.addControl(phySimpleEnemy);
phySimpleEnemy.setPhysicsSpace(bulletApp.getPhysicsSpace());
}
public Spatial getObjectSimpleEnemy(){
return objectSimpleEnemy;
}
private void delEnemy(){ //TODO при удалении нужно RootNode().detachChild + удалить все остальное (control+physic)
}
}
| [
"[email protected]"
] | |
b3a2fceeebe610161825ab5eb838533b4693b33e | bb3039d0e12b25a309cf22ae991ce4520f9a1b53 | /SpringEx03/src/main/java/co/hw/spex/main/common/LoginFilter.java | 1e3a7a67e974183bb9d8bac29f2041841baf4c9d | [] | no_license | dhfl1207/Spring | 3512c655056130a3b14de1ebb686ede5bff3fb7b | 20477b3d5f86bdf156a867fa46a4442557aac747 | refs/heads/main | 2023-02-24T09:11:15.808043 | 2021-02-01T05:09:50 | 2021-02-01T05:09:50 | 326,592,613 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,240 | java | package co.hw.spex.main.common;
import java.io.IOException;
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.annotation.WebFilter;
/**
* Servlet Filter implementation class LoginFilter
*/
//@WebFilter("/*")
public class LoginFilter implements Filter {
/**
* Default constructor.
*/
public LoginFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// place your code here
System.out.println("서블릿 실행 전");
// pass the request along the filter chain
chain.doFilter(request, response);
System.out.println("서블릿 실행 후");
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
| [
"[email protected]"
] | |
1aaa9041ff0682535b35e12444324a05408d77fa | 74d93c525437ab077d83a4f8ac0763e05abbe8c4 | /src/main/java/sample/spring/chapter09/aop/AopService.java | be034f8bdc79948fd4518219e1e77a18b9abc475 | [] | no_license | astraltear/spring4Ex | b398eb1ab2056360b6e13d768129c4b38647d025 | 32d18ad1c3e31ec054f02fa70add4300ed438918 | refs/heads/master | 2021-01-17T06:46:40.007357 | 2018-06-25T06:53:05 | 2018-06-25T06:53:05 | 46,019,118 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 507 | java | package sample.spring.chapter09.aop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service("AopService")
public class AopService {
private static Logger logger = LoggerFactory.getLogger(AopService.class);
public void methodCallOne(String title, int count) {
logger.info("methodCallOne !!");
}
public void methodCallTwo(MockDTO dto) {
logger.info("methodCallTwo !!");
}
public int returnMethodCallThree() {
return 999;
}
}
| [
"[email protected]"
] | |
c036e497e5fb004b53444623d9a86450ad0664a9 | a58ebea234ec919b60db9f2c289e9c445ace8f2d | /src/com/vish/pattern/abstrct/factory/Shapefactory.java | 5d6f1295f253619f56ccfd6292c16828589b9750 | [] | no_license | STDevTutos/Design-Patterns | a0db5232560519d7f5894d76b7bf2d767e984c76 | dde4129519b5d5deee8facfd8edc326c74101acf | refs/heads/master | 2021-09-28T03:36:38.689384 | 2018-11-14T05:15:28 | 2018-11-14T05:15:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 551 | java | package com.vish.pattern.abstrct.factory;
public class Shapefactory extends AbstractFactory {
@Override
Color getColor(String color) {
// TODO Auto-generated method stub
return null;
}
@Override
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
| [
"[email protected]"
] | |
9f32d50d7ba902a897b4a891d1887538d7a64cbc | fa93c9be2923e697fb8a2066f8fb65c7718cdec7 | /sources/com/avito/android/select/new_metro/adapter/gap/MetroListGapItemPresenter.java | d92fcfc80003eca0a8f48310c9ae4349c3a6dfba | [] | no_license | Auch-Auch/avito_source | b6c9f4b0e5c977b36d5fbc88c52f23ff908b7f8b | 76fdcc5b7e036c57ecc193e790b0582481768cdc | refs/heads/master | 2023-05-06T01:32:43.014668 | 2021-05-25T10:19:22 | 2021-05-25T10:19:22 | 370,650,685 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,750 | java | package com.avito.android.select.new_metro.adapter.gap;
import com.avito.konveyor.blueprint.ItemPresenter;
import com.vk.sdk.api.VKApiConst;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
@Metadata(bv = {1, 0, 3}, d1 = {"\u0000\"\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\b\n\u0000\n\u0002\u0010\u0002\n\u0002\b\u0005\u0018\u00002\u000e\u0012\u0004\u0012\u00020\u0002\u0012\u0004\u0012\u00020\u00030\u0001B\t\b\u0007¢\u0006\u0004\b\u000b\u0010\fJ'\u0010\t\u001a\u00020\b2\u0006\u0010\u0004\u001a\u00020\u00022\u0006\u0010\u0005\u001a\u00020\u00032\u0006\u0010\u0007\u001a\u00020\u0006H\u0016¢\u0006\u0004\b\t\u0010\n¨\u0006\r"}, d2 = {"Lcom/avito/android/select/new_metro/adapter/gap/MetroListGapItemPresenter;", "Lcom/avito/konveyor/blueprint/ItemPresenter;", "Lcom/avito/android/select/new_metro/adapter/gap/MetroListGapItemView;", "Lcom/avito/android/select/new_metro/adapter/gap/MetroListGapItem;", "view", "item", "", VKApiConst.POSITION, "", "bindView", "(Lcom/avito/android/select/new_metro/adapter/gap/MetroListGapItemView;Lcom/avito/android/select/new_metro/adapter/gap/MetroListGapItem;I)V", "<init>", "()V", "select_release"}, k = 1, mv = {1, 4, 2})
public final class MetroListGapItemPresenter implements ItemPresenter<MetroListGapItemView, MetroListGapItem> {
public void bindView(@NotNull MetroListGapItemView metroListGapItemView, @NotNull MetroListGapItem metroListGapItem, int i) {
Intrinsics.checkNotNullParameter(metroListGapItemView, "view");
Intrinsics.checkNotNullParameter(metroListGapItem, "item");
metroListGapItemView.setGapDimen(metroListGapItem.getGap());
}
}
| [
"[email protected]"
] | |
df4ca0302f628daed98c9ee417a2ab495b0baf0a | ee58ca4913e2e00c29d51e0cab6af4cfff39c810 | /src/main/java/com/duanxi/interview/HuaWei/interview/one/one/Main.java | a997f6f07a9fff41395877db6bddd52877828bee | [] | no_license | Aaron-cdx/swordoffer | 1252a237d8368bf9762f664138f8fbc7423d483b | 03908452c083e5163472c5a158321592da5ec46c | refs/heads/master | 2021-07-24T18:03:28.858169 | 2020-09-24T12:55:30 | 2020-09-24T12:55:30 | 225,360,713 | 1 | 0 | null | 2020-10-13T17:54:25 | 2019-12-02T11:37:18 | Java | UTF-8 | Java | false | false | 971 | java | package com.duanxi.interview.HuaWei.interview.one.one;
import java.util.*;
/**
* @Author: caoduanxi
* @Date: 2020/9/8
* 华为面试编程题
* <p>
* 题目:
* n个数,1 2 3 4 5,求k个数的所有组合
* 1 2 1 3 1 4 1 5
* 2 3
*/
public class Main {
private List<List<Integer>> lists = new ArrayList<>();
public static void main(String[] args) {
Main main = new Main();
int[] nums = new int[]{1,2,3,4,5};
main.getAll(nums,3,new ArrayList<Integer>(),0);
System.out.println(main.lists);
System.out.println(main.lists.size());
}
public void getAll(int[] nums, int k, List<Integer> list, int index) {
if (list.size() == k) {
lists.add(new ArrayList<>(list));
return;
}
for (int i = index; i < nums.length; i++) {
list.add(nums[i]);
getAll(nums, k, list, i + 1);
list.remove(list.size() - 1);
}
}
}
| [
"[email protected]"
] | |
791cc231d448953d75db53486ba8b900ded9bee8 | 64716f7f4c50b5eed1354000aca6300433f64f29 | /app/src/main/java/com/lx/learngitprojectdemo/NanoHTTPD.java | 9755a888c91af6c896774e34b6c2f6bde55cdf2f | [] | no_license | liuqi-91/ComplexNanoHTTD | e6b92a0cbca7c8001fc5eb756aa563c3621b1854 | c97c4d8507a9aeff37425e7ab18d32580b0fc484 | refs/heads/master | 2020-12-01T13:15:27.992800 | 2019-12-28T17:01:57 | 2019-12-28T17:01:57 | 230,636,876 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 92,040 | java | package com.lx.learngitprojectdemo;
/*
* #%L
* NanoHttpd-Core
* %%
* Copyright (C) 2012 - 2015 nanohttpd
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the nanohttpd nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import android.util.Log;
import com.lx.learngitprojectdemo.NanoHTTPD.Response.IStatus;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import static com.lx.learngitprojectdemo.MainActivity.TAG;
//import java.io.Closeable;
/**
* A simple, tiny, nicely embeddable HTTP server in Java
* <p/>
* <p/>
* NanoHTTPD
* <p>
* Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen,
* 2010 by Konstantinos Togias
* </p>
* <p/>
* <p/>
* <b>Features + limitations: </b>
* <ul>
* <p/>
* <li>Only one Java file</li>
* <li>Java 5 compatible</li>
* <li>Released as open source, Modified BSD licence</li>
* <li>No fixed config files, logging, authorization etc. (Implement yourself if
* you need them.)</li>
* <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT
* support in 1.25)</li>
* <li>Supports both dynamic content and file serving</li>
* <li>Supports file upload (since version 1.2, 2010)</li>
* <li>Supports partial content (streaming)</li>
* <li>Supports ETags</li>
* <li>Never caches anything</li>
* <li>Doesn't limit bandwidth, request time or simultaneous connections</li>
* <li>Default code serves files and shows all HTTP parameters and headers</li>
* <li>File server supports directory listing, index.html and index.htm</li>
* <li>File server supports partial content (streaming)</li>
* <li>File server supports ETags</li>
* <li>File server does the 301 redirection trick for directories without '/'</li>
* <li>File server supports simple skipping for files (continue download)</li>
* <li>File server serves also very long files without memory overhead</li>
* <li>Contains a built-in list of most common MIME types</li>
* <li>All header names are converted to lower case so they don't vary between
* browsers/clients</li>
* <p/>
* </ul>
* <p/>
* <p/>
* <b>How to use: </b>
* <ul>
* <p/>
* <li>Subclass and implement serve() and embed to your own program</li>
* <p/>
* </ul>
* <p/>
* See the separate "LICENSE.md" file for the distribution license (Modified BSD
* licence)
*/
public abstract class NanoHTTPD {
/**
* Pluggable strategy for asynchronously executing requests.
*/
public interface AsyncRunner {
void closeAll();
void closed(NanoHTTPD.ClientHandler clientHandler);
void exec(NanoHTTPD.ClientHandler code);
}
/**
* The runnable that will be used for every new client connection.
*/
public class ClientHandler implements Runnable {
private final InputStream inputStream;
private final Socket acceptSocket;
public ClientHandler(InputStream inputStream, Socket acceptSocket) {
this.inputStream = inputStream;
this.acceptSocket = acceptSocket;
}
public void close() {
safeClose(this.inputStream);
safeClose(this.acceptSocket);
}
@Override
public void run() {
OutputStream outputStream = null;
try {
outputStream = this.acceptSocket.getOutputStream();
NanoHTTPD.TempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create();
NanoHTTPD.HTTPSession session = new NanoHTTPD.HTTPSession(tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress());
while (!this.acceptSocket.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client,
// we throw our own SocketException
// to break the "keep alive" loop above. If
// the exception was anything other
// than the expected SocketException OR a
// SocketTimeoutException, print the
// stacktrace
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) {
NanoHTTPD.LOG.log(Level.SEVERE, "Communication with the client broken, or an bug in the handler code", e);
}
} finally {
safeClose(outputStream);
safeClose(this.inputStream);
safeClose(this.acceptSocket);
NanoHTTPD.this.asyncRunner.closed(this);
}
}
}
public static class Cookie {
public static String getHTTPTime(int days) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.add(Calendar.DAY_OF_MONTH, days);
return dateFormat.format(calendar.getTime());
}
private final String n, v, e;
public Cookie(String name, String value) {
this(name, value, 30);
}
public Cookie(String name, String value, int numDays) {
this.n = name;
this.v = value;
this.e = getHTTPTime(numDays);
}
public Cookie(String name, String value, String expires) {
this.n = name;
this.v = value;
this.e = expires;
}
public String getHTTPHeader() {
String fmt = "%s=%s; expires=%s";
return String.format(fmt, this.n, this.v, this.e);
}
}
/**
* Provides rudimentary support for cookies. Doesn't support 'path',
* 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported
* features.
*
* @author LordFokas
*/
public class CookieHandler implements Iterable<String> {
private final HashMap<String, String> cookies = new HashMap<String, String>();
private final ArrayList<NanoHTTPD.Cookie> queue = new ArrayList<NanoHTTPD.Cookie>();
public CookieHandler(Map<String, String> httpHeaders) {
String raw = httpHeaders.get("cookie");
if (raw != null) {
String[] tokens = raw.split(";");
for (String token : tokens) {
String[] data = token.trim().split("=");
if (data.length == 2) {
this.cookies.put(data[0], data[1]);
}
}
}
}
/**
* Set a cookie with an expiration date from a month ago, effectively
* deleting it on the client side.
*
* @param name
* The cookie name.
*/
public void delete(String name) {
set(name, "-delete-", -30);
}
@Override
public Iterator<String> iterator() {
return this.cookies.keySet().iterator();
}
/**
* Read a cookie from the HTTP Headers.
*
* @param name
* The cookie's name.
* @return The cookie's value if it exists, null otherwise.
*/
public String read(String name) {
return this.cookies.get(name);
}
public void set(NanoHTTPD.Cookie cookie) {
this.queue.add(cookie);
}
/**
* Sets a cookie.
*
* @param name
* The cookie's name.
* @param value
* The cookie's value.
* @param expires
* How many days until the cookie expires.
*/
public void set(String name, String value, int expires) {
this.queue.add(new NanoHTTPD.Cookie(name, value, NanoHTTPD.Cookie.getHTTPTime(expires)));
}
/**
* Internally used by the webserver to add all queued cookies into the
* Response's HTTP Headers.
*
* @param response
* The Response object to which headers the queued cookies
* will be added.
*/
public void unloadQueue(NanoHTTPD.Response response) {
for (NanoHTTPD.Cookie cookie : this.queue) {
response.addHeader("Set-Cookie", cookie.getHTTPHeader());
}
}
}
/**
* Default threading strategy for NanoHTTPD.
* <p/>
* <p>
* By default, the server spawns a new Thread for every incoming request.
* These are set to <i>daemon</i> status, and named according to the request
* number. The name is useful when profiling the application.
* </p>
*/
public static class DefaultAsyncRunner implements NanoHTTPD.AsyncRunner {
private long requestCount;
private final List<NanoHTTPD.ClientHandler> running = Collections.synchronizedList(new ArrayList<NanoHTTPD.ClientHandler>());
/**
* @return a list with currently running clients.
*/
public List<NanoHTTPD.ClientHandler> getRunning() {
return running;
}
@Override
public void closeAll() {
// copy of the list for concurrency
for (NanoHTTPD.ClientHandler clientHandler : new ArrayList<NanoHTTPD.ClientHandler>(this.running)) {
clientHandler.close();
}
}
@Override
public void closed(NanoHTTPD.ClientHandler clientHandler) {
this.running.remove(clientHandler);
}
@Override
public void exec(NanoHTTPD.ClientHandler clientHandler) {
++this.requestCount;
Thread t = new Thread(clientHandler);
t.setDaemon(true);
t.setName("NanoHttpd Request Processor (#" + this.requestCount + ")");
this.running.add(clientHandler);
t.start();
}
}
/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p>
* By default, files are created by <code>File.createTempFile()</code> in
* the directory specified.
* </p>
*/
public static class DefaultTempFile implements NanoHTTPD.TempFile {
private final File file;
private final OutputStream fstream;
public DefaultTempFile(File tempdir) throws IOException {
this.file = File.createTempFile("NanoHTTPD-", "", tempdir);
this.fstream = new FileOutputStream(this.file);
}
@Override
public void delete() throws Exception {
safeClose(this.fstream);
if (!this.file.delete()) {
throw new Exception("could not delete temporary file: " + this.file.getAbsolutePath());
}
}
@Override
public String getName() {
return this.file.getAbsolutePath();
}
@Override
public OutputStream open() throws Exception {
return this.fstream;
}
}
/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p>
* This class stores its files in the standard location (that is, wherever
* <code>java.io.tmpdir</code> points to). Files are added to an internal
* list, and deleted when no longer needed (that is, when
* <code>clear()</code> is invoked at the end of processing a request).
* </p>
*/
public static class DefaultTempFileManager implements NanoHTTPD.TempFileManager {
private final File tmpdir;
private final List<NanoHTTPD.TempFile> tempFiles;
public DefaultTempFileManager() {
this.tmpdir = new File(System.getProperty("java.io.tmpdir"));
if (!tmpdir.exists()) {
tmpdir.mkdirs();
}
this.tempFiles = new ArrayList<NanoHTTPD.TempFile>();
}
@Override
public void clear() {
for (NanoHTTPD.TempFile file : this.tempFiles) {
try {
file.delete();
} catch (Exception ignored) {
NanoHTTPD.LOG.log(Level.WARNING, "could not delete file ", ignored);
}
}
this.tempFiles.clear();
}
@Override
public NanoHTTPD.TempFile createTempFile(String filename_hint) throws Exception {
NanoHTTPD.DefaultTempFile tempFile = new NanoHTTPD.DefaultTempFile(this.tmpdir);
this.tempFiles.add(tempFile);
return tempFile;
}
}
/**
* Default strategy for creating and cleaning up temporary files.
*/
private class DefaultTempFileManagerFactory implements NanoHTTPD.TempFileManagerFactory {
@Override
public NanoHTTPD.TempFileManager create() {
return new NanoHTTPD.DefaultTempFileManager();
}
}
/**
* Creates a normal ServerSocket for TCP connections
*/
public static class DefaultServerSocketFactory implements NanoHTTPD.ServerSocketFactory {
@Override
public ServerSocket create() throws IOException {
return new ServerSocket();
}
}
/**
* Creates a new SSLServerSocket
*/
public static class SecureServerSocketFactory implements NanoHTTPD.ServerSocketFactory {
private SSLServerSocketFactory sslServerSocketFactory;
private String[] sslProtocols;
public SecureServerSocketFactory(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) {
this.sslServerSocketFactory = sslServerSocketFactory;
this.sslProtocols = sslProtocols;
}
@Override
public ServerSocket create() throws IOException {
SSLServerSocket ss = null;
ss = (SSLServerSocket) this.sslServerSocketFactory.createServerSocket();
if (this.sslProtocols != null) {
ss.setEnabledProtocols(this.sslProtocols);
} else {
ss.setEnabledProtocols(ss.getSupportedProtocols());
}
ss.setUseClientMode(false);
ss.setWantClientAuth(false);
ss.setNeedClientAuth(false);
return ss;
}
}
private static final String CONTENT_DISPOSITION_REGEX = "([ |\t]*Content-Disposition[ |\t]*:)(.*)";
private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(CONTENT_DISPOSITION_REGEX, Pattern.CASE_INSENSITIVE);
private static final String CONTENT_TYPE_REGEX = "([ |\t]*content-type[ |\t]*:)(.*)";
private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile(CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE);
private static final String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = "[ |\t]*([a-zA-Z]*)[ |\t]*=[ |\t]*['|\"]([^\"^']*)['|\"]";
private static final Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern.compile(CONTENT_DISPOSITION_ATTRIBUTE_REGEX);
protected static class ContentType {
private static final String ASCII_ENCODING = "US-ASCII";
private static final String MULTIPART_FORM_DATA_HEADER = "multipart/form-data";
private static final String CONTENT_REGEX = "[ |\t]*([^/^ ^;^,]+/[^ ^;^,]+)";
private static final Pattern MIME_PATTERN = Pattern.compile(CONTENT_REGEX, Pattern.CASE_INSENSITIVE);
private static final String CHARSET_REGEX = "[ |\t]*(charset)[ |\t]*=[ |\t]*['|\"]?([^\"^'^;^,]*)['|\"]?";
private static final Pattern CHARSET_PATTERN = Pattern.compile(CHARSET_REGEX, Pattern.CASE_INSENSITIVE);
private static final String BOUNDARY_REGEX = "[ |\t]*(boundary)[ |\t]*=[ |\t]*['|\"]?([^\"^'^;^,]*)['|\"]?";
private static final Pattern BOUNDARY_PATTERN = Pattern.compile(BOUNDARY_REGEX, Pattern.CASE_INSENSITIVE);
private final String contentTypeHeader;
private final String contentType;
private final String encoding;
private final String boundary;
public ContentType(String contentTypeHeader) {
this.contentTypeHeader = contentTypeHeader;
if (contentTypeHeader != null) {
contentType = getDetailFromContentHeader(contentTypeHeader, MIME_PATTERN, "", 1);
encoding = getDetailFromContentHeader(contentTypeHeader, CHARSET_PATTERN, null, 2);
} else {
contentType = "";
encoding = "UTF-8";
}
if (MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType)) {
boundary = getDetailFromContentHeader(contentTypeHeader, BOUNDARY_PATTERN, null, 2);
} else {
boundary = null;
}
}
private String getDetailFromContentHeader(String contentTypeHeader, Pattern pattern, String defaultValue, int group) {
Matcher matcher = pattern.matcher(contentTypeHeader);
return matcher.find() ? matcher.group(group) : defaultValue;
}
public String getContentTypeHeader() {
return contentTypeHeader;
}
public String getContentType() {
return contentType;
}
public String getEncoding() {
return encoding == null ? ASCII_ENCODING : encoding;
}
public String getBoundary() {
return boundary;
}
public boolean isMultipart() {
return MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType);
}
public NanoHTTPD.ContentType tryUTF8() {
if (encoding == null) {
return new NanoHTTPD.ContentType(this.contentTypeHeader + "; charset=UTF-8");
}
return this;
}
}
protected class HTTPSession implements NanoHTTPD.IHTTPSession {
private static final int REQUEST_BUFFER_LEN = 512;
private static final int MEMORY_STORE_LIMIT = 1024;
public static final int BUFSIZE = 8192;
public static final int MAX_HEADER_SIZE = 1024;
private final NanoHTTPD.TempFileManager tempFileManager;
private final OutputStream outputStream;
private final BufferedInputStream inputStream;
private int splitbyte;
private int rlen;
private String uri;
private NanoHTTPD.Method method;
private Map<String, List<String>> parms;
private Map<String, String> headers;
private NanoHTTPD.CookieHandler cookies;
private String queryParameterString;
private String remoteIp;
private String remoteHostname;
private String protocolVersion;
public HTTPSession(NanoHTTPD.TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
this.tempFileManager = tempFileManager;
this.inputStream = new BufferedInputStream(inputStream, NanoHTTPD.HTTPSession.BUFSIZE);
this.outputStream = outputStream;
}
public HTTPSession(NanoHTTPD.TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
this.tempFileManager = tempFileManager;
this.inputStream = new BufferedInputStream(inputStream, NanoHTTPD.HTTPSession.BUFSIZE);
this.outputStream = outputStream;
this.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
this.remoteHostname = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "localhost" : inetAddress.getHostName().toString();
this.headers = new HashMap<String, String>();
}
/**
* Decodes the sent headers and loads the data into Key/value pairs
*/
private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, List<String>> parms, Map<String, String> headers) throws NanoHTTPD.ResponseException {
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) {
return;
}
StringTokenizer st = new StringTokenizer(inLine);
if (!st.hasMoreTokens()) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
}
pre.put("method", st.nextToken());
if (!st.hasMoreTokens()) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
}
String uri = st.nextToken();
// Decode parameters from the URI
int qmi = uri.indexOf('?');
if (qmi >= 0) {
decodeParms(uri.substring(qmi + 1), parms);
uri = decodePercent(uri.substring(0, qmi));
} else {
uri = decodePercent(uri);
}
// If there's another token, its protocol version,
// followed by HTTP headers.
// NOTE: this now forces header names lower case since they are
// case insensitive and vary by client.
if (st.hasMoreTokens()) {
protocolVersion = st.nextToken();
} else {
protocolVersion = "HTTP/1.1";
NanoHTTPD.LOG.log(Level.FINE, "no protocol version specified, strange. Assuming HTTP/1.1.");
}
String line = in.readLine();
while (line != null && !line.trim().isEmpty()) {
int p = line.indexOf(':');
if (p >= 0) {
headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
}
line = in.readLine();
}
pre.put("uri", uri);
} catch (IOException ioe) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
/**
* Decodes the Multipart Body data and put it into Key/Value pairs.
*/
private void decodeMultipartFormData(NanoHTTPD.ContentType contentType, ByteBuffer fbuf, Map<String, List<String>> parms, Map<String, String> files) throws NanoHTTPD.ResponseException {
int pcount = 0;
try {
int[] boundaryIdxs = getBoundaryPositions(fbuf, contentType.getBoundary().getBytes());
if (boundaryIdxs.length < 2) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings.");
}
byte[] partHeaderBuff = new byte[MAX_HEADER_SIZE];
for (int boundaryIdx = 0; boundaryIdx < boundaryIdxs.length - 1; boundaryIdx++) {
fbuf.position(boundaryIdxs[boundaryIdx]);
int len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE;
fbuf.get(partHeaderBuff, 0, len);
BufferedReader in =
new BufferedReader(new InputStreamReader(new ByteArrayInputStream(partHeaderBuff, 0, len), Charset.forName(contentType.getEncoding())), len);
int headerLines = 0;
// First line is boundary string
String mpline = in.readLine();
headerLines++;
if (mpline == null || !mpline.contains(contentType.getBoundary())) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary.");
}
String partName = null, fileName = null, partContentType = null;
// Parse the reset of the header lines
mpline = in.readLine();
headerLines++;
while (mpline != null && mpline.trim().length() > 0) {
Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(mpline);
if (matcher.matches()) {
String attributeString = matcher.group(2);
matcher = CONTENT_DISPOSITION_ATTRIBUTE_PATTERN.matcher(attributeString);
while (matcher.find()) {
String key = matcher.group(1);
if ("name".equalsIgnoreCase(key)) {
partName = matcher.group(2);
} else if ("filename".equalsIgnoreCase(key)) {
fileName = matcher.group(2);
// add these two line to support multiple
// files uploaded using the same field Id
if (!fileName.isEmpty()) {
if (pcount > 0)
partName = partName + String.valueOf(pcount++);
else
pcount++;
}
}
}
}
matcher = CONTENT_TYPE_PATTERN.matcher(mpline);
if (matcher.matches()) {
partContentType = matcher.group(2).trim();
}
mpline = in.readLine();
headerLines++;
}
int partHeaderLength = 0;
while (headerLines-- > 0) {
partHeaderLength = scipOverNewLine(partHeaderBuff, partHeaderLength);
}
// Read the part data
if (partHeaderLength >= len - 4) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.INTERNAL_ERROR, "Multipart header size exceeds MAX_HEADER_SIZE.");
}
int partDataStart = boundaryIdxs[boundaryIdx] + partHeaderLength;
int partDataEnd = boundaryIdxs[boundaryIdx + 1] - 4;
fbuf.position(partDataStart);
List<String> values = parms.get(partName);
if (values == null) {
values = new ArrayList<String>();
parms.put(partName, values);
}
if (partContentType == null) {
// Read the part into a string
byte[] data_bytes = new byte[partDataEnd - partDataStart];
fbuf.get(data_bytes);
values.add(new String(data_bytes, contentType.getEncoding()));
} else {
// Read it into a file
String path = saveTmpFile(fbuf, partDataStart, partDataEnd - partDataStart, fileName);
if (!files.containsKey(partName)) {
files.put(partName, path);
} else {
int count = 2;
while (files.containsKey(partName + count)) {
count++;
}
files.put(partName + count, path);
}
values.add(fileName);
}
}
} catch (NanoHTTPD.ResponseException re) {
throw re;
} catch (Exception e) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.INTERNAL_ERROR, e.toString());
}
}
private int scipOverNewLine(byte[] partHeaderBuff, int index) {
while (partHeaderBuff[index] != '\n') {
index++;
}
return ++index;
}
/**
* Decodes parameters in percent-encoded URI-format ( e.g.
* "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given
* Map.
*/
private void decodeParms(String parms, Map<String, List<String>> p) {
if (parms == null) {
this.queryParameterString = "";
return;
}
this.queryParameterString = parms;
StringTokenizer st = new StringTokenizer(parms, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
String key = null;
String value = null;
if (sep >= 0) {
key = decodePercent(e.substring(0, sep)).trim();
value = decodePercent(e.substring(sep + 1));
} else {
key = decodePercent(e).trim();
value = "";
}
List<String> values = p.get(key);
if (values == null) {
values = new ArrayList<String>();
p.put(key, values);
}
values.add(value);
}
}
@Override
public void execute() throws IOException {
NanoHTTPD.Response r = null;
try {
// Read the first 8192 bytes.
// The full header should fit in here.
// Apache's default header limit is 8KB.
// Do NOT assume that a single read will get the entire header
// at once!
byte[] buf = new byte[NanoHTTPD.HTTPSession.BUFSIZE];
this.splitbyte = 0;
this.rlen = 0;
int read = -1;
this.inputStream.mark(NanoHTTPD.HTTPSession.BUFSIZE);
try {
read = this.inputStream.read(buf, 0, NanoHTTPD.HTTPSession.BUFSIZE);
} catch (SSLException e) {
throw e;
} catch (IOException e) {
safeClose(this.inputStream);
safeClose(this.outputStream);
throw new SocketException("NanoHttpd Shutdown");
}
if (read == -1) {
// socket was been closed
safeClose(this.inputStream);
safeClose(this.outputStream);
throw new SocketException("NanoHttpd Shutdown");
}
while (read > 0) {
this.rlen += read;
this.splitbyte = findHeaderEnd(buf, this.rlen);
if (this.splitbyte > 0) {
break;
}
read = this.inputStream.read(buf, this.rlen, NanoHTTPD.HTTPSession.BUFSIZE - this.rlen);
}
if (this.splitbyte < this.rlen) {
this.inputStream.reset();
this.inputStream.skip(this.splitbyte);
}
this.parms = new HashMap<String, List<String>>();
if (null == this.headers) {
this.headers = new HashMap<String, String>();
} else {
this.headers.clear();
}
// Create a BufferedReader for parsing the header.
BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen)));
// Decode the header into parms and header java properties
Map<String, String> pre = new HashMap<String, String>();
decodeHeader(hin, pre, this.parms, this.headers);
if (null != this.remoteIp) {
this.headers.put("remote-addr", this.remoteIp);
this.headers.put("http-client-ip", this.remoteIp);
}
this.method = NanoHTTPD.Method.lookup(pre.get("method"));
if (this.method == null) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. HTTP verb " + pre.get("method") + " unhandled.");
}
this.uri = pre.get("uri");
this.cookies = new NanoHTTPD.CookieHandler(this.headers);
String connection = this.headers.get("connection");
boolean keepAlive = "HTTP/1.1".equals(protocolVersion) && (connection == null || !connection.matches("(?i).*close.*"));
// Ok, now do the serve()
// TODO: long body_size = getBodySize();
// TODO: long pos_before_serve = this.inputStream.totalRead()
// (requires implementation for totalRead())
r = serve(this);
// TODO: this.inputStream.skip(body_size -
// (this.inputStream.totalRead() - pos_before_serve))
if (r == null) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
} else {
String acceptEncoding = this.headers.get("accept-encoding");
this.cookies.unloadQueue(r);
r.setRequestMethod(this.method);
r.setGzipEncoding(useGzipWhenAccepted(r) && acceptEncoding != null && acceptEncoding.contains("gzip"));
r.setKeepAlive(keepAlive);
r.send(this.outputStream);
}
if (!keepAlive || r.isCloseConnection()) {
throw new SocketException("NanoHttpd Shutdown");
}
} catch (SocketException e) {
// throw it out to close socket object (finalAccept)
throw e;
} catch (SocketTimeoutException ste) {
// treat socket timeouts the same way we treat socket exceptions
// i.e. close the stream & finalAccept object by throwing the
// exception up the call stack.
throw ste;
} catch (SSLException ssle) {
NanoHTTPD.Response resp = newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SSL PROTOCOL FAILURE: " + ssle.getMessage());
resp.send(this.outputStream);
safeClose(this.outputStream);
} catch (IOException ioe) {
NanoHTTPD.Response resp = newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
resp.send(this.outputStream);
safeClose(this.outputStream);
} catch (NanoHTTPD.ResponseException re) {
NanoHTTPD.Response resp = newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
resp.send(this.outputStream);
safeClose(this.outputStream);
} finally {
safeClose(r);
this.tempFileManager.clear();
}
}
/**
* Find byte index separating header from body. It must be the last byte
* of the first two sequential new lines.
*/
private int findHeaderEnd(final byte[] buf, int rlen) {
int splitbyte = 0;
while (splitbyte + 1 < rlen) {
// RFC2616
if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && splitbyte + 3 < rlen && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') {
return splitbyte + 4;
}
// tolerance
if (buf[splitbyte] == '\n' && buf[splitbyte + 1] == '\n') {
return splitbyte + 2;
}
splitbyte++;
}
return 0;
}
/**
* Find the byte positions where multipart boundaries start. This reads
* a large block at a time and uses a temporary buffer to optimize
* (memory mapped) file access.
*/
private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
int[] res = new int[0];
if (b.remaining() < boundary.length) {
return res;
}
int search_window_pos = 0;
byte[] search_window = new byte[4 * 1024 + boundary.length];
int first_fill = (b.remaining() < search_window.length) ? b.remaining() : search_window.length;
b.get(search_window, 0, first_fill);
int new_bytes = first_fill - boundary.length;
do {
// Search the search_window
for (int j = 0; j < new_bytes; j++) {
for (int i = 0; i < boundary.length; i++) {
if (search_window[j + i] != boundary[i])
break;
if (i == boundary.length - 1) {
// Match found, add it to results
int[] new_res = new int[res.length + 1];
System.arraycopy(res, 0, new_res, 0, res.length);
new_res[res.length] = search_window_pos + j;
res = new_res;
}
}
}
search_window_pos += new_bytes;
// Copy the end of the buffer to the start
System.arraycopy(search_window, search_window.length - boundary.length, search_window, 0, boundary.length);
// Refill search_window
new_bytes = search_window.length - boundary.length;
new_bytes = (b.remaining() < new_bytes) ? b.remaining() : new_bytes;
b.get(search_window, boundary.length, new_bytes);
} while (new_bytes > 0);
return res;
}
@Override
public NanoHTTPD.CookieHandler getCookies() {
return this.cookies;
}
@Override
public final Map<String, String> getHeaders() {
return this.headers;
}
@Override
public final InputStream getInputStream() {
return this.inputStream;
}
@Override
public final NanoHTTPD.Method getMethod() {
return this.method;
}
/**
* @deprecated use {@link #getParameters()} instead.
*/
@Override
@Deprecated
public final Map<String, String> getParms() {
Map<String, String> result = new HashMap<String, String>();
for (String key : this.parms.keySet()) {
result.put(key, this.parms.get(key).get(0));
}
return result;
}
@Override
public final Map<String, List<String>> getParameters() {
return this.parms;
}
@Override
public String getQueryParameterString() {
return this.queryParameterString;
}
private RandomAccessFile getTmpBucket() {
try {
NanoHTTPD.TempFile tempFile = this.tempFileManager.createTempFile(null);
return new RandomAccessFile(tempFile.getName(), "rw");
} catch (Exception e) {
throw new Error(e); // we won't recover, so throw an error
}
}
@Override
public final String getUri() {
return this.uri;
}
/**
* Deduce body length in bytes. Either from "content-length" header or
* read bytes.
*/
public long getBodySize() {
if (this.headers.containsKey("content-length")) {
return Long.parseLong(this.headers.get("content-length"));
} else if (this.splitbyte < this.rlen) {
return this.rlen - this.splitbyte;
}
return 0;
}
@Override
public void parseBody(Map<String, String> files) throws IOException, NanoHTTPD.ResponseException {
RandomAccessFile randomAccessFile = null;
try {
long size = getBodySize();
ByteArrayOutputStream baos = null;
DataOutput requestDataOutput = null;
// Store the request in memory or a file, depending on size
if (size < MEMORY_STORE_LIMIT) {
baos = new ByteArrayOutputStream();
requestDataOutput = new DataOutputStream(baos);
} else {
randomAccessFile = getTmpBucket();
requestDataOutput = randomAccessFile;
}
// Read all the body and write it to request_data_output
byte[] buf = new byte[REQUEST_BUFFER_LEN];
while (this.rlen >= 0 && size > 0) {
this.rlen = this.inputStream.read(buf, 0, (int) Math.min(size, REQUEST_BUFFER_LEN));
size -= this.rlen;
if (this.rlen > 0) {
requestDataOutput.write(buf, 0, this.rlen);
}
}
ByteBuffer fbuf = null;
if (baos != null) {
fbuf = ByteBuffer.wrap(baos.toByteArray(), 0, baos.size());
} else {
fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
randomAccessFile.seek(0);
}
// If the method is POST, there may be parameters
// in data section, too, read it:
if (NanoHTTPD.Method.POST.equals(this.method)) {
NanoHTTPD.ContentType contentType = new NanoHTTPD.ContentType(this.headers.get("content-type"));
if (contentType.isMultipart()) {
String boundary = contentType.getBoundary();
if (boundary == null) {
throw new NanoHTTPD.ResponseException(NanoHTTPD.Response.Status.BAD_REQUEST,
"BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
}
decodeMultipartFormData(contentType, fbuf, this.parms, files);
} else {
byte[] postBytes = new byte[fbuf.remaining()];
fbuf.get(postBytes);
String postLine = new String(postBytes, contentType.getEncoding()).trim();
// Handle application/x-www-form-urlencoded
if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType.getContentType())) {
decodeParms(postLine, this.parms);
} else if (postLine.length() != 0) {
// Special case for raw POST data => create a
// special files entry "postData" with raw content
// data
files.put("postData", postLine);
}
}
} else if (NanoHTTPD.Method.PUT.equals(this.method)) {
files.put("content", saveTmpFile(fbuf, 0, fbuf.limit(), null));
}
} finally {
safeClose(randomAccessFile);
}
}
/**
* Retrieves the content of a sent file and saves it to a temporary
* file. The full path to the saved file is returned.
*/
private String saveTmpFile(ByteBuffer b, int offset, int len, String filename_hint) {
String path = "";
if (len > 0) {
FileOutputStream fileOutputStream = null;
try {
NanoHTTPD.TempFile tempFile = this.tempFileManager.createTempFile(filename_hint);
ByteBuffer src = b.duplicate();
fileOutputStream = new FileOutputStream(tempFile.getName());
FileChannel dest = fileOutputStream.getChannel();
src.position(offset).limit(offset + len);
dest.write(src.slice());
path = tempFile.getName();
} catch (Exception e) { // Catch exception if any
throw new Error(e); // we won't recover, so throw an error
} finally {
safeClose(fileOutputStream);
}
}
return path;
}
@Override
public String getRemoteIpAddress() {
return this.remoteIp;
}
@Override
public String getRemoteHostName() {
return this.remoteHostname;
}
}
/**
* Handles one session, i.e. parses the HTTP request and returns the
* response.
*/
public interface IHTTPSession {
void execute() throws IOException;
NanoHTTPD.CookieHandler getCookies();
Map<String, String> getHeaders();
InputStream getInputStream();
NanoHTTPD.Method getMethod();
/**
* This method will only return the first value for a given parameter.
* You will want to use getParameters if you expect multiple values for
* a given key.
*
* @deprecated use {@link #getParameters()} instead.
*/
@Deprecated
Map<String, String> getParms();
Map<String, List<String>> getParameters();
String getQueryParameterString();
/**
* @return the path part of the URL.
*/
String getUri();
/**
* Adds the files in the request body to the files map.
*
* @param files
* map to modify
*/
void parseBody(Map<String, String> files) throws IOException, NanoHTTPD.ResponseException;
/**
* Get the remote ip address of the requester.
*
* @return the IP address.
*/
String getRemoteIpAddress();
/**
* Get the remote hostname of the requester.
*
* @return the hostname.
*/
String getRemoteHostName();
}
/**
* HTTP Request methods, with the ability to decode a <code>String</code>
* back to its enum value.
*/
public enum Method {
GET,
PUT,
POST,
DELETE,
HEAD,
OPTIONS,
TRACE,
CONNECT,
PATCH,
PROPFIND,
PROPPATCH,
MKCOL,
MOVE,
COPY,
LOCK,
UNLOCK;
static NanoHTTPD.Method lookup(String method) {
if (method == null)
return null;
try {
return valueOf(method);
} catch (IllegalArgumentException e) {
// TODO: Log it?
return null;
}
}
}
/**
* HTTP response. Return one of these from serve().
*/
public static class Response implements java.io.Closeable {
public interface IStatus {
String getDescription();
int getRequestStatus();
}
/**
* Some HTTP response status codes
*/
public enum Status implements NanoHTTPD.Response.IStatus {
SWITCH_PROTOCOL(101, "Switching Protocols"),
OK(200, "OK"),
CREATED(201, "Created"),
ACCEPTED(202, "Accepted"),
NO_CONTENT(204, "No Content"),
PARTIAL_CONTENT(206, "Partial Content"),
MULTI_STATUS(207, "Multi-Status"),
REDIRECT(301, "Moved Permanently"),
/**
* Many user agents mishandle 302 in ways that violate the RFC1945
* spec (i.e., redirect a POST to a GET). 303 and 307 were added in
* RFC2616 to address this. You should prefer 303 and 307 unless the
* calling user agent does not support 303 and 307 functionality
*/
@Deprecated
FOUND(302, "Found"),
REDIRECT_SEE_OTHER(303, "See Other"),
NOT_MODIFIED(304, "Not Modified"),
TEMPORARY_REDIRECT(307, "Temporary Redirect"),
BAD_REQUEST(400, "Bad Request"),
UNAUTHORIZED(401, "Unauthorized"),
FORBIDDEN(403, "Forbidden"),
NOT_FOUND(404, "Not Found"),
METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
NOT_ACCEPTABLE(406, "Not Acceptable"),
REQUEST_TIMEOUT(408, "Request Timeout"),
CONFLICT(409, "Conflict"),
GONE(410, "Gone"),
LENGTH_REQUIRED(411, "Length Required"),
PRECONDITION_FAILED(412, "Precondition Failed"),
PAYLOAD_TOO_LARGE(413, "Payload Too Large"),
UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"),
EXPECTATION_FAILED(417, "Expectation Failed"),
TOO_MANY_REQUESTS(429, "Too Many Requests"),
INTERNAL_ERROR(500, "Internal Server Error"),
NOT_IMPLEMENTED(501, "Not Implemented"),
SERVICE_UNAVAILABLE(503, "Service Unavailable"),
UNSUPPORTED_HTTP_VERSION(505, "HTTP Version Not Supported");
private final int requestStatus;
private final String description;
Status(int requestStatus, String description) {
this.requestStatus = requestStatus;
this.description = description;
}
public static NanoHTTPD.Response.Status lookup(int requestStatus) {
for (NanoHTTPD.Response.Status status : NanoHTTPD.Response.Status.values()) {
if (status.getRequestStatus() == requestStatus) {
return status;
}
}
return null;
}
@Override
public String getDescription() {
return "" + this.requestStatus + " " + this.description;
}
@Override
public int getRequestStatus() {
return this.requestStatus;
}
}
/**
* Output stream that will automatically send every write to the wrapped
* OutputStream according to chunked transfer:
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
*/
private static class ChunkedOutputStream extends FilterOutputStream {
public ChunkedOutputStream(OutputStream out) {
super(out);
}
@Override
public void write(int b) throws IOException {
byte[] data = {
(byte) b
};
write(data, 0, 1);
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (len == 0)
return;
out.write(String.format("%x\r\n", len).getBytes());
out.write(b, off, len);
out.write("\r\n".getBytes());
}
public void finish() throws IOException {
out.write("0\r\n\r\n".getBytes());
}
}
/**
* HTTP status code after processing, e.g. "200 OK", Status.OK
*/
private NanoHTTPD.Response.IStatus status;
/**
* MIME type of content, e.g. "text/html"
*/
private String mimeType;
/**
* Data of the response, may be null.
*/
private InputStream data;
private long contentLength;
/**
* Headers for the HTTP response. Use addHeader() to add lines. the
* lowercase map is automatically kept up to date.
*/
@SuppressWarnings("serial")
private final Map<String, String> header = new HashMap<String, String>() {
public String put(String key, String value) {
lowerCaseHeader.put(key == null ? key : key.toLowerCase(), value);
return super.put(key, value);
};
};
/**
* copy of the header map with all the keys lowercase for faster
* searching.
*/
private final Map<String, String> lowerCaseHeader = new HashMap<String, String>();
/**
* The request method that spawned this response.
*/
private NanoHTTPD.Method requestMethod;
/**
* Use chunkedTransfer
*/
private boolean chunkedTransfer;
private boolean encodeAsGzip;
private boolean keepAlive;
private boolean isOptZip;
public boolean isOptZip() {
return isOptZip;
}
public void setOptZip(boolean optZip) {
isOptZip = optZip;
}
private List<String> filesPathList;
/**
* Creates a fixed length response if totalBytes>=0, otherwise chunked.
*/
protected Response(NanoHTTPD.Response.IStatus status, String mimeType, InputStream data, List<String> filesPathList, long totalBytes) {
this.status = status;
this.mimeType = mimeType;
if (filesPathList!=null) {
this.isOptZip = true;
this.filesPathList = filesPathList;
this.data = new ByteArrayInputStream(new byte[0]);
this.contentLength = totalBytes;
} else if (data == null) {
this.data = new ByteArrayInputStream(new byte[0]);
this.contentLength = 0L;
} else {
this.data = data;
this.contentLength = totalBytes;
}
this.chunkedTransfer = this.contentLength < 0;
keepAlive = true;
}
protected Response(NanoHTTPD.Response.IStatus status, String mimeType, InputStream data, long totalBytes) {
this(status, mimeType, data, null, totalBytes);
}
@Override
public void close() throws IOException {
if (this.data != null) {
this.data.close();
}
}
/**
* Adds given line to the header.
*/
public void addHeader(String name, String value) {
this.header.put(name, value);
}
/**
* Indicate to close the connection after the Response has been sent.
*
* @param close {@code true} to hint connection closing, {@code false} to
* let connection be closed by client.
*/
public void closeConnection(boolean close) {
if (close)
this.header.put("connection", "close");
else
this.header.remove("connection");
}
/**
* @return {@code true} if connection is to be closed after this
* Response has been sent.
*/
public boolean isCloseConnection() {
return "close".equals(getHeader("connection"));
}
public InputStream getData() {
return this.data;
}
public String getHeader(String name) {
return this.lowerCaseHeader.get(name.toLowerCase());
}
public String getMimeType() {
return this.mimeType;
}
public NanoHTTPD.Method getRequestMethod() {
return this.requestMethod;
}
public NanoHTTPD.Response.IStatus getStatus() {
return this.status;
}
public void setGzipEncoding(boolean encodeAsGzip) {
this.encodeAsGzip = encodeAsGzip;
}
public void setKeepAlive(boolean useKeepAlive) {
this.keepAlive = useKeepAlive;
}
/**
* Sends given response to the socket.
*/
protected void send(OutputStream outputStream) {
SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
if (this.status == null) {
throw new Error("sendResponse(): Status can't be null.");
}
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new NanoHTTPD.ContentType(this.mimeType).getEncoding())), false);
pw.append("HTTP/1.1 ").append(this.status.getDescription()).append(" \r\n");
if (this.mimeType != null) {
printHeader(pw, "Content-Type", this.mimeType);
}
if (getHeader("date") == null) {
printHeader(pw, "Date", gmtFrmt.format(new Date()));
}
for (Entry<String, String> entry : this.header.entrySet()) {
printHeader(pw, entry.getKey(), entry.getValue());
}
if (getHeader("connection") == null) {
printHeader(pw, "Connection", (this.keepAlive ? "keep-alive" : "close"));
}
if (getHeader("content-length") != null) {
encodeAsGzip = false;
}
if (encodeAsGzip) {
printHeader(pw, "Content-Encoding", "gzip");
setChunkedTransfer(true);
}
long pending = this.data != null ? this.contentLength : 0;
if (this.requestMethod != NanoHTTPD.Method.HEAD && this.chunkedTransfer) {
printHeader(pw, "Transfer-Encoding", "chunked");
} else if (!encodeAsGzip) {
pending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending);
}
pw.append("\r\n");
pw.flush();
sendBodyWithCorrectTransferAndEncoding(outputStream, pending);
outputStream.flush();
safeClose(this.data);
} catch (IOException ioe) {
NanoHTTPD.LOG.log(Level.SEVERE, "Could not send response to the client", ioe);
}
}
@SuppressWarnings("static-method")
protected void printHeader(PrintWriter pw, String key, String value) {
pw.append(key).append(": ").append(value).append("\r\n");
}
protected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, long defaultSize) {
String contentLengthString = getHeader("content-length");
long size = defaultSize;
if (contentLengthString != null) {
try {
size = Long.parseLong(contentLengthString);
} catch (NumberFormatException ex) {
LOG.severe("content-length was no number " + contentLengthString);
}
}
pw.print("Content-Length: " + size + "\r\n");
return size;
}
private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {
if (this.requestMethod != NanoHTTPD.Method.HEAD && this.chunkedTransfer) {
NanoHTTPD.Response.ChunkedOutputStream chunkedOutputStream = new NanoHTTPD.Response.ChunkedOutputStream(outputStream);
sendBodyWithCorrectEncoding(chunkedOutputStream, -1);
chunkedOutputStream.finish();
} else {
sendBodyWithCorrectEncoding(outputStream, pending);
}
}
private void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {
if (encodeAsGzip) {
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
sendBody(gzipOutputStream, -1);
gzipOutputStream.finish();
} else {
sendBody(outputStream, pending);
}
}
/**
* Sends the body to the specified OutputStream. The pending parameter
* limits the maximum amounts of bytes sent unless it is -1, in which
* case everything is sent.
*
* @param outputStream the OutputStream to send data to
* @param pending -1 to send everything, otherwise sets a max limit to the
* number of bytes sent
* @throws IOException if something goes wrong while sending the data.
*/
private void sendBody(OutputStream outputStream, long pending) throws IOException {
if (isOptZip) {
sendOptZip(outputStream);
return;
}
long BUFFER_SIZE = 16 * 1024;
byte[] buff = new byte[(int) BUFFER_SIZE];
boolean sendEverything = pending == -1;
while (pending > 0 || sendEverything) {
long bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE);
int read = this.data.read(buff, 0, (int) bytesToRead);
if (read <= 0) {
break;
}
outputStream.write(buff, 0, read);
if (!sendEverything) {
pending -= read;
}
}
}
public void sendOptZip(OutputStream outputStream) {
int BUFFER_SIZE = 64 * 1024;
final byte[] buff = new byte[BUFFER_SIZE];
try (
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(2*BUFFER_SIZE);
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {
FileInputStream fileInputStream;
ZipEntry zipEntry;
File file;
byte[] bytes = new byte[20*BUFFER_SIZE];
for (String filePath : filesPathList) {
file = new File(filePath);
fileInputStream = new FileInputStream(file);
zipEntry = new ZipEntry(filePath);
zipEntry.setMethod(ZipEntry.STORED);
zipEntry.setSize(file.length());
zipEntry.setCompressedSize(file.length());
zipEntry.setCrc(getCRC32(filePath));
zipOutputStream.putNextEntry(zipEntry);
outputStream.write(byteArrayOutputStream.toByteArray(), 0, byteArrayOutputStream.size());
int len = 0;
long total = 0;
long startTime = System.currentTimeMillis();
Log.i(TAG, "filePath = " + filePath + ", len = " + zipEntry.getSize());
while ((len = fileInputStream.read(bytes, 0, bytes.length)) != -1) {
outputStream.write(bytes, 0, len);
total += len;
}
Log.i(TAG, "filePath = " + filePath + ", total = " + total+", cost time = "+(System.currentTimeMillis() - startTime)+" ms"+", speed = "+(total/(System.currentTimeMillis() - startTime)));
try {
zipEntry.setCrc(0L);
zipEntry.setSize(0L);
zipEntry.setCompressedSize(0L);
zipOutputStream.closeEntry();
byteArrayOutputStream.reset();
} catch (Exception e) {
Log.i(TAG, "closeEntry " + e);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public long getCRC32(String filepath) throws IOException{
InputStream inputStream = new BufferedInputStream(new FileInputStream(filepath));
CRC32 crc = new CRC32();
byte[] bytes = new byte[16*1024];
int cnt;
while ((cnt = inputStream.read(bytes)) != -1) {
crc.update(bytes, 0, cnt);
}
inputStream.close();
return crc.getValue();
}
public void setChunkedTransfer(boolean chunkedTransfer) {
this.chunkedTransfer = chunkedTransfer;
}
public void setData(InputStream data) {
this.data = data;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public void setRequestMethod(NanoHTTPD.Method requestMethod) {
this.requestMethod = requestMethod;
}
public void setStatus(NanoHTTPD.Response.IStatus status) {
this.status = status;
}
}
public static final class ResponseException extends Exception {
private static final long serialVersionUID = 6569838532917408380L;
private final NanoHTTPD.Response.Status status;
public ResponseException(NanoHTTPD.Response.Status status, String message) {
super(message);
this.status = status;
}
public ResponseException(NanoHTTPD.Response.Status status, String message, Exception e) {
super(message, e);
this.status = status;
}
public NanoHTTPD.Response.Status getStatus() {
return this.status;
}
}
/**
* The runnable that will be used for the main listening thread.
*/
public class ServerRunnable implements Runnable {
private final int timeout;
private IOException bindException;
private boolean hasBinded = false;
public ServerRunnable(int timeout) {
this.timeout = timeout;
}
@Override
public void run() {
try {
myServerSocket.bind(hostname != null ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
hasBinded = true;
} catch (IOException e) {
this.bindException = e;
return;
}
do {
try {
final Socket finalAccept = NanoHTTPD.this.myServerSocket.accept();
if (this.timeout > 0) {
finalAccept.setSoTimeout(this.timeout);
}
final InputStream inputStream = finalAccept.getInputStream();
NanoHTTPD.this.asyncRunner.exec(createClientHandler(finalAccept, inputStream));
} catch (IOException e) {
NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e);
}
} while (!NanoHTTPD.this.myServerSocket.isClosed());
}
}
/**
* A temp file.
* <p/>
* <p>
* Temp files are responsible for managing the actual temporary storage and
* cleaning themselves up when no longer needed.
* </p>
*/
public interface TempFile {
public void delete() throws Exception;
public String getName();
public OutputStream open() throws Exception;
}
/**
* Temp file manager.
* <p/>
* <p>
* Temp file managers are created 1-to-1 with incoming requests, to create
* and cleanup temporary files created as a result of handling the request.
* </p>
*/
public interface TempFileManager {
void clear();
public NanoHTTPD.TempFile createTempFile(String filename_hint) throws Exception;
}
/**
* Factory to create temp file managers.
*/
public interface TempFileManagerFactory {
public NanoHTTPD.TempFileManager create();
}
/**
* Factory to create ServerSocketFactories.
*/
public interface ServerSocketFactory {
public ServerSocket create() throws IOException;
}
/**
* Maximum time to wait on Socket.getInputStream().read() (in milliseconds)
* This is required as the Keep-Alive HTTP connections would otherwise block
* the socket reading thread forever (or as long the browser is open).
*/
public static final int SOCKET_READ_TIMEOUT = 5000;
/**
* Common MIME type for dynamic content: plain text
*/
public static final String MIME_PLAINTEXT = "text/plain";
/**
* Common MIME type for dynamic content: html
*/
public static final String MIME_HTML = "text/html";
/**
* Pseudo-Parameter to use to store the actual query string in the
* parameters map for later re-processing.
*/
private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING";
/**
* logger to log to.
*/
private static final Logger LOG = Logger.getLogger(NanoHTTPD.class.getName());
/**
* Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
*/
protected static Map<String, String> MIME_TYPES;
public static Map<String, String> mimeTypes() {
if (MIME_TYPES == null) {
MIME_TYPES = new HashMap<String, String>();
loadMimeTypes(MIME_TYPES, "META-INF/nanohttpd/default-mimetypes.properties");
loadMimeTypes(MIME_TYPES, "META-INF/nanohttpd/mimetypes.properties");
if (MIME_TYPES.isEmpty()) {
LOG.log(Level.WARNING, "no mime types found in the classpath! please provide mimetypes.properties");
}
}
return MIME_TYPES;
}
@SuppressWarnings({
"unchecked",
"rawtypes"
})
private static void loadMimeTypes(Map<String, String> result, String resourceName) {
try {
Enumeration<URL> resources = NanoHTTPD.class.getClassLoader().getResources(resourceName);
while (resources.hasMoreElements()) {
URL url = (URL) resources.nextElement();
Properties properties = new Properties();
InputStream stream = null;
try {
stream = url.openStream();
properties.load(stream);
} catch (IOException e) {
LOG.log(Level.SEVERE, "could not load mimetypes from " + url, e);
} finally {
safeClose(stream);
}
result.putAll((Map) properties);
}
} catch (IOException e) {
LOG.log(Level.INFO, "no mime types available at " + resourceName);
}
};
/**
* Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an
* array of loaded KeyManagers. These objects must properly
* loaded/initialized by the caller.
*/
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
SSLServerSocketFactory res = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(loadedKeyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
res = ctx.getServerSocketFactory();
} catch (Exception e) {
throw new IOException(e.getMessage());
}
return res;
}
/**
* Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
* loaded KeyManagerFactory. These objects must properly loaded/initialized
* by the caller.
*/
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
try {
return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
* certificate and passphrase
*/
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
try {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);
if (keystoreStream == null) {
throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
}
keystore.load(keystoreStream, passphrase);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, passphrase);
return makeSSLSocketFactory(keystore, keyManagerFactory);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* Get MIME type from file name extension, if possible
*
* @param uri
* the string representing a file
* @return the connected mime/type
*/
public static String getMimeTypeForFile(String uri) {
int dot = uri.lastIndexOf('.');
String mime = null;
if (dot >= 0) {
mime = mimeTypes().get(uri.substring(dot + 1).toLowerCase());
}
return mime == null ? "application/octet-stream" : mime;
}
private static final void safeClose(Object closeable) {
try {
if (closeable != null) {
if (closeable instanceof Closeable) {
((Closeable) closeable).close();
} else if (closeable instanceof Socket) {
((Socket) closeable).close();
} else if (closeable instanceof ServerSocket) {
((ServerSocket) closeable).close();
} else {
throw new IllegalArgumentException("Unknown object to close");
}
}
} catch (IOException e) {
NanoHTTPD.LOG.log(Level.SEVERE, "Could not close", e);
}
}
private final String hostname;
private final int myPort;
private volatile ServerSocket myServerSocket;
private NanoHTTPD.ServerSocketFactory serverSocketFactory = new NanoHTTPD.DefaultServerSocketFactory();
private Thread myThread;
/**
* Pluggable strategy for asynchronously executing requests.
*/
protected NanoHTTPD.AsyncRunner asyncRunner;
/**
* Pluggable strategy for creating and cleaning up temporary files.
*/
private NanoHTTPD.TempFileManagerFactory tempFileManagerFactory;
/**
* Constructs an HTTP server on given port.
*/
public NanoHTTPD(int port) {
this(null, port);
}
// -------------------------------------------------------------------------------
// //
//
// Threading Strategy.
//
// -------------------------------------------------------------------------------
// //
/**
* Constructs an HTTP server on given hostname and port.
*/
public NanoHTTPD(String hostname, int port) {
this.hostname = hostname;
this.myPort = port;
setTempFileManagerFactory(new NanoHTTPD.DefaultTempFileManagerFactory());
setAsyncRunner(new NanoHTTPD.DefaultAsyncRunner());
}
/**
* Forcibly closes all connections that are open.
*/
public synchronized void closeAllConnections() {
stop();
}
/**
* create a instance of the client handler, subclasses can return a subclass
* of the ClientHandler.
*
* @param finalAccept
* the socket the cleint is connected to
* @param inputStream
* the input stream
* @return the client handler
*/
protected NanoHTTPD.ClientHandler createClientHandler(final Socket finalAccept, final InputStream inputStream) {
return new NanoHTTPD.ClientHandler(inputStream, finalAccept);
}
/**
* Instantiate the server runnable, can be overwritten by subclasses to
* provide a subclass of the ServerRunnable.
*
* @param timeout
* the socet timeout to use.
* @return the server runnable.
*/
protected NanoHTTPD.ServerRunnable createServerRunnable(final int timeout) {
return new NanoHTTPD.ServerRunnable(timeout);
}
/**
* Decode parameters from a URL, handing the case where a single parameter
* name might have been supplied several times, by return lists of values.
* In general these lists will contain a single element.
*
* @param parms
* original <b>NanoHTTPD</b> parameters values, as passed to the
* <code>serve()</code> method.
* @return a map of <code>String</code> (parameter name) to
* <code>List<String></code> (a list of the values supplied).
*/
protected static Map<String, List<String>> decodeParameters(Map<String, String> parms) {
return decodeParameters(parms.get(NanoHTTPD.QUERY_STRING_PARAMETER));
}
// -------------------------------------------------------------------------------
// //
/**
* Decode parameters from a URL, handing the case where a single parameter
* name might have been supplied several times, by return lists of values.
* In general these lists will contain a single element.
*
* @param queryString
* a query string pulled from the URL.
* @return a map of <code>String</code> (parameter name) to
* <code>List<String></code> (a list of the values supplied).
*/
protected static Map<String, List<String>> decodeParameters(String queryString) {
Map<String, List<String>> parms = new HashMap<String, List<String>>();
if (queryString != null) {
StringTokenizer st = new StringTokenizer(queryString, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
String propertyName = sep >= 0 ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();
if (!parms.containsKey(propertyName)) {
parms.put(propertyName, new ArrayList<String>());
}
String propertyValue = sep >= 0 ? decodePercent(e.substring(sep + 1)) : null;
if (propertyValue != null) {
parms.get(propertyName).add(propertyValue);
}
}
}
return parms;
}
/**
* Decode percent encoded <code>String</code> values.
*
* @param str
* the percent encoded <code>String</code>
* @return expanded form of the input, for example "foo%20bar" becomes
* "foo bar"
*/
protected static String decodePercent(String str) {
String decoded = null;
try {
decoded = URLDecoder.decode(str, "UTF8");
} catch (UnsupportedEncodingException ignored) {
NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored);
}
return decoded;
}
/**
* @return true if the gzip compression should be used if the client
* accespts it. Default this option is on for text content and off
* for everything. Override this for custom semantics.
*/
@SuppressWarnings("static-method")
protected boolean useGzipWhenAccepted(NanoHTTPD.Response r) {
return r.getMimeType() != null && (r.getMimeType().toLowerCase().contains("text/") || r.getMimeType().toLowerCase().contains("/json"));
}
public final int getListeningPort() {
return this.myServerSocket == null ? -1 : this.myServerSocket.getLocalPort();
}
public final boolean isAlive() {
return wasStarted() && !this.myServerSocket.isClosed() && this.myThread.isAlive();
}
public NanoHTTPD.ServerSocketFactory getServerSocketFactory() {
return serverSocketFactory;
}
public void setServerSocketFactory(NanoHTTPD.ServerSocketFactory serverSocketFactory) {
this.serverSocketFactory = serverSocketFactory;
}
public String getHostname() {
return hostname;
}
public NanoHTTPD.TempFileManagerFactory getTempFileManagerFactory() {
return tempFileManagerFactory;
}
/**
* Call before start() to serve over HTTPS instead of HTTP
*/
public void makeSecure(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) {
this.serverSocketFactory = new NanoHTTPD.SecureServerSocketFactory(sslServerSocketFactory, sslProtocols);
}
/**
* Create a response with unknown length (using HTTP 1.1 chunking).
*/
public static NanoHTTPD.Response newChunkedResponse(Response.IStatus status, String mimeType, InputStream data) {
return new NanoHTTPD.Response(status, mimeType, data, -1);
}
public static NanoHTTPD.Response newChunkedZipResponse(Response.IStatus status, String mimeType, List<String> filePathList) {
return new NanoHTTPD.Response(status, mimeType, null, filePathList,-1);
}
/**
* Create a response with known length.
*/
public static NanoHTTPD.Response newFixedLengthResponse(IStatus status, String mimeType, InputStream data, long totalBytes) {
return new NanoHTTPD.Response(status, mimeType, data, totalBytes);
}
/**
* Create a text response with known length.
*/
public static NanoHTTPD.Response newFixedLengthResponse(IStatus status, String mimeType, String txt) {
NanoHTTPD.ContentType contentType = new NanoHTTPD.ContentType(mimeType);
if (txt == null) {
return newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);
} else {
byte[] bytes;
try {
CharsetEncoder newEncoder = Charset.forName(contentType.getEncoding()).newEncoder();
if (!newEncoder.canEncode(txt)) {
contentType = contentType.tryUTF8();
}
bytes = txt.getBytes(contentType.getEncoding());
} catch (UnsupportedEncodingException e) {
NanoHTTPD.LOG.log(Level.SEVERE, "encoding problem, responding nothing", e);
bytes = new byte[0];
}
return newFixedLengthResponse(status, contentType.getContentTypeHeader(), new ByteArrayInputStream(bytes), bytes.length);
}
}
/**
* Create a text response with known length.
*/
public static NanoHTTPD.Response newFixedLengthResponse(String msg) {
return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, msg);
}
/**
* Override this to customize the server.
* <p/>
* <p/>
* (By default, this returns a 404 "Not Found" plain text error response.)
*
* @param session
* The HTTP session
* @return HTTP response, see class Response for details
*/
public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
Map<String, String> files = new HashMap<String, String>();
NanoHTTPD.Method method = session.getMethod();
if (NanoHTTPD.Method.PUT.equals(method) || NanoHTTPD.Method.POST.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
} catch (NanoHTTPD.ResponseException re) {
return newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
}
}
Map<String, String> parms = session.getParms();
parms.put(NanoHTTPD.QUERY_STRING_PARAMETER, session.getQueryParameterString());
return serve(session.getUri(), method, session.getHeaders(), parms, files);
}
/**
* Override this to customize the server.
* <p/>
* <p/>
* (By default, this returns a 404 "Not Found" plain text error response.)
*
* @param uri
* Percent-decoded URI without parameters, for example
* "/index.cgi"
* @param method
* "GET", "POST" etc.
* @param parms
* Parsed, percent decoded parameters from URI and, in case of
* POST, data.
* @param headers
* Header entries, percent decoded
* @return HTTP response, see class Response for details
*/
@Deprecated
public NanoHTTPD.Response serve(String uri, NanoHTTPD.Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {
return newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Not Found");
}
/**
* Pluggable strategy for asynchronously executing requests.
*
* @param asyncRunner
* new strategy for handling threads.
*/
public void setAsyncRunner(NanoHTTPD.AsyncRunner asyncRunner) {
this.asyncRunner = asyncRunner;
}
/**
* Pluggable strategy for creating and cleaning up temporary files.
*
* @param tempFileManagerFactory
* new strategy for handling temp files.
*/
public void setTempFileManagerFactory(NanoHTTPD.TempFileManagerFactory tempFileManagerFactory) {
this.tempFileManagerFactory = tempFileManagerFactory;
}
/**
* Start the server.
*
* @throws IOException
* if the socket is in use.
*/
public void start() throws IOException {
start(NanoHTTPD.SOCKET_READ_TIMEOUT);
}
/**
* Starts the server (in setDaemon(true) mode).
*/
public void start(final int timeout) throws IOException {
start(timeout, true);
}
/**
* Start the server.
*
* @param timeout
* timeout to use for socket connections.
* @param daemon
* start the thread daemon or not.
* @throws IOException
* if the socket is in use.
*/
public void start(final int timeout, boolean daemon) throws IOException {
this.myServerSocket = this.getServerSocketFactory().create();
this.myServerSocket.setReuseAddress(true);
NanoHTTPD.ServerRunnable serverRunnable = createServerRunnable(timeout);
this.myThread = new Thread(serverRunnable);
this.myThread.setDaemon(daemon);
this.myThread.setName("NanoHttpd Main Listener");
this.myThread.start();
while (!serverRunnable.hasBinded && serverRunnable.bindException == null) {
try {
Thread.sleep(10L);
} catch (Throwable e) {
// on android this may not be allowed, that's why we
// catch throwable the wait should be very short because we are
// just waiting for the bind of the socket
}
}
if (serverRunnable.bindException != null) {
throw serverRunnable.bindException;
}
}
/**
* Stop the server.
*/
public void stop() {
try {
safeClose(this.myServerSocket);
this.asyncRunner.closeAll();
if (this.myThread != null) {
this.myThread.join();
}
} catch (Exception e) {
NanoHTTPD.LOG.log(Level.SEVERE, "Could not stop all connections", e);
}
}
public final boolean wasStarted() {
return this.myServerSocket != null && this.myThread != null;
}
}
| [
"[email protected]"
] | |
ed6d4186ce6e277b18bd4a52a3b32f6de33883e9 | 30ff5962bb8a4c514c7b6acdebde84d84c69de8b | /main/java/com/svop/tables/Handbooks/SezonRepository.java | ac97cbe8825252087b0f75f7a66ddaa3386ff20e | [] | no_license | AlexSlow/SVOP | 78191a41844b8ddc4c32e388a36d4fc49e803391 | 5ab4b712dbd7ff880d66bed625d75581affd6789 | refs/heads/master | 2022-10-06T10:31:04.544161 | 2020-06-09T21:14:02 | 2020-06-09T21:14:02 | 241,961,319 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 481 | java | package com.svop.tables.Handbooks;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface SezonRepository extends JpaRepository<Sezon,Integer> {
@Transactional
public void deleteByIdIn(List<Integer> id);
Page<Sezon> findAll(Pageable pageable);
}
| [
"[email protected]"
] | |
cddf8e04cf808e483ad2f433a3b523e9efe759af | 89a03cb3acdffd1b5ac566615c9bc28d5354ee7c | /src/main/java/mapreduce/service_chain_hour_statistic/ServiceChainKey.java | 172753f3000dcc99f824691d11717d4a01f23208 | [] | no_license | nju823/log_hadoop | 5e455fe7337ee7ce4f5a00dc9af6c7898cceaf35 | 183df215517d3a489739e2e6bfa6d9f288f600e4 | refs/heads/master | 2021-04-03T01:57:06.978259 | 2018-03-29T10:48:44 | 2018-03-29T10:48:44 | 124,753,583 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,532 | java | package mapreduce.service_chain_hour_statistic;
/**
* Created by cong on 2018-03-27.
*/
public class ServiceChainKey {
/**
* 本接口
*/
private String serviceName;
/**
* 目标系统
*/
private int hour;
/**
* 日期
*/
private String date;
/**
* 起始调用的接口,用于标识调用链
*/
private String rootServiceName;
/**
* 发起调用的接口
*/
private String parentServiceName;
/**
* 目标系统
*/
private String target;
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getRootServiceName() {
return rootServiceName;
}
public void setRootServiceName(String rootServiceName) {
this.rootServiceName = rootServiceName;
}
public String getParentServiceName() {
return parentServiceName;
}
public void setParentServiceName(String parentServiceName) {
this.parentServiceName = parentServiceName;
}
}
| [
"[email protected]"
] | |
1fabadfc25990ed6c48fb00c1019ad9b6b34f4d1 | 2686270607044710a4185b39f9a78efaa9b3ff09 | /old/interview/src/main/java/com/shine/ali/Test446.java | b031b786886a49e8532a1eaa82ee494254d2578d | [] | no_license | CoinShine/algo | 5c6747c03eb3e9d153e71673b52f371ed19b3e21 | 50f1d241dceb1ec036188ac921c1959f43428293 | refs/heads/master | 2022-11-28T14:47:11.211597 | 2022-11-21T15:06:45 | 2022-11-21T15:06:45 | 205,323,094 | 4 | 0 | null | 2022-11-21T15:18:00 | 2019-08-30T06:54:05 | Java | UTF-8 | Java | false | false | 1,794 | java | package com.shine.ali;
import java.util.HashMap;
import java.util.Map;
/**
* description:等差数列划分 II - 子序列
*
* 如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。
* 例如,以下数列为等差数列:
* 1, 3, 5, 7, 9
* 7, 7, 7, 7
* 3, -1, -5, -9
* 以下数列不是等差数列。
* 1, 1, 2, 5, 7
*
* 数组 A 包含 N 个数,且索引从 0 开始。该数组子序列将划分为整数序列 (P0, P1, ..., Pk),P 与 Q 是整数且满足 0 ≤ P0 < P1 < ... < Pk < N。
* 如果序列 A[P0],A[P1],...,A[Pk-1],A[Pk] 是等差的,那么数组 A 的子序列 (P0,P1,…,PK) 称为等差序列。值得注意的是,这意味着 k ≥ 2。
* 函数要返回数组 A 中所有等差子序列的个数。
* 输入包含 N 个整数。每个整数都在 -2^31 和 2^31-1 之间,另外 0 ≤ N ≤ 1000。保证输出小于 2^31-1
*
* 示例:
* 输入:[2, 4, 6, 8, 10]
* 输出:7
* 解释:
* 所有的等差子序列为:
* [2,4,6]
* [4,6,8]
* [6,8,10]
* [2,4,6,8]
* [4,6,8,10]
* [2,4,6,8,10]
* [2,6,10]
* @author shine
* @date 2019/11/19 12:18
* @version 1.0
*/
public class Test446 {
public int numberOfArithmeticSlices(int[] A) {
int n = A.length;
long ans = 0;
Map<Integer, Integer>[] cnt = new Map[n];
for (int i = 0; i < n; i++) {
cnt[i] = new HashMap<>(i);
for (int j = 0; j < i; j++) {
long delta = (long)A[i] - (long)A[j];
if (delta < Integer.MIN_VALUE || delta > Integer.MAX_VALUE) {
continue;
}
int diff = (int)delta;
int sum = cnt[j].getOrDefault(diff, 0);
int origin = cnt[i].getOrDefault(diff, 0);
cnt[i].put(diff, origin + sum + 1);
ans += sum;
}
}
return (int)ans;
}
}
| [
"null"
] | null |
e43e8064b844379b5a0885713dabda25dc1856af | e20545b426897a9c4c5524135214b3dbf1a55424 | /src/layout/TeacherJPanel.java | 6e4ff7fc5bd2a4ac77219ba0f461864bd09843df | [] | no_license | trucydo/CheckAttendance | 344ab920b1a7e58f57969ea0bacd74ba06a4c23f | 71fdc8ee8928d4d1f8da8530cbe610cd24373904 | refs/heads/master | 2021-01-23T12:33:13.909473 | 2017-06-02T14:18:45 | 2017-06-02T14:18:45 | 93,170,792 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 79,165 | java | package layout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.WeekFields;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTable;
import com.github.lgooddatepicker.components.DatePicker;
import com.github.lgooddatepicker.components.DatePickerSettings;
import com.github.lgooddatepicker.components.TimePicker;
import com.github.lgooddatepicker.components.TimePickerSettings;
import pojo.Attendance;
import pojo.Course;
import pojo.User;
import dao.AttendanceDAO;
import dao.CourseDAO;
import dao.UserDAO;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
public class TeacherJPanel extends JPanel {
private JTextField textFieldSearch;
private JTable tableCourses;
private JButton btnShowCourses;
private JButton btnEditCourses;
private JButton btnShowAttendance;
private JPanel panelContent;
private JLabel lblPageTitle;
private JLabel lblSearch;
private JButton btnSearch;
private JButton btnAddCourse;
private JLabel lblSearchDetail;
private JComboBox comboBox;
private SpringLayout sl_panelMenu;
private JPanel panelMenu;
private SpringLayout sl_panelContent;
private JLabel lblOr;
private JButton btnNewCourseDetail;
private JLabel lblTitleDetail;
private JLabel lblCourseID;
private JTextField textFieldCourseID;
private DefaultTableModel model;
private TableColumnModel tcm;
private JLabel lblCourseName;
private JTextField textFieldCourseName;
private JLabel lblDateStarted;
private DatePicker datepickerDateStarted;
private JLabel lblDateFinished;
private DatePicker datepickerDateFinished;
private JLabel lblWeek;
private JComboBox comboBoxWeek;
private JLabel lblClassroom;
private JTextField textFieldClassroom;
private DatePickerSettings dateSettings1;
private DatePickerSettings dateSettings2;
private LocalDate date1;
private LocalDate date2;
private JLabel lblTimeFinished;
private JLabel lblTimeStarted;
private TimePicker timepickerTimeFinished;
private TimePicker timepickerTimeStarted;
private JScrollPane scrollPaneCourses;
private JButton btnShowEnrolled;
private JButton btnShowNonEnrolled;
private JButton btnAddNew;
private JButton btnImportCSV;
private JButton btnSave;
private JLabel lblStatus;
private boolean hasDetail = false;
private int optionInput = 0;
private List<Course> listCourse;
private JScrollPane spEnrolled;
private String editCourse;
private JScrollPane spNonEnrolled;
private JButton btnOp1;
private JButton btnOp2;
private boolean addNew = false;
private JButton btnOp3;
private JTextField textFieldAddNew;
private JComboBox comboBoxAttendance;
private JLabel lblChooseCourse;
private JScrollPane spAttendance;
private JTextField textFieldAddName;
private JButton btnExport;
private JButton btnImport;
/**
* Create the panel.
*/
public TeacherJPanel() {
setBackground(Color.WHITE);
setBounds(200, 100, 1200, 700);
SpringLayout springLayout = new SpringLayout();
setLayout(springLayout);
panelMenu = new JPanel();
springLayout.putConstraint(SpringLayout.NORTH, panelMenu, 0, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.EAST, panelMenu, 250, SpringLayout.WEST, this);
panelMenu.setBackground(new Color(245, 245, 245));
springLayout.putConstraint(SpringLayout.WEST, panelMenu, 0, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, panelMenu, 0, SpringLayout.SOUTH, this);
add(panelMenu);
sl_panelMenu = new SpringLayout();
panelMenu.setLayout(sl_panelMenu);
btnShowCourses = new JButton("Xem danh s\u00E1ch m\u00F4n h\u1ECDc");
sl_panelMenu.putConstraint(SpringLayout.NORTH, btnShowCourses, 0, SpringLayout.NORTH, panelMenu);
sl_panelMenu.putConstraint(SpringLayout.WEST, btnShowCourses, 0, SpringLayout.WEST, panelMenu);
sl_panelMenu.putConstraint(SpringLayout.SOUTH, btnShowCourses, 60, SpringLayout.NORTH, panelMenu);
sl_panelMenu.putConstraint(SpringLayout.EAST, btnShowCourses, 0, SpringLayout.EAST, panelMenu);
panelMenu.add(btnShowCourses);
btnShowCourses.setForeground(new Color(255, 255, 255));
btnShowCourses.setBackground(new Color(255, 140, 0));
btnShowCourses.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnShowCourses.setBorder(BorderFactory.createEmptyBorder());
btnEditCourses = new JButton("Thêm/Chỉnh sửa môn học");
sl_panelMenu.putConstraint(SpringLayout.NORTH, btnEditCourses, 0, SpringLayout.SOUTH, btnShowCourses);
sl_panelMenu.putConstraint(SpringLayout.WEST, btnEditCourses, 0, SpringLayout.WEST, panelMenu);
sl_panelMenu.putConstraint(SpringLayout.SOUTH, btnEditCourses, 60, SpringLayout.SOUTH, btnShowCourses);
sl_panelMenu.putConstraint(SpringLayout.EAST, btnEditCourses, 0, SpringLayout.EAST, panelMenu);
panelMenu.add(btnEditCourses);
btnEditCourses.setForeground(new Color(255, 255, 255));
btnEditCourses.setBackground(new Color(112, 128, 144));
btnEditCourses.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnEditCourses.setBorder(BorderFactory.createEmptyBorder());
btnShowAttendance = new JButton("Xem kết quả điểm danh");
sl_panelMenu.putConstraint(SpringLayout.NORTH, btnShowAttendance, 0, SpringLayout.SOUTH, btnEditCourses);
sl_panelMenu.putConstraint(SpringLayout.WEST, btnShowAttendance, 0, SpringLayout.WEST, panelMenu);
sl_panelMenu.putConstraint(SpringLayout.SOUTH, btnShowAttendance, 60, SpringLayout.SOUTH, btnEditCourses);
sl_panelMenu.putConstraint(SpringLayout.EAST, btnShowAttendance, 0, SpringLayout.EAST, panelMenu);
panelMenu.add(btnShowAttendance);
btnShowAttendance.setBackground(new Color(112, 128, 144));
btnShowAttendance.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnShowAttendance.setForeground(Color.WHITE);
btnShowAttendance.setBorder(BorderFactory.createEmptyBorder());
panelContent = new JPanel();
springLayout.putConstraint(SpringLayout.NORTH, panelContent, 0, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.WEST, panelContent, 0, SpringLayout.EAST, panelMenu);
springLayout.putConstraint(SpringLayout.EAST, panelContent, 0, SpringLayout.EAST, this);
panelContent.setBackground(new Color(255, 255, 255));
springLayout.putConstraint(SpringLayout.SOUTH, panelContent, 0, SpringLayout.SOUTH, this);
add(panelContent);
sl_panelContent = new SpringLayout();
panelContent.setLayout(sl_panelContent);
listCourse = CourseDAO.getCourseList();
addShowCourse();
btnShowCourses.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
panelContent.removeAll();
hasDetail = false;
addShowCourse();
btnShowCourses.setBackground(new Color(255, 140, 0));
btnShowAttendance.setBackground(new Color(112, 128, 144));
btnEditCourses.setBackground(new Color(112, 128, 144));
panelContent.validate();
panelContent.repaint();
}
});
btnEditCourses.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
panelContent.removeAll();
addEditCourses();
hasDetail = false;
btnShowCourses.setBackground(new Color(112, 128, 144));
btnShowAttendance.setBackground(new Color(112, 128, 144));
btnEditCourses.setBackground(new Color(255, 140, 0));
panelContent.validate();
panelContent.repaint();
}
});
btnShowAttendance.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
panelContent.removeAll();
addAttendance();
hasDetail = false;
btnShowCourses.setBackground(new Color(112, 128, 144));
btnEditCourses.setBackground(new Color(112, 128, 144));
btnShowAttendance.setBackground(new Color(255, 140, 0));
panelContent.validate();
panelContent.repaint();
}
});
}
void addShowCourse(){
lblPageTitle = new JLabel("Danh sách môn học");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblPageTitle, 20, SpringLayout.NORTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, lblPageTitle, 40, SpringLayout.WEST, panelContent);
panelContent.add(lblPageTitle);
lblPageTitle.setForeground(new Color(0, 191, 255));
lblPageTitle.setBackground(Color.WHITE);
lblPageTitle.setFont(new Font("Segoe UI Light", Font.PLAIN, 28));
lblSearch = new JLabel("T\u00ECm ki\u1EBFm m\u00F4n h\u1ECDc");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblSearch, 80, SpringLayout.NORTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, lblSearch, 40, SpringLayout.WEST, panelContent);
panelContent.add(lblSearch);
lblSearch.setFont(new Font("Segoe UI", Font.PLAIN, 18));
textFieldSearch = new JTextField();
sl_panelContent.putConstraint(SpringLayout.NORTH, textFieldSearch, 78, SpringLayout.NORTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, textFieldSearch, 10, SpringLayout.EAST, lblSearch);
sl_panelContent.putConstraint(SpringLayout.SOUTH, textFieldSearch, 112, SpringLayout.NORTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, textFieldSearch, -400, SpringLayout.EAST, panelContent);
panelContent.add(textFieldSearch);
textFieldSearch.setFont(new Font("Segoe UI", Font.PLAIN, 18));
textFieldSearch.setColumns(10);
btnSearch = new JButton("T\u00ECm");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnSearch, 0, SpringLayout.NORTH, textFieldSearch);
sl_panelContent.putConstraint(SpringLayout.WEST, btnSearch, 10, SpringLayout.EAST, textFieldSearch);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnSearch, 0, SpringLayout.SOUTH, textFieldSearch);
sl_panelContent.putConstraint(SpringLayout.EAST, btnSearch, -300, SpringLayout.EAST, panelContent);
panelContent.add(btnSearch);
btnSearch.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnSearch.setBackground(new Color(112, 128, 144));
btnSearch.setForeground(new Color(255, 255, 255));
btnSearch.setBorder(BorderFactory.createEmptyBorder());
btnAddCourse = new JButton("Thêm môn học mới");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnAddCourse, 0, SpringLayout.NORTH, btnSearch);
sl_panelContent.putConstraint(SpringLayout.WEST, btnAddCourse, 20, SpringLayout.EAST, btnSearch);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnAddCourse, 0, SpringLayout.SOUTH, btnSearch);
sl_panelContent.putConstraint(SpringLayout.EAST, btnAddCourse, -40, SpringLayout.EAST, panelContent);
panelContent.add(btnAddCourse);
btnAddCourse.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnAddCourse.setBackground(new Color(255, 140, 0));
btnAddCourse.setForeground(new Color(255, 255, 255));
btnAddCourse.setBorder(BorderFactory.createEmptyBorder());
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Mã môn học");
columnNames.addElement("Tên môn học");
columnNames.addElement("Tình trạng");
columnNames.addElement("#");
Vector<Vector> rowData = new Vector<Vector>();
tableCourses = new JTable(rowData, columnNames){
public boolean isCellEditable(int row, int column){
return column == 3;
}
};
model = (DefaultTableModel) tableCourses.getModel();
model.setDataVector(null,columnNames);
for(int i=0; i<listCourse.size(); i++){
model.addRow(Course.getTableRow(i, listCourse));
}
// Make cell centered
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
tcm = tableCourses.getColumnModel();
tcm.getColumn(0).setPreferredWidth(150);
tcm.getColumn(1).setPreferredWidth(370);
tcm.getColumn(2).setPreferredWidth(200);
tcm.getColumn(3).setPreferredWidth(150);
tableCourses.setFont(new Font("Segoe UI", Font.PLAIN, 16));
tableCourses.setRowHeight(30);
//model = (DefaultTableModel) tableCourses.getModel();
tableCourses.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
tableCourses.getColumnModel().getColumn(1).setCellRenderer( centerRenderer );
tableCourses.getColumnModel().getColumn(2).setCellRenderer( centerRenderer );
scrollPaneCourses = new JScrollPane(tableCourses);
sl_panelContent.putConstraint(SpringLayout.NORTH, scrollPaneCourses, 140, SpringLayout.NORTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, scrollPaneCourses, 40, SpringLayout.WEST, panelContent);
sl_panelContent.putConstraint(SpringLayout.SOUTH, scrollPaneCourses, -40, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, scrollPaneCourses, -40, SpringLayout.EAST, panelContent);
panelContent.add(scrollPaneCourses);
tableCourses.setSelectionBackground(new Color(255, 235, 205));
tableCourses.getColumn("#").setCellRenderer(new ButtonRenderer());
tableCourses.getColumn("#").setCellEditor(new ButtonEditor(new JCheckBox()));
tableCourses.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
// your code goes here, whatever you want to do when something changes in the table
//System.out.println(model.getValueAt(e.getFirstRow(),0));
hasDetail = false;
panelContent.removeAll();
addEditCourses();
comboBox.setSelectedIndex(e.getFirstRow()+1);
btnShowCourses.setBackground(new Color(112, 128, 144));
btnShowAttendance.setBackground(new Color(112, 128, 144));
btnEditCourses.setBackground(new Color(255, 140, 0));
panelContent.validate();
panelContent.repaint();
}
});
btnAddCourse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
panelContent.removeAll();
addNew = true;
addEditCourses();
Date date = new Date();
Time time = new Time(date.getTime());
System.out.println(time.toString());
addDetailCourse("Thêm môn học mới","","--","",date,date,2,time,time,"");
hasDetail = true;
editCourse="";
btnShowCourses.setBackground(new Color(112, 128, 144));
btnShowAttendance.setBackground(new Color(112, 128, 144));
btnEditCourses.setBackground(new Color(255, 140, 0));
panelContent.validate();
panelContent.repaint();
}
});
}
void removeShowCourse(){
panelContent.remove(lblPageTitle);
panelContent.remove(lblSearch);
panelContent.remove(textFieldSearch);
panelContent.remove(btnSearch);
panelContent.remove(btnAddCourse);
panelContent.remove(lblSearch);
panelContent.remove(scrollPaneCourses);
panelContent.remove(scrollPaneCourses);
}
void addEditCourses(){
lblSearchDetail = new JLabel("Chỉnh sửa môn học");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblSearchDetail, 20, SpringLayout.NORTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, lblSearchDetail, 40, SpringLayout.WEST, panelContent);
lblSearchDetail.setBackground(new Color(255, 255, 255));
lblSearchDetail.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblSearchDetail);
Vector<String> course = new Vector<String>();
course.add("");
//listCourses.clear();
listCourse = CourseDAO.getCourseList();
for(int i=0; i< listCourse.size(); i++){
Course c= listCourse.get(i);
course.addElement(c.getmCourseID()+" - "+ c.getmName());
}
comboBox = new JComboBox(course);
comboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
sl_panelContent.putConstraint(SpringLayout.NORTH, comboBox, -5, SpringLayout.NORTH, lblSearchDetail);
sl_panelContent.putConstraint(SpringLayout.WEST, comboBox, 10, SpringLayout.EAST, lblSearchDetail);
sl_panelContent.putConstraint(SpringLayout.SOUTH, comboBox, 5, SpringLayout.SOUTH, lblSearchDetail);
sl_panelContent.putConstraint(SpringLayout.EAST, comboBox, 600, SpringLayout.WEST, panelContent);
//comboBox.setEditable(true);
panelContent.add(comboBox);
lblOr = new JLabel("hoặc");
lblOr.setFont(new Font("Segoe UI", Font.PLAIN, 18));
lblOr.setHorizontalAlignment(SwingConstants.CENTER);
sl_panelContent.putConstraint(SpringLayout.NORTH, lblOr, 0, SpringLayout.NORTH, lblSearchDetail);
sl_panelContent.putConstraint(SpringLayout.WEST, lblOr, 20, SpringLayout.EAST, comboBox);
sl_panelContent.putConstraint(SpringLayout.SOUTH, lblOr, 0, SpringLayout.SOUTH, lblSearchDetail);
panelContent.add(lblOr);
btnNewCourseDetail = new JButton("Thêm môn học mới");
btnNewCourseDetail.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnNewCourseDetail.setForeground(new Color(255, 255, 255));
btnNewCourseDetail.setBackground(new Color(255, 140, 0));
sl_panelContent.putConstraint(SpringLayout.NORTH, btnNewCourseDetail, 0, SpringLayout.NORTH, comboBox);
sl_panelContent.putConstraint(SpringLayout.WEST, btnNewCourseDetail, 20, SpringLayout.EAST, lblOr);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnNewCourseDetail, 0, SpringLayout.SOUTH, comboBox);
sl_panelContent.putConstraint(SpringLayout.EAST, btnNewCourseDetail, -40, SpringLayout.EAST, panelContent);
panelContent.add(btnNewCourseDetail);
btnNewCourseDetail.setBorder(BorderFactory.createEmptyBorder());
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (comboBox.getSelectedIndex()!= 0){
addNew = false;
int index = comboBox.getSelectedIndex() - 1;
Course c = listCourse.get(index);
Date date = new Date();
//Time time = new Time(date.getTime());
//System.out.println(time.toString());
String status ="";
if (c.getmDateFinished().compareTo(date)< 0){
status = "Đã kết thúc";
}
else if (c.getmDateStarted().compareTo(date)>0){
status = "Chưa bắt đầu";
}else {
status = "Đang diễn ra";
}
if (hasDetail){
removeCourseDetail();
}
if (optionInput == 1){
panelContent.remove(spEnrolled);
panelContent.remove(btnOp1);
}else if(optionInput == 2){
panelContent.remove(spNonEnrolled);
panelContent.remove(btnOp2);
}else if(optionInput == 3){
panelContent.remove(textFieldAddNew);
panelContent.remove(textFieldAddName);
panelContent.remove(btnOp3);
}else if(optionInput ==4){
panelContent.remove(btnExport);
panelContent.remove(btnImport);
}
hasDetail = true;
editCourse = c.getmCourseID();
addDetailCourse("Chỉnh sửa môn học",c.getmCourseID(),status,c.getmName(),
c.getmDateStarted(),c.getmDateFinished(),c.getmWeekday(),
c.getmTimeStarted(),c.getmTimeFinished(),c.getmClassroom());
optionInput = 0;
panelContent.validate();
panelContent.repaint();
}
}
});
btnNewCourseDetail.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
panelContent.removeAll();
addNew = true;
addEditCourses();
if (hasDetail){
removeCourseDetail();
}
Date date = new Date();
Time time = new Time(date.getTime());
System.out.println(time.toString());
addDetailCourse("Thêm môn học mới","","--","",date,date,2,time,time,"");
hasDetail = true;
btnShowCourses.setBackground(new Color(112, 128, 144));
btnShowAttendance.setBackground(new Color(112, 128, 144));
btnEditCourses.setBackground(new Color(255, 140, 0));
panelContent.validate();
panelContent.repaint();
}
});
}
void removeEditCourse(){
panelContent.add(lblSearchDetail);
panelContent.add(comboBox);
panelContent.add(lblOr);
panelContent.add(btnNewCourseDetail);
comboBox.removeActionListener(comboBox);
btnNewCourseDetail.setBorder(BorderFactory.createEmptyBorder());
}
void addDetailCourse(String title, String courseID, String status, String courseName, Date dateStarted, Date dateFinished, int week, Time timeStarted, Time timeFinished, String classroom ){
lblTitleDetail = new JLabel(title);
sl_panelContent.putConstraint(SpringLayout.NORTH, lblTitleDetail, 70, SpringLayout.NORTH, panelContent);
lblTitleDetail.setForeground(new Color(0, 191, 255));
lblTitleDetail.setFont(new Font("Segoe UI Light", Font.PLAIN, 28));
lblTitleDetail.setBackground(new Color(255, 255, 255));
sl_panelContent.putConstraint(SpringLayout.WEST, lblTitleDetail, 40, SpringLayout.WEST, panelContent);
panelContent.add(lblTitleDetail);
lblCourseID = new JLabel("Mã môn học");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblCourseID, 140, SpringLayout.NORTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, lblCourseID, 40, SpringLayout.WEST, panelContent);
lblCourseID.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblCourseID);
textFieldCourseID = new JTextField(courseID);
sl_panelContent.putConstraint(SpringLayout.NORTH, textFieldCourseID, -5, SpringLayout.NORTH, lblCourseID);
sl_panelContent.putConstraint(SpringLayout.WEST, textFieldCourseID, 15, SpringLayout.EAST, lblCourseID);
sl_panelContent.putConstraint(SpringLayout.SOUTH, textFieldCourseID, 5, SpringLayout.SOUTH, lblCourseID);
sl_panelContent.putConstraint(SpringLayout.EAST, textFieldCourseID, 350, SpringLayout.WEST, panelContent);
panelContent.add(textFieldCourseID);
textFieldCourseID.setFont(new Font("Segoe UI", Font.PLAIN, 18));
textFieldCourseID.setColumns(10);
lblStatus = new JLabel("Tình trạng: "+ status);
sl_panelContent.putConstraint(SpringLayout.EAST, lblStatus, 630, SpringLayout.WEST, panelContent);
lblStatus.setFont(new Font("Segoe UI", Font.PLAIN, 18));
sl_panelContent.putConstraint(SpringLayout.NORTH, lblStatus, 0, SpringLayout.NORTH, lblCourseID);
sl_panelContent.putConstraint(SpringLayout.WEST, lblStatus, 40, SpringLayout.EAST, textFieldCourseID);
sl_panelContent.putConstraint(SpringLayout.SOUTH, lblStatus, 0, SpringLayout.SOUTH, lblCourseID);
panelContent.add(lblStatus);
/*
JButton btnDeleteCourse = new JButton("Xóa môn học");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnDeleteCourse, 0, SpringLayout.NORTH, textFieldCourseID);
sl_panelContent.putConstraint(SpringLayout.WEST, btnDeleteCourse, 45, SpringLayout.EAST, lblStatus);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnDeleteCourse, 0, SpringLayout.SOUTH, textFieldCourseID);
sl_panelContent.putConstraint(SpringLayout.EAST, btnDeleteCourse, -40, SpringLayout.EAST, panelContent);
btnDeleteCourse.setForeground(new Color(255, 255, 255));
btnDeleteCourse.setBackground(new Color(255, 99, 71));
btnDeleteCourse.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnDeleteCourse.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnDeleteCourse);
*/
lblCourseName = new JLabel("Tên môn học");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblCourseName, 50, SpringLayout.NORTH, lblCourseID);
sl_panelContent.putConstraint(SpringLayout.WEST, lblCourseName, 40, SpringLayout.WEST, panelContent);
lblCourseName.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblCourseName);
textFieldCourseName = new JTextField(courseName);
sl_panelContent.putConstraint(SpringLayout.NORTH, textFieldCourseName, -5, SpringLayout.NORTH, lblCourseName);
sl_panelContent.putConstraint(SpringLayout.WEST, textFieldCourseName, 0, SpringLayout.WEST, textFieldCourseID);
sl_panelContent.putConstraint(SpringLayout.SOUTH, textFieldCourseName, 5, SpringLayout.SOUTH, lblCourseName);
sl_panelContent.putConstraint(SpringLayout.EAST, textFieldCourseName, -350, SpringLayout.EAST, panelContent);
panelContent.add(textFieldCourseName);
textFieldCourseName.setFont(new Font("Segoe UI", Font.PLAIN, 18));
textFieldCourseName.setColumns(10);
lblDateStarted = new JLabel("Ngày bắt đầu");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblDateStarted, 50, SpringLayout.NORTH, lblCourseName);
sl_panelContent.putConstraint(SpringLayout.WEST, lblDateStarted, 40, SpringLayout.WEST, panelContent);
lblDateStarted.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblDateStarted);
dateSettings1 = new DatePickerSettings();
datepickerDateStarted = new DatePicker(dateSettings1);
dateSettings1.setFontValidDate(new Font("Segoe UI", Font.PLAIN, 18));
//System.out.println(dateStarted.toString());
if (courseID.equals("")){
date1 = dateStarted.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
date2 = dateStarted.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}else{
date1= LocalDate.parse(dateStarted.toString());
date2= LocalDate.parse(dateFinished.toString());
}
datepickerDateStarted.setDate(date1);
sl_panelContent.putConstraint(SpringLayout.NORTH, datepickerDateStarted, -5, SpringLayout.NORTH, lblDateStarted);
sl_panelContent.putConstraint(SpringLayout.WEST, datepickerDateStarted, 0, SpringLayout.WEST, textFieldCourseID);
sl_panelContent.putConstraint(SpringLayout.SOUTH, datepickerDateStarted, 5, SpringLayout.SOUTH, lblDateStarted);
sl_panelContent.putConstraint(SpringLayout.EAST, datepickerDateStarted, 16, SpringLayout.EAST, textFieldCourseID);
panelContent.add(datepickerDateStarted);
datepickerDateStarted.setFont(new Font("Segoe UI", Font.PLAIN, 18));
//datepickerDateStarted.setColumns(10);
lblDateFinished = new JLabel("Ngày kết thúc");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblDateFinished, 0, SpringLayout.NORTH, lblDateStarted);
sl_panelContent.putConstraint(SpringLayout.WEST, lblDateFinished, 0, SpringLayout.WEST, lblStatus);
lblDateFinished.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblDateFinished);
dateSettings2 = new DatePickerSettings();
datepickerDateFinished = new DatePicker(dateSettings2);
dateSettings2.setFontValidDate(new Font("Segoe UI", Font.PLAIN, 18));
//date2 = dateFinished.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
datepickerDateFinished.setDate(date2);
sl_panelContent.putConstraint(SpringLayout.NORTH, datepickerDateFinished, 0, SpringLayout.NORTH, datepickerDateStarted);
sl_panelContent.putConstraint(SpringLayout.WEST, datepickerDateFinished, 10, SpringLayout.EAST, lblDateFinished);
sl_panelContent.putConstraint(SpringLayout.SOUTH, datepickerDateFinished, 0, SpringLayout.SOUTH, datepickerDateStarted);
sl_panelContent.putConstraint(SpringLayout.EAST, datepickerDateFinished, 220, SpringLayout.EAST, lblDateFinished);
datepickerDateFinished.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(datepickerDateFinished);
//datepickerDateFinished.setColumns(10);
lblWeek = new JLabel("Thứ");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblWeek, 50, SpringLayout.NORTH, lblDateStarted);
sl_panelContent.putConstraint(SpringLayout.WEST, lblWeek, 40, SpringLayout.WEST, panelContent);
lblWeek.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblWeek);
String[] arrWeekdays = { "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm","Thứ sáu","Thứ bảy","Chủ nhật" };
comboBoxWeek = new JComboBox<String>(arrWeekdays);
sl_panelContent.putConstraint(SpringLayout.NORTH, comboBoxWeek, -5, SpringLayout.NORTH, lblWeek);
sl_panelContent.putConstraint(SpringLayout.WEST, comboBoxWeek, 0, SpringLayout.WEST, datepickerDateStarted);
sl_panelContent.putConstraint(SpringLayout.SOUTH, comboBoxWeek, 5, SpringLayout.SOUTH, lblWeek);
sl_panelContent.putConstraint(SpringLayout.EAST, comboBoxWeek, 0, SpringLayout.EAST, datepickerDateStarted);
comboBoxWeek.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(comboBoxWeek);
comboBoxWeek.setSelectedIndex(week-2);
lblClassroom = new JLabel("Phòng học");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblClassroom, 0, SpringLayout.NORTH, lblCourseName);
sl_panelContent.putConstraint(SpringLayout.WEST, lblClassroom, 25, SpringLayout.EAST, textFieldCourseName);
lblClassroom.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblClassroom);
textFieldClassroom = new JTextField(classroom);
sl_panelContent.putConstraint(SpringLayout.NORTH, textFieldClassroom, 0, SpringLayout.NORTH, textFieldCourseName);
sl_panelContent.putConstraint(SpringLayout.WEST, textFieldClassroom, 15, SpringLayout.EAST, lblClassroom);
sl_panelContent.putConstraint(SpringLayout.SOUTH, textFieldClassroom, 0, SpringLayout.SOUTH, textFieldCourseName);
sl_panelContent.putConstraint(SpringLayout.EAST, textFieldClassroom, 200, SpringLayout.EAST, lblClassroom);
textFieldClassroom.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(textFieldClassroom);
textFieldClassroom.setColumns(10);
lblTimeStarted = new JLabel("Giờ bắt đầu");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblTimeStarted, 0, SpringLayout.NORTH, lblWeek);
sl_panelContent.putConstraint(SpringLayout.WEST, lblTimeStarted, 25, SpringLayout.EAST, comboBoxWeek);
lblTimeStarted.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblTimeStarted);
TimePickerSettings timeSettings1 = new TimePickerSettings();
timeSettings1.initialTime = timeStarted.toLocalTime();
timepickerTimeStarted = new TimePicker(timeSettings1);
sl_panelContent.putConstraint(SpringLayout.NORTH, timepickerTimeStarted, 0, SpringLayout.NORTH, comboBoxWeek);
sl_panelContent.putConstraint(SpringLayout.WEST, timepickerTimeStarted, 0, SpringLayout.WEST, datepickerDateFinished);
sl_panelContent.putConstraint(SpringLayout.SOUTH, timepickerTimeStarted, 0, SpringLayout.SOUTH, comboBoxWeek);
//sl_panelContent.putConstraint(SpringLayout.EAST, timepickerTimeStarted, 220, SpringLayout.EAST, lblDateFinished);
panelContent.add(timepickerTimeStarted);
lblTimeFinished = new JLabel("Giờ kết thúc");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblTimeFinished, 0, SpringLayout.NORTH, lblTimeStarted);
sl_panelContent.putConstraint(SpringLayout.WEST, lblTimeFinished, 25, SpringLayout.EAST, timepickerTimeStarted);
lblTimeFinished.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblTimeFinished);
TimePickerSettings timeSettings2 = new TimePickerSettings();
timeSettings2.initialTime = timeFinished.toLocalTime();
timepickerTimeFinished = new TimePicker(timeSettings2);
sl_panelContent.putConstraint(SpringLayout.NORTH, timepickerTimeFinished, 0, SpringLayout.NORTH, timepickerTimeStarted);
sl_panelContent.putConstraint(SpringLayout.WEST, timepickerTimeFinished, 25, SpringLayout.EAST, lblTimeFinished);
sl_panelContent.putConstraint(SpringLayout.SOUTH, timepickerTimeFinished, 0, SpringLayout.SOUTH, timepickerTimeStarted);
sl_panelContent.putConstraint(SpringLayout.EAST, timepickerTimeFinished, -40, SpringLayout.EAST, panelContent);
panelContent.add(timepickerTimeFinished);
btnShowEnrolled = new JButton("Danh sách sinh viên đăng ký");
btnShowEnrolled.setBackground(new Color(112, 128, 144));
btnShowEnrolled.setForeground(Color.WHITE);
sl_panelContent.putConstraint(SpringLayout.NORTH, btnShowEnrolled, 60, SpringLayout.NORTH, lblWeek);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnShowEnrolled, 100, SpringLayout.NORTH, lblWeek);
sl_panelContent.putConstraint(SpringLayout.WEST, btnShowEnrolled, 40, SpringLayout.WEST, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, btnShowEnrolled, 0, SpringLayout.EAST, comboBoxWeek);
btnShowEnrolled.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnShowEnrolled.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnShowEnrolled);
btnShowNonEnrolled = new JButton("Danh sách sinh viên chưa đăng ký");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnShowNonEnrolled, 50, SpringLayout.NORTH, btnShowEnrolled);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnShowNonEnrolled, 90, SpringLayout.NORTH, btnShowEnrolled);
btnShowNonEnrolled.setBackground(new Color(112, 128, 144));
btnShowNonEnrolled.setForeground(new Color(255, 255, 255));
sl_panelContent.putConstraint(SpringLayout.WEST, btnShowNonEnrolled, 0, SpringLayout.WEST, btnShowEnrolled);
sl_panelContent.putConstraint(SpringLayout.EAST, btnShowNonEnrolled, 0, SpringLayout.EAST, btnShowEnrolled);
btnShowNonEnrolled.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnShowNonEnrolled.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnShowNonEnrolled);
btnAddNew = new JButton("Thêm sinh viên mới");
btnAddNew.setBackground(new Color(112, 128, 144));
btnAddNew.setForeground(new Color(255, 255, 255));
btnAddNew.setFont(new Font("Segoe UI", Font.PLAIN, 18));
sl_panelContent.putConstraint(SpringLayout.NORTH, btnAddNew, 50, SpringLayout.NORTH, btnShowNonEnrolled);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnAddNew, 90, SpringLayout.NORTH, btnShowNonEnrolled);
sl_panelContent.putConstraint(SpringLayout.WEST, btnAddNew, 0, SpringLayout.WEST, btnShowNonEnrolled);
sl_panelContent.putConstraint(SpringLayout.EAST, btnAddNew, 0, SpringLayout.EAST, btnShowNonEnrolled);
btnAddNew.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnAddNew);
btnImportCSV = new JButton("Import từ CSV");
btnImportCSV.setBackground(new Color(112, 128, 144));
btnImportCSV.setForeground(new Color(255, 255, 255));
btnImportCSV.setFont(new Font("Segoe UI", Font.PLAIN, 18));
sl_panelContent.putConstraint(SpringLayout.NORTH, btnImportCSV, 50, SpringLayout.NORTH, btnAddNew);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnImportCSV, 90, SpringLayout.NORTH, btnAddNew);
sl_panelContent.putConstraint(SpringLayout.WEST, btnImportCSV, 0, SpringLayout.WEST, btnAddNew);
sl_panelContent.putConstraint(SpringLayout.EAST, btnImportCSV, 0, SpringLayout.EAST, btnAddNew);
btnImportCSV.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnImportCSV);
btnSave = new JButton("Lưu thay đổi");
btnSave.setBackground(new Color(255, 99, 71));
btnSave.setForeground(new Color(255, 255, 255));
btnSave.setFont(new Font("Segoe UI", Font.PLAIN, 20));
sl_panelContent.putConstraint(SpringLayout.NORTH, btnSave, -80, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, btnSave, 300, SpringLayout.WEST, panelContent);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnSave, -40, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, btnSave, -300, SpringLayout.EAST, panelContent);
btnSave.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnSave);
btnSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
boolean matched = false;
boolean accept = false;
LocalDate dateActual = null;
LocalDate dateActualF = null;
if (textFieldCourseID.getText().equals("") || textFieldCourseName.getText().equals("") || textFieldClassroom.getText().equals("")){
JOptionPane.showMessageDialog(null, "Xin hãy điền đầy đủ thông tin môn học.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
if (addNew){
for (int i = 0; i<listCourse.size(); ++i){
if (textFieldCourseID.getText().equals(listCourse.get(i).getmCourseID())){
matched = true;
}
}
}
if (matched){
JOptionPane.showMessageDialog(null, "Mã môn học đã tồn tại", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
if (timepickerTimeStarted.getTime().compareTo(timepickerTimeFinished.getTime()) >= 0){
JOptionPane.showMessageDialog(null, "Giờ bắt đầu phải bé hơn giờ kết thúc", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
int dowstudy = (comboBoxWeek.getSelectedIndex() != 6) ?(comboBoxWeek.getSelectedIndex()+ 2) : 1;
int dow1 = datepickerDateStarted.getDate().get(WeekFields.SUNDAY_START.dayOfWeek());
if (dow1 == dowstudy){
dateActual = datepickerDateStarted.getDate();
}else if (dow1 < dowstudy){
dateActual = datepickerDateStarted.getDate().plusDays(dowstudy-dow1);
}else{
dateActual = datepickerDateStarted.getDate().plusDays(7 - (dow1-dowstudy));
}
dateActualF = dateActual.plusDays(7*15);
//System.out.println(dowstudy);
//System.out.println(dow1);
//System.out.println(dateActual);
//System.out.println(dateActualF);
Course c = new Course();
c.setmCourseID(textFieldCourseID.getText());
c.setmName(textFieldCourseName.getText());
c.setmDateStarted(Date.from(dateActual.atStartOfDay(ZoneId.systemDefault()).toInstant()));
c.setmDateFinished(Date.from(dateActualF.atStartOfDay(ZoneId.systemDefault()).toInstant()));
if (dowstudy == 1){
c.setmWeekday(8);
}else{
c.setmWeekday(dowstudy);
}
c.setmTimeStarted(Time.valueOf(timepickerTimeStarted.getTime()));
c.setmTimeFinished(Time.valueOf(timepickerTimeFinished.getTime()));
c.setmClassroom(textFieldClassroom.getText());
boolean res = false;
if (addNew){
res= CourseDAO.addNew(c);
}else{
res= CourseDAO.update(c);
}
if (res == true) {
JOptionPane.showMessageDialog(null, "Thêm/cập nhật thành công.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
listCourse.clear();
listCourse = CourseDAO.getCourseList();
panelContent.removeAll();
addShowCourse();
btnShowCourses.setBackground(new Color(255, 140, 0));
btnShowAttendance.setBackground(new Color(112, 128, 144));
btnEditCourses.setBackground(new Color(112, 128, 144));
panelContent.validate();
panelContent.repaint();
}
else {
JOptionPane.showMessageDialog(null, "Thêm/cập nhật thất bại.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
}
});
btnShowEnrolled.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (editCourse.equals("")){
JOptionPane.showMessageDialog(null, "Xin hãy hoàn thành thông tin môn học. Sau đó bấm 'Lưu thay đổi' để tiếp tục.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
addEnrolledStudents(editCourse);
panelContent.validate();
panelContent.repaint();
}
}
});
btnShowNonEnrolled.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (editCourse.equals("")){
JOptionPane.showMessageDialog(null, "Xin hãy hoàn thành thông tin môn học. Sau đó bấm 'Lưu thay đổi' để tiếp tục.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
addNonEnrolledStudents(editCourse);
panelContent.validate();
panelContent.repaint();
}
}
});
btnAddNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (editCourse.equals("")){
JOptionPane.showMessageDialog(null, "Xin hãy hoàn thành thông tin môn học. Sau đó bấm 'Lưu thay đổi' để tiếp tục.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
addNewStudents(editCourse);
panelContent.validate();
panelContent.repaint();
}
}
});
btnImportCSV.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (editCourse.equals("")){
JOptionPane.showMessageDialog(null, "Xin hãy hoàn thành thông tin môn học. Sau đó bấm 'Lưu thay đổi' để tiếp tục.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
addCSV();
panelContent.validate();
panelContent.repaint();
}
}
});
}
void removeCourseDetail(){
panelContent.remove(lblTitleDetail);
panelContent.remove(lblCourseID);
panelContent.remove(textFieldCourseID);
panelContent.remove(lblStatus);
//panelContent.remove(btnDeleteCourse);
panelContent.remove(lblCourseName);
panelContent.remove(textFieldCourseName);
panelContent.remove(lblDateStarted);
panelContent.remove(datepickerDateStarted);
panelContent.remove(lblDateFinished);
panelContent.remove(datepickerDateFinished);
panelContent.remove(lblWeek);
panelContent.remove(comboBoxWeek);
panelContent.remove(lblClassroom);
panelContent.remove(textFieldClassroom);
panelContent.remove(lblTimeStarted);
panelContent.remove(timepickerTimeStarted);
panelContent.remove(lblTimeFinished);
panelContent.remove(timepickerTimeFinished);
panelContent.remove(btnShowEnrolled);
panelContent.remove(btnShowNonEnrolled);
panelContent.remove(btnAddNew);
panelContent.remove(btnImportCSV);
panelContent.remove(btnSave);
}
void addEnrolledStudents(String courseID){
if(optionInput == 2){
panelContent.remove(spNonEnrolled);
panelContent.remove(btnOp2);
panelContent.validate();
panelContent.repaint();
}else if(optionInput == 3){
panelContent.remove(textFieldAddNew);
panelContent.remove(textFieldAddName);
panelContent.remove(btnOp3);
panelContent.validate();
panelContent.repaint();
}else if(optionInput == 4){
panelContent.remove(btnExport);
panelContent.remove(btnImport);
panelContent.validate();
panelContent.repaint();
}
String colNames[] = {"CheckBox", "MSSV"};
Object[][] data = {};
DefaultTableModel dtm;
dtm = new DefaultTableModel(data,colNames);
JTable table = new JTable(dtm);
spEnrolled = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
sl_panelContent.putConstraint(SpringLayout.NORTH, spEnrolled, -300, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, spEnrolled, -350, SpringLayout.EAST, panelContent);
sl_panelContent.putConstraint(SpringLayout.SOUTH, spEnrolled, -140, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, spEnrolled, -100, SpringLayout.EAST, panelContent);
btnOp1 = new JButton("Xóa sinh viên");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnOp1, 10, SpringLayout.SOUTH, spEnrolled);
sl_panelContent.putConstraint(SpringLayout.WEST, btnOp1, 20, SpringLayout.WEST, spEnrolled);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnOp1, 36, SpringLayout.SOUTH, spEnrolled);
sl_panelContent.putConstraint(SpringLayout.EAST, btnOp1, -20, SpringLayout.EAST, spEnrolled);
btnOp1.setForeground(new Color(255, 255, 255));
btnOp1.setBackground(new Color(255, 99, 71));
btnOp1.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnOp1.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnOp1);
List<Attendance> listAttendance = AttendanceDAO.getAttendanceList();
Vector<String> temp = new Vector<String>();
boolean matched = false;
for (int i =0; i < listAttendance.size(); ++i){
Attendance a = listAttendance.get(i);
if (a.getmCourse().getmCourseID().equals(courseID)){
if (temp.size()>0){
for (int j = 0; j < temp.size(); ++j){
if (a.getmStudent().getmUsername().equals(temp.get(j))){
matched = true;
}
}
if (!matched){
temp.add(a.getmStudent().getmUsername());
dtm.addRow(new Object[]{new Boolean(true),a.getmStudent().getmUsername()});
}
matched = false;
}else{
temp.add(a.getmStudent().getmUsername());
dtm.addRow(new Object[]{new Boolean(true),a.getmStudent().getmUsername()});
}
}
}
panelContent.add(spEnrolled);
optionInput = 1;
Vector <Integer> tempDelete = new Vector<Integer>();
table.getModel().addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if (e.getFirstRow()!=-1 && e.getColumn() != -1 ){
tempDelete.add(e.getFirstRow());
}
}
});
btnOp1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (tempDelete.size()>0){
List <Attendance> lsa = AttendanceDAO.getAttendanceList();
for (int i = 0; i< tempDelete.size();++i){
for (int j = 0; j < lsa.size(); ++j){
Attendance a = lsa.get(j);
if (a.getmStudent().getmUsername().equals(table.getModel().getValueAt(tempDelete.get(i),1)) &&
a.getmCourse().getmCourseID().equals(editCourse)){
boolean res = AttendanceDAO.delete(a.getmAttendanceID());
}
}
}
for (int i = 0; i< tempDelete.size()-1; ++i){
for (int j = i+1; j < tempDelete.size(); ++j){
if (tempDelete.get(i)<tempDelete.get(j)){
int temp = tempDelete.get(i);
tempDelete.set(i, tempDelete.get(j));
tempDelete.set(j, temp);
}
}
}
String info="";
for (int i = 0; i < tempDelete.size(); ++i){
info = info + dtm.getValueAt(tempDelete.get(i), 1) + "\n";
dtm.removeRow(tempDelete.get(i));
}
JOptionPane.showMessageDialog(null, "Xóa các sinh viên: \n"+info, "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
void addNonEnrolledStudents(String courseID){
if(optionInput == 1){
panelContent.remove(spEnrolled);
panelContent.remove(btnOp1);
panelContent.validate();
panelContent.repaint();
}else if(optionInput == 3){
panelContent.remove(textFieldAddNew);
panelContent.remove(textFieldAddName);
panelContent.remove(btnOp3);
panelContent.validate();
panelContent.repaint();
}else if(optionInput == 4){
panelContent.remove(btnExport);
panelContent.remove(btnImport);
panelContent.validate();
panelContent.repaint();
}
String colNames[] = {"CheckBox", "MSSV"};
Object[][] data = {};
DefaultTableModel dtm;
dtm = new DefaultTableModel(data,colNames);
JTable table = new JTable(dtm);
spNonEnrolled = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
sl_panelContent.putConstraint(SpringLayout.NORTH, spNonEnrolled, -300, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, spNonEnrolled, -350, SpringLayout.EAST, panelContent);
sl_panelContent.putConstraint(SpringLayout.SOUTH, spNonEnrolled, -140, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, spNonEnrolled, -100, SpringLayout.EAST, panelContent);
btnOp2 = new JButton("Thêm sinh viên");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnOp2, 10, SpringLayout.SOUTH, spNonEnrolled);
sl_panelContent.putConstraint(SpringLayout.WEST, btnOp2, 20, SpringLayout.WEST, spNonEnrolled);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnOp2, 36, SpringLayout.SOUTH, spNonEnrolled);
sl_panelContent.putConstraint(SpringLayout.EAST, btnOp2, -20, SpringLayout.EAST, spNonEnrolled);
btnOp2.setForeground(new Color(255, 255, 255));
btnOp2.setBackground(new Color(255, 99, 71));
btnOp2.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnOp2.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnOp2);
List<Attendance> listAttendance = AttendanceDAO.getAttendanceList();
Vector<String> temp = new Vector<String>();
boolean matched = false;
for (int i =0; i < listAttendance.size(); ++i){
Attendance a = listAttendance.get(i);
if (a.getmCourse().getmCourseID().equals(courseID)){
if (temp.size()>0){
for (int j = 0; j < temp.size(); ++j){
if (a.getmStudent().getmUsername().equals(temp.get(j))){
matched = true;
}
}
if (!matched){
temp.add(a.getmStudent().getmUsername());
}
matched = false;
}else{
temp.add(a.getmStudent().getmUsername());
}
}
}
List<User> lsu = UserDAO.getUserList();
for (int i = 0; i < lsu.size(); i++){
User u = lsu.get(i);
for (int j = 0; j <temp.size();++j){
if (u.getmUsername().equals(temp.get(j)) && u.getmType() == 0){
matched =true;
break;
}
}
if (!matched && u.getmType()==0){
dtm.addRow(new Object[]{new Boolean(false),u.getmUsername()});
}
matched = false;
}
panelContent.add(spNonEnrolled);
optionInput = 2;
Vector <Integer> tempAdd = new Vector <Integer>();
table.getModel().addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if (e.getFirstRow()!=-1 && e.getColumn() != -1 ){
tempAdd.add(e.getFirstRow());
}
}
});
btnOp2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (tempAdd.size()>0){
for (int i = 0; i< tempAdd.size();++i){
for (int k = 0; k < 15; ++k){
Attendance a1 = new Attendance();
a1.setmStudent(UserDAO.getUserInfo(dtm.getValueAt(tempAdd.get(i),1).toString()));
a1.setmCourse(CourseDAO.getCourse(editCourse));
a1.setmWeek(k+1);
Date dateDate = CourseDAO.getCourse(editCourse).getmDateStarted();
LocalDate date= LocalDate.parse(dateDate.toString());
//System.out.println(i+1);
date = date.plusDays(k*7);
Date dateAdd = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
a1.setmDate(dateAdd);
a1.setmStatus(0);
boolean res = AttendanceDAO.addNew(a1);
}
}
for (int i = 0; i< tempAdd.size()-1; ++i){
for (int j = i+1; j < tempAdd.size(); ++j){
if (tempAdd.get(i)<tempAdd.get(j)){
int temp = tempAdd.get(i);
tempAdd.set(i, tempAdd.get(j));
tempAdd.set(j, temp);
}
}
}
String info="";
for (int i = 0; i < tempAdd.size(); ++i){
info = info + dtm.getValueAt(tempAdd.get(i), 1) + "\n";
dtm.removeRow(tempAdd.get(i));
}
JOptionPane.showMessageDialog(null, "Thêm các sinh viên: \n"+info, "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
void addNewStudents(String courseID){
if(optionInput == 1){
panelContent.remove(spEnrolled);
panelContent.remove(btnOp1);
panelContent.validate();
panelContent.repaint();
}else if(optionInput == 2){
panelContent.remove(spNonEnrolled);
panelContent.remove(btnOp2);
panelContent.validate();
panelContent.repaint();
}else if (optionInput == 4){
panelContent.remove(btnExport);
panelContent.remove(btnImport);
panelContent.validate();
panelContent.repaint();
}
textFieldAddNew = new JTextField("MSSV");
sl_panelContent.putConstraint(SpringLayout.NORTH, textFieldAddNew, -300, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, textFieldAddNew, -350, SpringLayout.EAST, panelContent);
//sl_panelContent.putConstraint(SpringLayout.SOUTH, textFieldAddNew, -140, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, textFieldAddNew, -100, SpringLayout.EAST, panelContent);
textFieldAddNew.setFont(new Font("Segoe UI", Font.PLAIN, 18));
textFieldAddNew.setColumns(10);
textFieldAddName = new JTextField("Họ và tên");
sl_panelContent.putConstraint(SpringLayout.NORTH, textFieldAddName, 20, SpringLayout.SOUTH, textFieldAddNew);
sl_panelContent.putConstraint(SpringLayout.WEST, textFieldAddName, -350, SpringLayout.EAST, panelContent);
//sl_panelContent.putConstraint(SpringLayout.SOUTH, textFieldAddName, -140, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, textFieldAddName, -100, SpringLayout.EAST, panelContent);
textFieldAddName.setFont(new Font("Segoe UI", Font.PLAIN, 18));
textFieldAddName.setColumns(10);
btnOp3 = new JButton("Thêm sinh viên");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnOp3, 10, SpringLayout.SOUTH, textFieldAddName);
sl_panelContent.putConstraint(SpringLayout.WEST, btnOp3, 20, SpringLayout.WEST, textFieldAddName);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnOp3, 36, SpringLayout.SOUTH, textFieldAddName);
sl_panelContent.putConstraint(SpringLayout.EAST, btnOp3, -20, SpringLayout.EAST, textFieldAddName);
btnOp3.setForeground(new Color(255, 255, 255));
btnOp3.setBackground(new Color(255, 99, 71));
btnOp3.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnOp3.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(textFieldAddNew);
panelContent.add(textFieldAddName);
panelContent.add(btnOp3);
optionInput = 3;
btnOp3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
boolean matched = false;
if (textFieldAddNew.getText().equals("")|| textFieldAddName.getText().equals("") ){
JOptionPane.showMessageDialog(null, "Xin hãy điền đầy đủ thông tin.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
if(UserDAO.getUserInfo(textFieldAddNew.getText())== null){
//
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
digest.update(textFieldAddNew.getText().getBytes("utf8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] digestBytes = digest.digest();
String digestStr = javax.xml.bind.DatatypeConverter.printHexBinary(digestBytes);
User u = new User();
u.setmUsername(textFieldAddNew.getText());
u.setmPassword(digestStr);
u.setmType(0);
u.setmFullname(textFieldAddName.getText());
boolean res = UserDAO.addNew(u);
if (res == true) {
//JOptionPane.showMessageDialog(null, "Sinh viên đã được thêm vào CSDL.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
} else {
//JOptionPane.showMessageDialog(null, "Sinh viên không được thêm vào CSDL.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}
}
}
List<Attendance> listAttendance = AttendanceDAO.getAttendanceList();
for (int i =0; i < listAttendance.size(); ++i){
Attendance a = listAttendance.get(i);
if (a.getmCourse().getmCourseID().equals(courseID) && a.getmStudent().getmUsername().equals(textFieldAddNew.getText())){
matched = true;
break;
}
}
if (matched){
JOptionPane.showMessageDialog(null, "Sinh viên đã đăng ký môn học này.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else{
for (int i = 0; i < 15; i++){
Attendance a = new Attendance();
a.setmStudent(UserDAO.getUserInfo(textFieldAddNew.getText()));
a.setmCourse(CourseDAO.getCourse(editCourse));
a.setmWeek(i+1);
Date dateDate = CourseDAO.getCourse(editCourse).getmDateStarted();
LocalDate date= LocalDate.parse(dateDate.toString());
//System.out.println(i+1);
date = date.plusDays(i*7);
Date dateAdd = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
a.setmDate(dateAdd);
a.setmStatus(0);
boolean res = AttendanceDAO.addNew(a);
}
JOptionPane.showMessageDialog(null, "Thêm sinh viên thành công.", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
void addCSV(){
if(optionInput == 1){
panelContent.remove(spEnrolled);
panelContent.remove(btnOp1);
panelContent.validate();
panelContent.repaint();
}else if(optionInput == 2){
panelContent.remove(spNonEnrolled);
panelContent.remove(btnOp2);
panelContent.validate();
panelContent.repaint();
}else if (optionInput == 3){
panelContent.remove(textFieldAddNew);
panelContent.remove(textFieldAddName);
panelContent.remove(btnOp3);
panelContent.validate();
panelContent.repaint();
}
btnExport = new JButton("Export template");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnExport, -300, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, btnExport, -350, SpringLayout.EAST, panelContent);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnExport, -270, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, btnExport, -100, SpringLayout.EAST, panelContent);
btnExport.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnExport.setForeground(new Color(255, 255, 255));
btnExport.setBackground(new Color(255, 99, 71));
btnExport.setBorder(BorderFactory.createEmptyBorder());
btnImport = new JButton("Import CSV");
sl_panelContent.putConstraint(SpringLayout.NORTH, btnImport, 20, SpringLayout.SOUTH, btnExport);
sl_panelContent.putConstraint(SpringLayout.WEST, btnImport, 0, SpringLayout.WEST, btnExport);
sl_panelContent.putConstraint(SpringLayout.SOUTH, btnImport, 50, SpringLayout.SOUTH, btnExport);
sl_panelContent.putConstraint(SpringLayout.EAST, btnImport, 0, SpringLayout.EAST, btnExport);
btnImport.setFont(new Font("Segoe UI", Font.PLAIN, 18));
btnImport.setForeground(new Color(255, 255, 255));
btnImport.setBackground(new Color(255, 99, 71));
btnImport.setBorder(BorderFactory.createEmptyBorder());
panelContent.add(btnExport);
panelContent.add(btnImport);
optionInput=4;
btnExport.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Chọn đường dẫn lưu template");
String str = "MSSV, Họ và tên\n";
int result = fileChooser.showSaveDialog(panelContent);
if (result == JFileChooser.APPROVE_OPTION) {
// user selects a file
try {
PrintWriter fw = new PrintWriter(fileChooser.getSelectedFile()+".csv","UTF-8");
fw.write(str.toString());
fw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
btnImport.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Chọn đường dẫn lấy template");
int result = fileChooser.showOpenDialog(panelContent);
if (result == JFileChooser.APPROVE_OPTION) {
// user selects a file
try{
File selectedFile = fileChooser.getSelectedFile();
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(selectedFile), "UTF8"));
String str, strID, strName;
while ((str = in.readLine()) != null) {
int pos = str.indexOf(",");
strID = str.substring(0, pos);
strName = str.substring(pos+1,str.length());
if (strID.equals("MSSV")){
//Do nothing
}else if(strID.equals("") || strName.equals("")){
//Do nothing
}else{
User u = UserDAO.getUserInfo(strID);
if (u == null){
u = new User();
u.setmUsername(strID);
u.setmPassword(getSHA1pass(strID));
u.setmType(0);
u.setmFullname(strName);
boolean res = UserDAO.addNew(u);
}else{
}
for (int i = 0; i < 15; i++){
Attendance a = new Attendance();
a.setmStudent(UserDAO.getUserInfo(strID));
a.setmCourse(CourseDAO.getCourse(editCourse));
a.setmWeek(i+1);
Date dateDate = CourseDAO.getCourse(editCourse).getmDateStarted();
LocalDate date= LocalDate.parse(dateDate.toString());
//System.out.println(i+1);
date = date.plusDays(i*7);
Date dateAdd = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
a.setmDate(dateAdd);
a.setmStatus(0);
boolean res = AttendanceDAO.addNew(a);
}
}
//System.out.println(str);
//System.out.println(strID);
//System.out.println(strName);
}
in.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
JOptionPane.showMessageDialog(null, "Các sinh viên đã được thêm vào", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
void addAttendance(){
lblChooseCourse = new JLabel("Chọn môn học");
sl_panelContent.putConstraint(SpringLayout.NORTH, lblChooseCourse, 20, SpringLayout.NORTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.WEST, lblChooseCourse, 40, SpringLayout.WEST, panelContent);
lblChooseCourse.setBackground(new Color(255, 255, 255));
lblChooseCourse.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panelContent.add(lblChooseCourse);
Vector<String> course = new Vector<String>();
//course.add("");
if (listCourse.size()>0){
listCourse.clear();
}
listCourse = CourseDAO.getCourseList();
for(int i=0; i< listCourse.size(); i++){
Course c= listCourse.get(i);
course.addElement(c.getmCourseID()+" - "+ c.getmName());
}
comboBoxAttendance = new JComboBox(course);
sl_panelContent.putConstraint(SpringLayout.EAST, comboBoxAttendance, -40, SpringLayout.EAST, panelContent);
comboBoxAttendance.setFont(new Font("Segoe UI", Font.PLAIN, 18));
sl_panelContent.putConstraint(SpringLayout.NORTH, comboBoxAttendance, -5, SpringLayout.NORTH, lblChooseCourse);
sl_panelContent.putConstraint(SpringLayout.WEST, comboBoxAttendance, 10, SpringLayout.EAST, lblChooseCourse);
sl_panelContent.putConstraint(SpringLayout.SOUTH, comboBoxAttendance, 5, SpringLayout.SOUTH, lblChooseCourse);
//comboBoxAttendance.setEditable(true);
panelContent.add(comboBoxAttendance);
//String colNames[] = {"MSSV", "Tuần 1","Tuần 2","Tuần 3","Tuần 4","Tuần 5","Tuần 6","Tuần 7","Tuần 8","Tuần 9","Tuần 10","Tuần 11","Tuần 12","Tuần 13","Tuần 14","Tuần 15"};
String colNames[] = {"MSSV", "T1","T2","T3","T4","T5","T6","T7","T8","T9","T10","T11","T12","T13","T14","T15"};
Object[][] data = {};
DefaultTableModel dtmAttendance;
dtmAttendance = new DefaultTableModel(data,colNames);
JTable table = new JTable(dtmAttendance){
@Override
public Class<?> getColumnClass(int columnIndex) {
Class type = String.class;
switch (columnIndex) {
case 0:
type = String.class;
break;
case 1:
type = Boolean.class;
break;
case 2:
type = Boolean.class;
break;
case 3:
type = Boolean.class;
break;
case 4:
type = Boolean.class;
break;
case 5:
type = Boolean.class;
break;
case 6:
type = Boolean.class;
break;
case 7:
type = Boolean.class;
break;
case 8:
type = Boolean.class;
break;
case 9:
type = Boolean.class;
break;
case 10:
type = Boolean.class;
break;
case 11:
type = Boolean.class;
break;
case 12:
type = Boolean.class;
break;
case 13:
type = Boolean.class;
break;
case 14:
type = Boolean.class;
break;
case 15:
type = Boolean.class;
break;
}
return type;
}
};
spAttendance = new JScrollPane(table);
table.setFont(new Font("Segoe UI", Font.PLAIN, 16));
table.setRowHeight(30);
JTableHeader header = table.getTableHeader();
header.setBackground(new Color(255, 140, 0));
header.setForeground(Color.white);
header.setFont(new Font("Segoe UI", Font.PLAIN, 16));
sl_panelContent.putConstraint(SpringLayout.NORTH, spAttendance, 100, SpringLayout.SOUTH, comboBoxAttendance);
sl_panelContent.putConstraint(SpringLayout.WEST, spAttendance, 40, SpringLayout.WEST, panelContent);
sl_panelContent.putConstraint(SpringLayout.SOUTH, spAttendance, -40, SpringLayout.SOUTH, panelContent);
sl_panelContent.putConstraint(SpringLayout.EAST, spAttendance, -40, SpringLayout.EAST, panelContent);
panelContent.add(spAttendance);
List<Attendance> listAttendance = AttendanceDAO.getAttendanceList();
Vector<String> temp = new Vector<String>();
boolean matched = false;
for (int i =0; i < listAttendance.size(); ++i){
Attendance a = listAttendance.get(i);
if (a.getmCourse().getmCourseID().equals(listCourse.get(comboBoxAttendance.getSelectedIndex()).getmCourseID())){
if (temp.size()>0){
for (int j = 0; j < temp.size(); ++j){
if (a.getmStudent().getmUsername().equals(temp.get(j))){
matched = true;
}
}
if (!matched){
temp.add(a.getmStudent().getmUsername());
}
matched = false;
}else{
temp.add(a.getmStudent().getmUsername());
}
}
}
for (int i = 0; i <temp.size();++i){
boolean attendance[] = {false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false};
for (int j = 0; j< listAttendance.size(); ++j){
Attendance a = listAttendance.get(j);
System.out.println(a.getmStudent().getmUsername());
System.out.println(temp.get(i));
System.out.println(a.getmStudent().getmUsername());
System.out.println(listCourse.get(comboBoxAttendance.getSelectedIndex()).getmCourseID());
if (a.getmStudent().getmUsername().equals(temp.get(i))&&
a.getmCourse().getmCourseID().equals(listCourse.get(comboBoxAttendance.getSelectedIndex()).getmCourseID())){
if(a.getmStatus() == 1){
attendance[a.getmWeek()-1] = true;
}
}
}
dtmAttendance.addRow(new Object[]{temp.get(i),
new Boolean(attendance[0]),
new Boolean(attendance[1]),
new Boolean(attendance[2]),
new Boolean(attendance[3]),
new Boolean(attendance[4]),
new Boolean(attendance[5]),
new Boolean(attendance[6]),
new Boolean(attendance[7]),
new Boolean(attendance[8]),
new Boolean(attendance[9]),
new Boolean(attendance[10]),
new Boolean(attendance[11]),
new Boolean(attendance[12]),
new Boolean(attendance[13]),
new Boolean(attendance[14])
});
if (temp.size()>0){
temp.clear();
}
}
comboBoxAttendance.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
int addColor = 0;
dtmAttendance.setDataVector(null,colNames);
List<Attendance> listAttendance = AttendanceDAO.getAttendanceList();
Vector<String> temp = new Vector<String>();
boolean matched = false;
editCourse = listCourse.get(comboBoxAttendance.getSelectedIndex()).getmCourseID();
for (int i =0; i < listAttendance.size(); ++i){
Attendance a = listAttendance.get(i);
if (a.getmCourse().getmCourseID().equals(listCourse.get(comboBoxAttendance.getSelectedIndex()).getmCourseID())){
if (temp.size()>0){
for (int j = 0; j < temp.size(); ++j){
if (a.getmStudent().getmUsername().equals(temp.get(j))){
matched = true;
}
}
if (!matched){
temp.add(a.getmStudent().getmUsername());
}
matched = false;
}else{
temp.add(a.getmStudent().getmUsername());
}
}
}
for (int i = 0; i <temp.size();++i){
boolean attendance[] = {false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false};
for (int j = 0; j< listAttendance.size(); ++j){
Attendance a = listAttendance.get(j);
if (a.getmStudent().getmUsername().equals(temp.get(i))&&
a.getmCourse().getmCourseID().equals(listCourse.get(comboBoxAttendance.getSelectedIndex()).getmCourseID())){
if(a.getmStatus() == 1){
attendance[a.getmWeek()-1] = true;
}
}
}
dtmAttendance.addRow(new Object[]{temp.get(i),
new Boolean(attendance[0]),
new Boolean(attendance[1]),
new Boolean(attendance[2]),
new Boolean(attendance[3]),
new Boolean(attendance[4]),
new Boolean(attendance[5]),
new Boolean(attendance[6]),
new Boolean(attendance[7]),
new Boolean(attendance[8]),
new Boolean(attendance[9]),
new Boolean(attendance[10]),
new Boolean(attendance[11]),
new Boolean(attendance[12]),
new Boolean(attendance[13]),
new Boolean(attendance[14])
});
}
panelContent.validate();
panelContent.repaint();
}
});
table.getModel().addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if (e.getFirstRow()!=-1 && e.getColumn() != -1 ){
table.getModel().getValueAt(e.getFirstRow(), e.getColumn());
User u = UserDAO.getUserInfo(table.getModel().getValueAt(e.getFirstRow(), 0).toString());
if (u != null){
Iterator<Attendance> lsa = u.getmAttendances().iterator();
while(lsa.hasNext()){
Attendance a = lsa.next();
//System.out.println(listCourse.get(comboBoxAttendance.getSelectedIndex()).getmCourseID());
//System.out.println(a.getmWeek());
//System.out.println(e.getColumn());
if(a.getmCourse().getmCourseID().equals(listCourse.get(comboBoxAttendance.getSelectedIndex()).getmCourseID()) &&
a.getmWeek() == e.getColumn()){
//System.out.println(table.getModel().getValueAt(e.getFirstRow(), e.getColumn()).toString());
if (table.getModel().getValueAt(e.getFirstRow(), e.getColumn()).equals(true)){
a.setmStatus(1);
JOptionPane.showMessageDialog(null, "Đánh dấu 'có mặt' sinh viên có MSSV "+table.getModel().getValueAt(e.getFirstRow(), 0), "Thông báo", JOptionPane.INFORMATION_MESSAGE);
}else if(table.getModel().getValueAt(e.getFirstRow(), e.getColumn()).equals(false)){
JOptionPane.showMessageDialog(null, "Đánh dấu 'vắng' sinh viên có MSSV "+table.getModel().getValueAt(e.getFirstRow(), 0), "Thông báo", JOptionPane.INFORMATION_MESSAGE);
a.setmStatus(2);
}
boolean res = AttendanceDAO.update(a);
}
}
}
}
}
});
}
String getSHA1pass(String passStr){
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
digest.update(passStr.getBytes("utf8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] digestBytes = digest.digest();
String digestStr = javax.xml.bind.DatatypeConverter.printHexBinary(digestBytes);
return digestStr;
}
}
class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
//setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
setFont(new Font("Segoe UI", Font.PLAIN, 16));
setForeground(new Color(0, 191, 255));
setBackground(new Color(255, 255, 255));
setBorder(BorderFactory.createEmptyBorder());
setText((value == null) ? "" : value.toString());
return this;
}
}
class ButtonEditor extends DefaultCellEditor {
protected JButton button;
private String label;
private boolean isPushed;
private String courseID;
public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton();
//button.setOpaque(true);
button.setFont(new Font("Segoe UI", Font.PLAIN, 16));
button.setForeground(new Color(0, 191, 255));
button.setBackground(new Color(240,248,255));
button.setBorder(BorderFactory.createEmptyBorder());
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (isSelected) {
button.setForeground(new Color(255, 140, 0));
} else {
button.setForeground(new Color(0, 191, 255));
}
label = (value == null) ? "" : value.toString();
courseID = (value == null) ? "" : table.getModel().getValueAt(row, 0).toString();
button.setText(label);
isPushed = true;
return button;
}
@Override
public Object getCellEditorValue() {
if (isPushed) {
//JOptionPane.showMessageDialog(button, courseID + ": Ouch!");
}
isPushed = false;
return label;
}
@Override
public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}
}
| [
"[email protected]"
] | |
bf3008576599ef54ccab9caa62788b3ce830eb9e | 7c3d483e4988a046dd25c2dc36ccce576c2c6daf | /Practice2/datastructures/Sorts.java | 558e8608a181ab662b682f8fbb517efa85382d6f | [] | no_license | pavan0169/myplacementscodes | cf909de5787e15a10a5c3948fa9795190551b974 | e82974090a96948e6266d0663748687cc6340d88 | refs/heads/main | 2023-01-22T00:28:08.358310 | 2020-11-25T08:39:41 | 2020-11-25T08:39:41 | 315,872,960 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,072 | java | package datastructures;
import java.util.*;
public class Sorts
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0; i<n; i++)
{
arr[i]=sc.nextInt();
}
int[] out=mergeSort(arr);
for(int i=0; i<n; i++)
{
System.out.print(out[i]+" ");
}
}
public static int[] bubbleSort(int[] arr)
{
for(int i=0; i<arr.length-1; i++)
{
for(int j=0; j<arr.length-1-i; j++)
{
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
return arr;
}
public static int[] insertionSort(int[] arr)
{
for(int i=1; i<arr.length; i++)
{
int value=arr[i];
int index=i;
while(index>0 && arr[index-1]>value)
{
arr[index]=arr[index-1];
index--;
}
arr[index]=value;
}
return arr;
}
public static int[] selectionSort(int[] arr)
{
for(int i=0; i<arr.length-1; i++)
{
for(int j=i+1; j<arr.length; j++)
{
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
return arr;
}
public static int[] quickSort(int[] arr)
{
return quickSort(arr, 0, arr.length-1);
}
public static int[] quickSort(int[] arr, int first, int last)
{
if(first<last)
{
int pindex=partition(arr,first,last);
quickSort(arr,first,pindex-1);
quickSort(arr,pindex+1,last);
}
return arr;
}
public static int partition(int[] arr, int first,int last)
{
int index=first;
int pivot=arr[last];
for(int i=first; i<last; i++)
{
if(arr[i]<pivot)
{
int value=arr[i];
arr[i]=arr[index];
arr[index]=value;
index++;
}
}
int value=arr[index];
arr[index]=arr[last];
arr[last]=value;
return index;
}
public static int[] mergeSort(int[] arr)
{
mergeSort(arr, 0, arr.length-1);
return arr;
}
static void mergeSort(int[] arr, int first, int last)
{
if(first<last)
{
int mid=(first+last)/2;
mergeSort(arr, first, mid);
mergeSort(arr, mid+1, last);
merger(arr,first,mid,last);
}
}
public static void merger(int[] arr, int lower, int middle, int higher)
{
int l=middle-lower+1;
int r=higher-middle;
//create temp array
int[] left=new int[l];
int[] right=new int[r];
//add all the elements into temp arrays
for(int i=0; i<l; i++)
{
left[i]=arr[lower+i];
}
for(int j=0; j<r; j++)
{
right[j]=arr[middle+1+j];
}
int i=0;
int j=0;
int k=lower;
while (i < l && j < r)
{
if (left[i] <= right[j])
{
arr[k] = left[i];
i++;
}
else
{
arr[k] = right[j];
j++;
}
k++;
}
while (i < l)
{
arr[k] = left[i];
i++;
k++;
}
while(j<r)
{
arr[k] = right[j];
j++;
k++;
}
}
}
| [
"[email protected]"
] | |
99679564148e99001b2e88de8a142914d2cd304e | 54eb32d6bd74d6e8b80d6e0bd1b0638422f0d505 | /Practica9i/src/Practica9i/DispositivoElectronico.java | 786f678feb1b22b0c55a05db3b43911ff7222460 | [] | no_license | MasMat2/LaboratorioJavaSabado | 8aab5d6b0c76d0fd552b0bfc57091e07d752bcc2 | baa9cbbcb1e6a20c8fdc816a7437492af281b898 | refs/heads/master | 2022-09-28T12:24:13.831529 | 2020-06-06T13:07:01 | 2020-06-06T13:07:01 | 258,034,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 139 | java | package practica9i;
public interface DispositivoElectronico {
public abstract String encender();
public abstract void apagar();
} | [
"[email protected]"
] | |
b8cdf3c1e9b1a155beeb6da7d3d7c160f7d7c721 | cab2be96e03ddfca1f76108741c8cc8ffdf49be2 | /Codeforces/B/734B/AntonDigits.java | ce5f2536180278ff5f213226b6d6c134a1510663 | [] | no_license | ThePinger/ACM | ceeb3b36fc5609d869ba12f7b8783ffd87ed435b | 955836e9648a2328cc9638e5af21cec5f4fb5143 | refs/heads/master | 2021-01-22T21:59:34.770120 | 2019-08-20T07:57:28 | 2019-08-20T07:57:28 | 92,749,931 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 514 | java | //734B
//Anton and Digits
import java.util.*;
public class AntonDigits
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int k2 = sc.nextInt();
int k3 = sc.nextInt();
int k5 = sc.nextInt();
int k6 = sc.nextInt();
long ans = Math.min(k2, Math.min(k5, k6)) * 256;
k2 -= Math.min(k2, Math.min(k5, k6));
ans += Math.min(k2, k3) * 32;
System.out.println(ans);
}
} | [
"[email protected]"
] | |
7bc5cc033222156a599cb8b8dda60ba5de469a9d | 9f0a64afdf499ed887b78c9e39e464cf5676cb9c | /src/test/java/com/galebo/HttpTookit.java | 7a39a57719804363cfdb02603f8aac048ac72cf5 | [] | no_license | galebo/baidu_8_background | 0d8c2aed8b568e1c2229e04e1b08cd38b9420593 | a940cdc61c64a94d021fbe1274194b89505f8be7 | refs/heads/master | 2021-01-22T13:38:13.842395 | 2015-01-16T04:49:04 | 2015-01-16T04:49:04 | 23,899,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,609 | java | package com.galebo;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
public final class HttpTookit {
private static Logger log = Logger.getLogger(HttpTookit.class);
/**
* 执行一个HTTP GET请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @return 返回请求响应的HTML
*/
public static String doGet(Logger logger, String url) {
if (logger == null)
logger = log;
String response = null;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
try {
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
params.setConnectionTimeout(1000 * 10);// 连接超时
params.setSoTimeout(1000 * 60*3);// 读数据超时
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response =IOUtils.toString(method.getResponseBodyAsStream());
} else {
logger.error("执行HTTP Get请求" + url + "时,发生异常!" + method.getResponseBodyAsString());
}
} catch (IOException e) {
logger.error("执行HTTP Get请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response;
}
}
| [
"[email protected]"
] | |
61a3bb2e20911c5dc732bd718edfaa005db80ce7 | 5cbcd626f26f16fe7d8a41de58dc94f549814454 | /src/main/java/com/example/crud/commons/GenericServiceImp.java | 785a39f9b3526ae7b77c12b4bdcc7bac7679da4e | [] | no_license | santiagowac/Java-CRUD-con-Spring-Boot | c7ead6474d2562a5a6fe48eb6b2e62e4e4ab9d6c | fcf657d8bb99064e38dcc495aec647578252f912 | refs/heads/master | 2020-12-18T16:07:34.976050 | 2020-01-21T22:02:16 | 2020-01-21T22:02:16 | 235,449,012 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 981 | java | package com.example.crud.commons;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;
@Service
public abstract class GenericServiceImp<T, ID extends Serializable> implements GenericService<T, ID> {
@Override
public T save(T entity) {
return getDao().save(entity);
}
@Override
public void delete(ID id) {
getDao().deleteById(id);
}
@Override
public T get(ID id) {
Optional<T> obj = getDao().findById(id);
if(obj.isPresent()){
return obj.get();
}
return null;
}
@Override
public List<T> getAll() {
List<T> returnList = new ArrayList<>();
getDao().findAll().forEach(obj -> returnList.add(obj));
return returnList;
}
public abstract CrudRepository<T, ID> getDao();
} | [
"[email protected]"
] | |
bec4c17a69a81cff380229e0d1075eb4c920e79a | 6b97c1e0c10b749b66c2eb23be679eec179a746f | /JavaSpades/src/jspades/util/tick.java | 5f57fbc54e2404d0b3c1a14b9bd606d86528bd18 | [] | no_license | HoboHob/JavaSpades | 50d7d6af2351da271ffdae1db8e60fea3ae71bf8 | 245774019a7523aaa17228003d6d923b18fafb74 | refs/heads/master | 2020-12-25T19:14:35.978477 | 2012-12-13T04:08:34 | 2012-12-13T04:08:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 488 | java | package jspades.util;
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.opengl.Display;
/*
* Class description:
* A utility class for functions called in either the render method or update method
* of the main class
* Last Changed:
* 11/13/2012
* Reason:
* Created
*/
public class tick {
public static void clearBuffers()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
public static void updateDisplay()
{
Display.update();
Display.sync(60);
}
}
| [
"[email protected]"
] | |
3591db3ecd87b3ab606da63351d2273e2da25b7a | af920633d2185b6ec653f28f1779437158a6212a | /generated/java/gapic-google-cloud-speech-v1beta1/src/test/java/com/google/cloud/speech/v1beta1/SpeechSmokeTest.java | cb0296a92ad84cdbb36cc726ad0e06a26eb57d55 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | vkedia/api-client-staging | 895f462328f792c32dc74aa90cb6500b75dd06ac | a5a637bbcccfcbd14b483a88f78e5272275128af | refs/heads/master | 2020-06-27T13:10:54.627081 | 2018-02-27T01:10:55 | 2018-02-27T01:10:55 | 97,057,129 | 0 | 0 | null | 2017-07-12T22:29:30 | 2017-07-12T22:29:30 | null | UTF-8 | Java | false | false | 2,101 | java | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.speech.v1beta1;
import com.google.cloud.speech.v1beta1.RecognitionConfig.AudioEncoding;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
@javax.annotation.Generated("by GAPIC")
public class SpeechSmokeTest {
public static void main(String args[]) {
Logger.getLogger("").setLevel(Level.WARNING);
try {
executeNoCatch();
System.out.println("OK");
} catch (Exception e) {
System.err.println("Failed with exception:");
e.printStackTrace(System.err);
System.exit(1);
}
}
public static void executeNoCatch() throws Exception {
try (SpeechClient client = SpeechClient.create()) {
String languageCode = "en-US";
int sampleRate = 44100;
RecognitionConfig.AudioEncoding encoding = RecognitionConfig.AudioEncoding.FLAC;
RecognitionConfig config =
RecognitionConfig.newBuilder()
.setLanguageCode(languageCode)
.setSampleRate(sampleRate)
.setEncoding(encoding)
.build();
String uri = "gs://gapic-toolkit/hello.flac";
RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(uri).build();
SyncRecognizeResponse response = client.syncRecognize(config, audio);
System.out.println(
ReflectionToStringBuilder.toString(response, ToStringStyle.MULTI_LINE_STYLE));
}
}
}
| [
"[email protected]"
] | |
d01016fe37d87f843cff7c85368af6a21a0ce7e1 | 408d81d7154fc94042f7733a7ac2163547b42015 | /Prog02B/mobile/src/test/java/com/example/cookmilk/prog02b/ExampleUnitTest.java | 5d63660253a0fe17615252648b602aa0935002fb | [] | no_license | cs160-berkeley/prog-02-represent-cookmilk | da18073021591aac5c39f1e411fb0127e7c312a1 | 899c89533caa83be45b351bc5029e925ca4341e9 | refs/heads/master | 2020-12-31T03:42:18.533227 | 2016-03-14T06:52:06 | 2016-03-14T06:52:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 321 | java | package com.example.cookmilk.prog02b;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
00f9f16df61a094eb84a93b42803f6499a5274a0 | 2f717365c020a020e22ce58aceabaa2d2bebd5fb | /rbac_demo/rbac-manager/src/main/java/com/zhku/mh/rbac/service/impl/UserServiceImpl.java | e8f07140c8ea39055901d9183a41e11d19300c7b | [] | no_license | Howie-mai/rbac_demo | 64e524619772be028dca3775b8117411917da289 | 808d9311d72144f9b618b64688da6f1009cd0961 | refs/heads/master | 2022-12-22T00:35:32.321587 | 2019-12-09T09:16:11 | 2019-12-09T09:16:11 | 226,830,075 | 0 | 0 | null | 2022-12-16T02:51:02 | 2019-12-09T09:10:32 | JavaScript | UTF-8 | Java | false | false | 1,650 | java | package com.zhku.mh.rbac.service.impl;
import com.zhku.mh.rbac.bean.User;
import com.zhku.mh.rbac.dao.UserDao;
import com.zhku.mh.rbac.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* ClassName:
* Time:2019/12/4 15:55
* Description:
* Author: mh
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public List<User> queryAll() {
return userDao.queryAll();
}
public User query4Login(User user) {
return userDao.query4Login(user);
}
public List<User> pageQueryData(Map<String, Object> map) {
return userDao.pageQueryData(map);
}
public int pageQueryCount(Map<String, Object> map) {
return userDao.pageQueryCount(map);
}
public void insertUser(User user) {
userDao.insertUser(user);
}
public User queryById(Integer id) {
return userDao.queryById(id);
}
public void updateUser(User user) {
userDao.updateUser(user);
}
public void deleteUserById(Integer id) {
userDao.deleteUserById(id);
}
public void deleteUsers(Map<String, Object> map) {
userDao.deleteUsers(map);
}
public void insertUserRoles(Map<String, Object> map) {
userDao.insertUserRoles(map);
}
public void deleteUserRoles(Map<String, Object> map) {
userDao.deleteUserRoles(map);
}
public List<Integer> queryRoleidsByUserid(Integer id) {
return userDao.queryRoleidsByUserid(id);
}
}
| [
"[email protected]"
] | |
51cf1b23a5a4e28ff2fd786efacdcfdf72e11672 | b1133e34c8ce32bf8ae41c847e6af0a995a6645e | /src/main/java/com/how2java/tmall/mapper/SellerMapper.java | de2bd087e9c6f6ea43d2e5d72d11ffa5d79c6a42 | [] | no_license | ChenXiao-sjtu/OnlineShoppingMall | 4d2fdf599ec9fc8e2208d801d928ffe1033c19c2 | 6fc7f68c3c87cb55e1f54bd79b2d9703174033fd | refs/heads/master | 2023-01-01T02:06:34.840902 | 2019-07-16T12:21:51 | 2019-07-16T12:21:51 | 197,154,935 | 7 | 2 | null | 2022-12-16T05:00:57 | 2019-07-16T08:39:56 | Java | UTF-8 | Java | false | false | 490 | java | package com.how2java.tmall.mapper;
import com.how2java.tmall.pojo.Seller;
import com.how2java.tmall.pojo.SellerExample;
import java.util.List;
public interface SellerMapper {
int deleteByPrimaryKey(Integer id);
int insert(Seller record);
int insertSelective(Seller record);
List<Seller> selectByExample(SellerExample example);
Seller selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Seller record);
int updateByPrimaryKey(Seller record);
} | [
"[email protected]"
] | |
52820a00541a27771fb377118484add4c41a9f3d | 6229ba023bc7496c7539e52f51713340d9d13da5 | /demo-basics-api/src/main/java/com/example/utils/Weather/OneWeekWeather.java | 62768f3a3b7d4332f458746c94bea1e50b770e89 | [] | no_license | lianmengliang/practiceTest | 946de2fafb31aa8ec99ea0ef161ea043d804c1bd | 3f2bb488443cf92411f1c576e24b3ff7912e3dd7 | refs/heads/master | 2023-04-13T07:13:44.738226 | 2023-04-09T04:17:56 | 2023-04-09T04:18:19 | 230,899,705 | 1 | 0 | null | 2022-11-16T12:15:20 | 2019-12-30T10:58:26 | Java | UTF-8 | Java | false | false | 561 | java | package com.example.utils.Weather;
import lombok.Data;
import java.util.Date;
/**
* @Author : Leo
* @Date : 2020/11/4 16:44
* @Desc:
*/
@Data
public class OneWeekWeather {
//更新时间
private Date date ;
//白天天气图标
private String dayIcon;
//星期几
private String week;
//夜晚天气图标
private String nightIcon;
//天气情况
private String weather;
//风力情况
private String wind;
//最高温
private String tempHigh;
//最低温
private String tempLow;
}
| [
"[email protected]"
] | |
1eea6b7860005c56604e7276422ee82798e9625e | cb4a3a0f40c457479c33804336921dbbc3970290 | /src/main/java/com/outdoorsy/challenge/service/RentalService.java | f9f52c06f56f024511a23437642fa422db337e9e | [] | no_license | tasmana/outdoorsy-challenge | 18eb14beeaee2c29448ab07e80bd697791d18f32 | 56e8609e9af0dd7ee64bec892632007c299dc91d | refs/heads/master | 2022-12-07T23:32:25.994822 | 2020-08-10T05:57:59 | 2020-08-10T05:57:59 | 286,309,638 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,824 | java | package com.outdoorsy.challenge.service;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.outdoorsy.challenge.domain.Rental;
import com.outdoorsy.challenge.dto.SearchRequestParameters;
import com.outdoorsy.challenge.exception.RentalNotFoundException;
import com.outdoorsy.challenge.repository.RentalRepository;
@Service
public class RentalService {
@Value("${rental.near.distance:100}")
private Integer nearDistance;
@Autowired
private RentalRepository rentalRepository;
public Rental findById(Integer id) throws RentalNotFoundException {
return rentalRepository.findById(id).orElseThrow(() -> new RentalNotFoundException(id));
}
public Page<Rental> search(SearchRequestParameters searchRequestParameters, Pageable pageable) {
if (searchRequestParameters.getPrice() != null) {
return rentalRepository
.findAllByPricePerDayIsBetween(searchRequestParameters.getPrice().getMin(), searchRequestParameters.getPrice().getMax(), pageable);
} else if (!CollectionUtils.isEmpty(searchRequestParameters.getIds())) {
return rentalRepository.findAllByIdIn(searchRequestParameters.getIds(), pageable);
} else if (isNotEmpty(searchRequestParameters.getNear())) {
String[] coordinates = searchRequestParameters.getNear().split(",");
return rentalRepository.findNearRentals(nearDistance, Double.parseDouble(coordinates[0]), Double.parseDouble(coordinates[1]), pageable);
}
return rentalRepository.findAll(pageable);
}
}
| [
"[email protected]"
] | |
b8b8fc5367f977d0027c5cbf91ccbb7592a67b25 | ef0c1514e9af6de3ba4a20e0d01de7cc3a915188 | /sdk/automation/azure-resourcemanager-automation/src/main/java/com/azure/resourcemanager/automation/implementation/SoftwareUpdateConfigurationRunImpl.java | 53502b5a12d4745ccecdbc501a93b17ba5517c18 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"CC0-1.0",
"BSD-3-Clause",
"UPL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | Azure/azure-sdk-for-java | 0902d584b42d3654b4ce65b1dad8409f18ddf4bc | 789bdc6c065dc44ce9b8b630e2f2e5896b2a7616 | refs/heads/main | 2023-09-04T09:36:35.821969 | 2023-09-02T01:53:56 | 2023-09-02T01:53:56 | 2,928,948 | 2,027 | 2,084 | MIT | 2023-09-14T21:37:15 | 2011-12-06T23:33:56 | Java | UTF-8 | Java | false | false | 2,756 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.automation.implementation;
import com.azure.resourcemanager.automation.fluent.models.SoftwareUpdateConfigurationRunInner;
import com.azure.resourcemanager.automation.models.SoftwareUpdateConfigurationRun;
import com.azure.resourcemanager.automation.models.SoftwareUpdateConfigurationRunTasks;
import com.azure.resourcemanager.automation.models.UpdateConfigurationNavigation;
import java.time.OffsetDateTime;
public final class SoftwareUpdateConfigurationRunImpl implements SoftwareUpdateConfigurationRun {
private SoftwareUpdateConfigurationRunInner innerObject;
private final com.azure.resourcemanager.automation.AutomationManager serviceManager;
SoftwareUpdateConfigurationRunImpl(
SoftwareUpdateConfigurationRunInner innerObject,
com.azure.resourcemanager.automation.AutomationManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public String name() {
return this.innerModel().name();
}
public String id() {
return this.innerModel().id();
}
public UpdateConfigurationNavigation softwareUpdateConfiguration() {
return this.innerModel().softwareUpdateConfiguration();
}
public String status() {
return this.innerModel().status();
}
public String configuredDuration() {
return this.innerModel().configuredDuration();
}
public String osType() {
return this.innerModel().osType();
}
public OffsetDateTime startTime() {
return this.innerModel().startTime();
}
public OffsetDateTime endTime() {
return this.innerModel().endTime();
}
public Integer computerCount() {
return this.innerModel().computerCount();
}
public Integer failedCount() {
return this.innerModel().failedCount();
}
public OffsetDateTime creationTime() {
return this.innerModel().creationTime();
}
public String createdBy() {
return this.innerModel().createdBy();
}
public OffsetDateTime lastModifiedTime() {
return this.innerModel().lastModifiedTime();
}
public String lastModifiedBy() {
return this.innerModel().lastModifiedBy();
}
public SoftwareUpdateConfigurationRunTasks tasks() {
return this.innerModel().tasks();
}
public SoftwareUpdateConfigurationRunInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.automation.AutomationManager manager() {
return this.serviceManager;
}
}
| [
"[email protected]"
] | |
ac26f0561ff2774e82110e2e1737d1e9ade75e31 | 350c9db526574b1583e65990611f3eeca256d633 | /hospital/src/main/java/com/solvd/lambda/ListToSort.java | 445c4ff04f963436a52dfd69e4066b8d7459f6a5 | [] | no_license | CFacu/java-test-automation | 386657bb1e066bd3fa972139a142d99606133453 | bfd1ba7dbc4b5f8eb4542f8f574b5a26825c39c3 | refs/heads/master | 2022-11-27T01:59:25.918812 | 2020-03-10T04:53:40 | 2020-03-10T04:53:40 | 232,844,691 | 0 | 0 | null | 2022-11-16T00:41:33 | 2020-01-09T15:48:58 | Java | UTF-8 | Java | false | false | 360 | java | package com.solvd.lambda;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListToSort<T extends Comparable> {
public List<T> list;
public ListToSort(T[] array) {
list = new ArrayList<T>(Arrays.asList(array));
}
public void sort(LambdaSort lambdaSort) {
lambdaSort.sort(list);
}
}
| [
"[email protected]"
] | |
1d5ffefaa3b31301397865c33a878b2ab847245b | b8e205dfdd362ca3142ee48f840dcf09058de89d | /app/src/main/java/com/qinnovation/sample/ui/home/HomePagePresenter.java | 11f846ad526a548a374107ded46d06a9c6cdef21 | [] | no_license | mohamed-ashik169/SampleEvent | a15781219ef2d787f17feb1b2985687908932f44 | 99d2fde176a6510b51da874a62418001d4f88c59 | refs/heads/master | 2021-08-31T12:23:52.963030 | 2017-12-21T08:40:53 | 2017-12-21T08:40:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,314 | java | package com.qinnovation.sample.ui.home;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.qinnovation.sample.helper.mvp.BasePresenter;
import com.qinnovation.sample.master.model.MenuDetail;
import com.qinnovation.sample.preferences.PreferenceManager;
import com.qinnovation.sample.ui.speaker.ISpeakerDataManager;
import com.qinnovation.sample.ui.speaker.SpeakerDataManager;
import com.qinnovation.sample.ui.speaker.SpeakerDetail;
import java.util.List;
import static com.qinnovation.sample.utils.Constants.MESSAGE;
import static com.qinnovation.sample.utils.Constants.SUCCESS;
/**
* Created by qinnovation on 12/17/17.
*/
public class HomePagePresenter extends BasePresenter<HomePageContract.View> implements HomePageContract.Presenter {
public HomePagePresenter(HomePageContract.View view, SQLiteDatabase sqLiteDatabase, PreferenceManager preferenceManager) {
super(view, sqLiteDatabase, preferenceManager);
}
public void fetchMenuList() {
if (!isViewAttached()) {
return;
}
view.progressBarVisibility(true);
IMenuDataManager menuDataManager = new MenuDataManager(sqLiteDatabase);
Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
if (!HomePagePresenter.this.isViewAttached()) {
return false;
}
Bundle data = message.getData();
boolean success = data.getBoolean(SUCCESS);
String msg = data.getString(MESSAGE, "Unknown message");
if (!success) {
view.showToastMessage(msg);
} else {
//noinspection unchecked
view.populateMenuList((List<MenuDetail>) message.obj);
}
view.progressBarVisibility(false);
return false;
}
});
menuDataManager.getLocalMenuDetailList(handler);
}
@Override
public void fetchSpeakerList(int limitCount) {
if (!isViewAttached()) {
return;
}
view.progressBarVisibility(true);
ISpeakerDataManager speakerDataManager = new SpeakerDataManager(sqLiteDatabase);
Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
if (!HomePagePresenter.this.isViewAttached()) {
return false;
}
Bundle data = message.getData();
boolean success = data.getBoolean(SUCCESS);
String msg = data.getString(MESSAGE, "Unknown message");
if (!success) {
view.showToastMessage(msg);
} else {
//noinspection unchecked
view.populateSpeakerList((List<SpeakerDetail>) message.obj);
}
view.progressBarVisibility(false);
return false;
}
});
speakerDataManager.getOfflineSpeakerList(handler, 3);
}
}
| [
"[email protected]"
] | |
dce3877d1ac1b01b40134dada8d566e321da03a2 | 06ae82a46a97d7cab4968eac702b57e0d2dfbe1f | /smartmeal/src/com/example/smartmeal/tab/Submitted.java | 022df707a5b451a79bd67d598c832598d920d4ac | [] | no_license | sunkid06/smart-meal | 68e798b9b8d7254701a84acf758aa3b2ebb05a17 | 243b2aff8aae074ef74ed2dbd69656dbfe23439c | refs/heads/master | 2021-01-20T21:40:52.751718 | 2013-11-27T06:42:24 | 2013-11-27T06:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,341 | java | package com.example.smartmeal.tab;
import java.text.SimpleDateFormat;
import java.util.Locale;
import vn.hust.smie.Dish;
import vn.hust.smie.History;
import vn.hust.smie.Meal;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import com.example.smartmeal.MainActivity;
import com.example.smartmeal.R;
import com.example.smartmeal.adapter.HistoryAdapter;
import com.example.smartmeal.menu.MealMenu;
public class Submitted extends Fragment {
public static Submitted submitted;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// construct view
View rootView = inflater.inflate(R.layout.list, container, false);
((TextView) rootView.findViewById(R.id.day)).setText("Các bữa đã chấp nhận");
// clear history
((Button) rootView.findViewById(R.id.button)).setText("Xóa lịch sử");
((Button) rootView.findViewById(R.id.button)).setClickable(true);
// history view
History history = MainActivity.smie.getHistory();
int i = 0;
MealMenu menu;
SparseArray<MealMenu> groups = new SparseArray<MealMenu>();
for (Meal m : history.getMealList()){
String type = "";
switch(m.getType()){
case Meal.TYPE_BREAKFAST:
type = "sáng";
break;
case Meal.TYPE_LUNCH:
type = "trưa";
break;
case Meal.TYPE_DINNER:
type = "tối";
break;
}
menu = new MealMenu("Bữa " + type + " ngày " + (new SimpleDateFormat("dd/MM/yyyy", Locale.US).format(m.getDate().getTime())));
for (Dish d : m.getMenu())
menu.add(d);
groups.append(i++, menu);
}
ExpandableListView listView = (ExpandableListView) rootView.findViewById(R.id.expandableListView1);
HistoryAdapter adapter = new HistoryAdapter(getActivity(), groups);
listView.setAdapter(adapter);
submitted = this;
return rootView;
}
public static void reloadHistory() {
Submitted.submitted.getFragmentManager().beginTransaction()
.detach(Submitted.submitted)
.attach(Submitted.submitted)
.commit();
}
}
| [
"[email protected]"
] | |
fd7d30a7d8e6d2e29516d713668fdfbcae7a648c | 799378af74fa750bcb519392a297906be9f895ce | /app/src/main/java/com/example/marcu/health/CustomSeekBar.java | 0d681a0ec9ef0b47d0ba39074cd3da9cf458856f | [] | no_license | Sucramo/Health | b8b593a61c4b45ab2e0187139da3e13ba8e0fb53 | c86b3997d0ae6a29dc8c65af24dedc74b7baf808 | refs/heads/master | 2020-03-31T21:23:31.010200 | 2018-12-19T19:09:22 | 2018-12-19T19:09:22 | 152,578,789 | 1 | 0 | null | 2018-12-19T11:30:30 | 2018-10-11T11:11:48 | Java | UTF-8 | Java | false | false | 2,480 | java | package com.example.marcu.health;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
public class CustomSeekBar extends android.support.v7.widget.AppCompatSeekBar {
private ArrayList<ProgressItem> mProgressItemsList;
public CustomSeekBar(Context context) {
super(context);
}
public CustomSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void initData(ArrayList<ProgressItem> progressItemsList) {
this.mProgressItemsList = progressItemsList;
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
protected void onDraw(Canvas canvas) {
if (mProgressItemsList.size() > 0) {
int progressBarWidth = getWidth();
int progressBarHeight = getHeight();
int thumboffset = getThumbOffset();
int lastProgressX = 0;
int progressItemWidth, progressItemRight;
for (int i = 0; i < mProgressItemsList.size(); i++) {
ProgressItem progressItem = mProgressItemsList.get(i);
Paint progressPaint = new Paint();
progressPaint.setColor(getResources().getColor(
progressItem.color));
progressItemWidth = (int) (progressItem.progressItemPercentage
* progressBarWidth / 100);
progressItemRight = lastProgressX + progressItemWidth;
// for last item give right to progress item to the width
if (i == mProgressItemsList.size() - 1
&& progressItemRight != progressBarWidth) {
progressItemRight = progressBarWidth;
}
Rect progressRect = new Rect();
progressRect.set(lastProgressX, thumboffset / 2,
progressItemRight, progressBarHeight - thumboffset / 2);
canvas.drawRect(progressRect, progressPaint);
lastProgressX = progressItemRight;
}
super.onDraw(canvas);
}
}
}
| [
"[email protected]"
] | |
ff4f5c70b021d4768d0bb32382fa14021ee7e570 | 42a60bc77f408032be056b4271942ada33e5a57d | /core/src/main/java/hivemall/fm/StringFeature.java | e74cf6c1a65d455679977907d0b69dfb3a0b1bd9 | [
"Apache-2.0"
] | permissive | keylorsdu/hivemall | 97c8e860afeffdfd4586de65c252eb51e08d34f2 | 2667f8b9ff5654dfbd41b474ec4c54960c6d4061 | refs/heads/master | 2021-01-12T18:24:25.135932 | 2016-09-27T06:11:38 | 2016-09-27T06:11:38 | 69,419,096 | 0 | 1 | null | 2016-09-28T02:48:53 | 2016-09-28T02:48:53 | null | UTF-8 | Java | false | false | 2,018 | java | /*
* Hivemall: Hive scalable Machine Learning Library
*
* Copyright (C) 2015 Makoto YUI
* Copyright (C) 2013-2015 National Institute of Advanced Industrial Science and Technology (AIST)
*
* 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 hivemall.fm;
import hivemall.utils.io.NIOUtils;
import java.nio.ByteBuffer;
import javax.annotation.Nonnull;
public class StringFeature extends Feature {
@Nonnull
protected String feature;
public StringFeature(@Nonnull String feature, double value) {
super(value);
this.feature = feature;
}
// VisibleForTesting
StringFeature(int feature, double value) {
this(String.valueOf(feature), value);
}
public StringFeature(@Nonnull ByteBuffer src) {
super();
readFrom(src);
}
@Override
public String getFeature() {
return feature;
}
@Override
public void setFeature(@Nonnull String feature) {
this.feature = feature;
}
@Override
public int bytes() {
return NIOUtils.requiredBytes(feature) + Double.SIZE / Byte.SIZE;
}
@Override
public void writeTo(@Nonnull ByteBuffer dst) {
NIOUtils.putString(feature, dst);
dst.putDouble(value);
}
@Override
public void readFrom(@Nonnull ByteBuffer src) {
this.feature = NIOUtils.getString(src);
this.value = src.getDouble();
}
@Override
public String toString() {
return feature + ':' + value;
}
}
| [
"[email protected]"
] | |
e485ac65187c903acf285f792aed53ec7cc344cf | 748a1fc9d848773db713368d6f33e3bfba66ffe9 | /src/dpproblem/FruitIntoTheBasket.java | 2036528d316b1d06da063271934c2dc978fcab1a | [] | no_license | akcsbtech/datastructure | b2df3fa7179dfeed980606cf0089e9e4a1be0d2b | 00851b178b58985060a3cd7331a4544c22867fc9 | refs/heads/master | 2021-04-13T10:14:07.164459 | 2020-12-14T16:52:04 | 2020-12-14T16:52:04 | 249,154,582 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 212 | java | /**
*
*/
package dpproblem;
/**
* @author akashgoyal
*
*/
public class FruitIntoTheBasket {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| [
"[email protected]"
] | |
79fbf2b9c36085841c5aa0a6747b6a36416ee620 | 07a4204c4188803866852640696e6a30cf68f386 | /src/main/java/com/zsmart/base/bean/Adherent.java | d92ae0395f1330a2916117bfb4f0a2c1639a5209 | [] | no_license | ZOUANI/compta_transparency_base | b4e6a1037b6364b8993c54a64d9f5ab93f62d460 | 3669fb255f0f5f039526a13c8b0f31d711e10450 | refs/heads/master | 2021-03-27T03:28:17.403706 | 2020-04-07T14:03:17 | 2020-04-07T14:03:46 | 247,781,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,616 | java | /*
* 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 com.zsmart.base.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
/**
*
* @author YOUNES
*/
@Entity
public class Adherent implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nom;
private String email;
private String tel;
private String login;
private String password;
@OneToMany(mappedBy = "adherent")
private List<Societe> societes = new ArrayList<Societe>();
public List<Societe> getSocietes() {
return societes;
}
public void setSocietes(List<Societe> societes) {
this.societes = societes;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Adherent)) {
return false;
}
Adherent other = (Adherent) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return nom+"("+tel+")";
}
}
| [
"MoulaYounes@DESKTOP-GBNILO9"
] | MoulaYounes@DESKTOP-GBNILO9 |
0843889c828a944477820124f71fd9d8643a127b | 3fe383525b2dcd3f9a405c5105a4562983c7f7fa | /mlod/src/main/java/wvw/utils/Config.java | aaf93a7d9472626dfb979186d96578a8ee470036 | [
"Apache-2.0"
] | permissive | william-vw/mlod | 7e013d999878a1fcd16e4add94e62626a16875a5 | 20d67f8790ef24527d2e0baff4b5dd053b5ab621 | refs/heads/master | 2023-07-25T12:35:00.658936 | 2022-03-02T16:03:55 | 2022-03-02T16:03:55 | 253,907,808 | 0 | 0 | Apache-2.0 | 2023-07-23T11:15:08 | 2020-04-07T20:44:36 | HTML | UTF-8 | Java | false | false | 735 | java | package wvw.utils;
import java.io.IOException;
import java.util.Properties;
import wvw.utils.log.Log;
public class Config {
public static Properties config = new Properties();
@SuppressWarnings("rawtypes")
protected static void init(Class cls) {
try {
config.load(cls.getResourceAsStream("config.properties"));
Log.d("config? " + config);
} catch (IOException e) {
e.printStackTrace();
}
}
protected static int getIntProperty(String name) {
return Integer.valueOf(config.getProperty(name));
}
protected static double getDoubleProperty(String name) {
return Double.valueOf(config.getProperty(name));
}
protected static String getStringProperty(String name) {
return config.getProperty(name);
}
}
| [
"[email protected]"
] | |
b2211042b1c7a1dc666076092a068ef415f09a60 | 23378f00e90632624c2d69d50abbb922a177d6d1 | /src/java/util/concurrent/ConcurrentHashMap.java | 2303d10527e385bf355e768d095395280cb59908 | [] | no_license | qiuzj/jdk1.8 | 378156d6350558686902ef0bb9c72fded19b2e09 | 1de321913405c0a0f7a01c36b4ec29d4351a220a | refs/heads/master | 2021-07-10T14:21:32.057444 | 2020-06-23T15:55:52 | 2020-06-23T15:55:52 | 156,401,143 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 263,658 | java | /*
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
/*
*
*
*
*
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Spliterator;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.DoubleBinaryOperator;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.LongBinaryOperator;
import java.util.function.ToDoubleBiFunction;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntBiFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongBiFunction;
import java.util.function.ToLongFunction;
import java.util.stream.Stream;
/**
* <pre>
* ConcurrentHashMap是线程安全的哈希表。HashMap, Hashtable, ConcurrentHashMap之间的关联如下:
* (01) HashMap是非线程安全的哈希表,常用于单线程程序中。
* (02) Hashtable是线程安全的哈希表,它是通过synchronized来保证线程安全的。
* 即,多线程通过同一个“对象的同步锁”来实现并发控制。Hashtable在线程竞争激烈时,效率比较低(此时建议使用ConcurrentHashMap)!因为当一个线程访问Hashtable的同步方法时,其它线程就访问Hashtable的同步方法时,可能会进入阻塞状态。
* (03) ConcurrentHashMap是线程安全的哈希表,它是通过“锁分段”来保证线程安全的。
* ConcurrentHashMap将哈希表分成许多片段(Segment),每一个片段除了保存哈希表之外,本质上也是一个“可重入的互斥锁”(ReentrantLock)。多线程对同一个片段的访问,是互斥的;但是,对于不同片段的访问,却是可以同步进行的。
* </pre>
* A hash table supporting full concurrency of retrievals and
* high expected concurrency for updates. This class obeys the
* same functional specification as {@link java.util.Hashtable}, and
* includes versions of methods corresponding to each method of
* {@code Hashtable}. However, even though all operations are
* thread-safe, retrieval operations do <em>not</em> entail locking,
* and there is <em>not</em> any support for locking the entire table
* in a way that prevents all access. This class is fully
* interoperable with {@code Hashtable} in programs that rely on its
* thread safety but not on its synchronization details.
*
* <p>Retrieval operations (including {@code get}) generally do not
* block, so may overlap with update operations (including {@code put}
* and {@code remove}). Retrievals reflect the results of the most
* recently <em>completed</em> update operations holding upon their
* onset. (More formally, an update operation for a given key bears a
* <em>happens-before</em> relation with any (non-null) retrieval for
* that key reporting the updated value.) For aggregate operations
* such as {@code putAll} and {@code clear}, concurrent retrievals may
* reflect insertion or removal of only some entries. Similarly,
* Iterators, Spliterators and Enumerations return elements reflecting the
* state of the hash table at some point at or since the creation of the
* iterator/enumeration. They do <em>not</em> throw {@link
* java.util.ConcurrentModificationException ConcurrentModificationException}.
* However, iterators are designed to be used by only one thread at a time.
* Bear in mind that the results of aggregate status methods including
* {@code size}, {@code isEmpty}, and {@code containsValue} are typically
* useful only when a map is not undergoing concurrent updates in other threads.
* Otherwise the results of these methods reflect transient states
* that may be adequate for monitoring or estimation purposes, but not
* for program control.
*
* <p>The table is dynamically expanded when there are too many
* collisions (i.e., keys that have distinct hash codes but fall into
* the same slot modulo the table size), with the expected average
* effect of maintaining roughly two bins per mapping (corresponding
* to a 0.75 load factor threshold for resizing). There may be much
* variance around this average as mappings are added and removed, but
* overall, this maintains a commonly accepted time/space tradeoff for
* hash tables. However, resizing this or any other kind of hash
* table may be a relatively slow operation. When possible, it is a
* good idea to provide a size estimate as an optional {@code
* initialCapacity} constructor argument. An additional optional
* {@code loadFactor} constructor argument provides a further means of
* customizing initial table capacity by specifying the table density
* to be used in calculating the amount of space to allocate for the
* given number of elements. Also, for compatibility with previous
* versions of this class, constructors may optionally specify an
* expected {@code concurrencyLevel} as an additional hint for
* internal sizing. Note that using many keys with exactly the same
* {@code hashCode()} is a sure way to slow down performance of any
* hash table. To ameliorate impact, when keys are {@link Comparable},
* this class may use comparison order among keys to help break ties.
*
* <p>A {@link Set} projection of a ConcurrentHashMap may be created
* (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
* (using {@link #keySet(Object)} when only keys are of interest, and the
* mapped values are (perhaps transiently) not used or all take the
* same mapping value.
*
* <p>A ConcurrentHashMap can be used as scalable frequency map (a
* form of histogram or multiset) by using {@link
* java.util.concurrent.atomic.LongAdder} values and initializing via
* {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
* to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
* {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}
*
* <p>This class and its views and iterators implement all of the
* <em>optional</em> methods of the {@link Map} and {@link Iterator}
* interfaces.
*
* <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
* does <em>not</em> allow {@code null} to be used as a key or value.
*
* <p>ConcurrentHashMaps support a set of sequential and parallel bulk
* operations that, unlike most {@link Stream} methods, are designed
* to be safely, and often sensibly, applied even with maps that are
* being concurrently updated by other threads; for example, when
* computing a snapshot summary of the values in a shared registry.
* There are three kinds of operation, each with four forms, accepting
* functions with Keys, Values, Entries, and (Key, Value) arguments
* and/or return values. Because the elements of a ConcurrentHashMap
* are not ordered in any particular way, and may be processed in
* different orders in different parallel executions, the correctness
* of supplied functions should not depend on any ordering, or on any
* other objects or values that may transiently change while
* computation is in progress; and except for forEach actions, should
* ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
* objects do not support method {@code setValue}.
*
* <ul>
* <li> forEach: Perform a given action on each element.
* A variant form applies a given transformation on each element
* before performing the action.</li>
*
* <li> search: Return the first available non-null result of
* applying a given function on each element; skipping further
* search when a result is found.</li>
*
* <li> reduce: Accumulate each element. The supplied reduction
* function cannot rely on ordering (more formally, it should be
* both associative and commutative). There are five variants:
*
* <ul>
*
* <li> Plain reductions. (There is not a form of this method for
* (key, value) function arguments since there is no corresponding
* return type.)</li>
*
* <li> Mapped reductions that accumulate the results of a given
* function applied to each element.</li>
*
* <li> Reductions to scalar doubles, longs, and ints, using a
* given basis value.</li>
*
* </ul>
* </li>
* </ul>
*
* <p>These bulk operations accept a {@code parallelismThreshold}
* argument. Methods proceed sequentially if the current map size is
* estimated to be less than the given threshold. Using a value of
* {@code Long.MAX_VALUE} suppresses all parallelism. Using a value
* of {@code 1} results in maximal parallelism by partitioning into
* enough subtasks to fully utilize the {@link
* ForkJoinPool#commonPool()} that is used for all parallel
* computations. Normally, you would initially choose one of these
* extreme values, and then measure performance of using in-between
* values that trade off overhead versus throughput.
*
* <p>The concurrency properties of bulk operations follow
* from those of ConcurrentHashMap: Any non-null result returned
* from {@code get(key)} and related access methods bears a
* happens-before relation with the associated insertion or
* update. The result of any bulk operation reflects the
* composition of these per-element relations (but is not
* necessarily atomic with respect to the map as a whole unless it
* is somehow known to be quiescent). Conversely, because keys
* and values in the map are never null, null serves as a reliable
* atomic indicator of the current lack of any result. To
* maintain this property, null serves as an implicit basis for
* all non-scalar reduction operations. For the double, long, and
* int versions, the basis should be one that, when combined with
* any other value, returns that other value (more formally, it
* should be the identity element for the reduction). Most common
* reductions have these properties; for example, computing a sum
* with basis 0 or a minimum with basis MAX_VALUE.
*
* <p>Search and transformation functions provided as arguments
* should similarly return null to indicate the lack of any result
* (in which case it is not used). In the case of mapped
* reductions, this also enables transformations to serve as
* filters, returning null (or, in the case of primitive
* specializations, the identity basis) if the element should not
* be combined. You can create compound transformations and
* filterings by composing them yourself under this "null means
* there is nothing there now" rule before using them in search or
* reduce operations.
*
* <p>Methods accepting and/or returning Entry arguments maintain
* key-value associations. They may be useful for example when
* finding the key for the greatest value. Note that "plain" Entry
* arguments can be supplied using {@code new
* AbstractMap.SimpleEntry(k,v)}.
*
* <p>Bulk operations may complete abruptly, throwing an
* exception encountered in the application of a supplied
* function. Bear in mind when handling such exceptions that other
* concurrently executing functions could also have thrown
* exceptions, or would have done so if the first exception had
* not occurred.
*
* <p>Speedups for parallel compared to sequential forms are common
* but not guaranteed. Parallel operations involving brief functions
* on small maps may execute more slowly than sequential forms if the
* underlying work to parallelize the computation is more expensive
* than the computation itself. Similarly, parallelization may not
* lead to much actual parallelism if all processors are busy
* performing unrelated tasks.
*
* <p>All arguments to all task methods must be non-null.
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @since 1.5
* @author Doug Lea
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*/
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable {
private static final long serialVersionUID = 7249069246763182397L;
/*
* Overview:
*
* The primary design goal of this hash table is to maintain
* concurrent readability (typically method get(), but also
* iterators and related methods) while minimizing update
* contention. Secondary goals are to keep space consumption about
* the same or better than java.util.HashMap, and to support high
* initial insertion rates on an empty table by many threads.
*
* This map usually acts as a binned (bucketed) hash table. Each
* key-value mapping is held in a Node. Most nodes are instances
* of the basic Node class with hash, key, value, and next
* fields. However, various subclasses exist: TreeNodes are
* arranged in balanced trees, not lists. TreeBins hold the roots
* of sets of TreeNodes. ForwardingNodes are placed at the heads
* of bins during resizing. ReservationNodes are used as
* placeholders while establishing values in computeIfAbsent and
* related methods. The types TreeBin, ForwardingNode, and
* ReservationNode do not hold normal user keys, values, or
* hashes, and are readily distinguishable during search etc
* because they have negative hash fields and null key and value
* fields. (These special nodes are either uncommon or transient,
* so the impact of carrying around some unused fields is
* insignificant.)
*
* The table is lazily initialized to a power-of-two size upon the
* first insertion. Each bin in the table normally contains a
* list of Nodes (most often, the list has only zero or one Node).
* Table accesses require volatile/atomic reads, writes, and
* CASes. Because there is no other way to arrange this without
* adding further indirections, we use intrinsics
* (sun.misc.Unsafe) operations.
*
* We use the top (sign) bit of Node hash fields for control
* purposes -- it is available anyway because of addressing
* constraints. Nodes with negative hash fields are specially
* handled or ignored in map methods.
*
* Insertion (via put or its variants) of the first node in an
* empty bin is performed by just CASing it to the bin. This is
* by far the most common case for put operations under most
* key/hash distributions. Other update operations (insert,
* delete, and replace) require locks. We do not want to waste
* the space required to associate a distinct lock object with
* each bin, so instead use the first node of a bin list itself as
* a lock. Locking support for these locks relies on builtin
* "synchronized" monitors.
*
* Using the first node of a list as a lock does not by itself
* suffice though: When a node is locked, any update must first
* validate that it is still the first node after locking it, and
* retry if not. Because new nodes are always appended to lists,
* once a node is first in a bin, it remains first until deleted
* or the bin becomes invalidated (upon resizing).
*
* The main disadvantage of per-bin locks is that other update
* operations on other nodes in a bin list protected by the same
* lock can stall, for example when user equals() or mapping
* functions take a long time. However, statistically, under
* random hash codes, this is not a common problem. Ideally, the
* frequency of nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average, given the resizing threshold
* of 0.75, although with a large variance because of resizing
* granularity. Ignoring variance, the expected occurrences of
* list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
* first values are:
*
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
* more: less than 1 in ten million
*
* Lock contention probability for two threads accessing distinct
* elements is roughly 1 / (8 * #elements) under random hashes.
*
* Actual hash code distributions encountered in practice
* sometimes deviate significantly from uniform randomness. This
* includes the case when N > (1<<30), so some keys MUST collide.
* Similarly for dumb or hostile usages in which multiple keys are
* designed to have identical hash codes or ones that differs only
* in masked-out high bits. So we use a secondary strategy that
* applies when the number of nodes in a bin exceeds a
* threshold. These TreeBins use a balanced tree to hold nodes (a
* specialized form of red-black trees), bounding search time to
* O(log N). Each search step in a TreeBin is at least twice as
* slow as in a regular list, but given that N cannot exceed
* (1<<64) (before running out of addresses) this bounds search
* steps, lock hold times, etc, to reasonable constants (roughly
* 100 nodes inspected per operation worst case) so long as keys
* are Comparable (which is very common -- String, Long, etc).
* TreeBin nodes (TreeNodes) also maintain the same "next"
* traversal pointers as regular nodes, so can be traversed in
* iterators in the same way.
*
* The table is resized when occupancy exceeds a percentage
* threshold (nominally, 0.75, but see below). Any thread
* noticing an overfull bin may assist in resizing after the
* initiating thread allocates and sets up the replacement array.
* However, rather than stalling, these other threads may proceed
* with insertions etc. The use of TreeBins shields us from the
* worst case effects of overfilling while resizes are in
* progress. Resizing proceeds by transferring bins, one by one,
* from the table to the next table. However, threads claim small
* blocks of indices to transfer (via field transferIndex) before
* doing so, reducing contention. A generation stamp in field
* sizeCtl ensures that resizings do not overlap. Because we are
* using power-of-two expansion, the elements from each bin must
* either stay at same index, or move with a power of two
* offset. We eliminate unnecessary node creation by catching
* cases where old nodes can be reused because their next fields
* won't change. On average, only about one-sixth of them need
* cloning when a table doubles. The nodes they replace will be
* garbage collectable as soon as they are no longer referenced by
* any reader thread that may be in the midst of concurrently
* traversing table. Upon transfer, the old table bin contains
* only a special forwarding node (with hash field "MOVED") that
* contains the next table as its key. On encountering a
* forwarding node, access and update operations restart, using
* the new table.
*
* Each bin transfer requires its bin lock, which can stall
* waiting for locks while resizing. However, because other
* threads can join in and help resize rather than contend for
* locks, average aggregate waits become shorter as resizing
* progresses. The transfer operation must also ensure that all
* accessible bins in both the old and new table are usable by any
* traversal. This is arranged in part by proceeding from the
* last bin (table.length - 1) up towards the first. Upon seeing
* a forwarding node, traversals (see class Traverser) arrange to
* move to the new table without revisiting nodes. To ensure that
* no intervening nodes are skipped even when moved out of order,
* a stack (see class TableStack) is created on first encounter of
* a forwarding node during a traversal, to maintain its place if
* later processing the current table. The need for these
* save/restore mechanics is relatively rare, but when one
* forwarding node is encountered, typically many more will be.
* So Traversers use a simple caching scheme to avoid creating so
* many new TableStack nodes. (Thanks to Peter Levart for
* suggesting use of a stack here.)
*
* The traversal scheme also applies to partial traversals of
* ranges of bins (via an alternate Traverser constructor)
* to support partitioned aggregate operations. Also, read-only
* operations give up if ever forwarded to a null table, which
* provides support for shutdown-style clearing, which is also not
* currently implemented.
*
* Lazy table initialization minimizes footprint until first use,
* and also avoids resizings when the first operation is from a
* putAll, constructor with map argument, or deserialization.
* These cases attempt to override the initial capacity settings,
* but harmlessly fail to take effect in cases of races.
*
* The element count is maintained using a specialization of
* LongAdder. We need to incorporate a specialization rather than
* just use a LongAdder in order to access implicit
* contention-sensing that leads to creation of multiple
* CounterCells. The counter mechanics avoid contention on
* updates but can encounter cache thrashing if read too
* frequently during concurrent access. To avoid reading so often,
* resizing under contention is attempted only upon adding to a
* bin already holding two or more nodes. Under uniform hash
* distributions, the probability of this occurring at threshold
* is around 13%, meaning that only about 1 in 8 puts check
* threshold (and after resizing, many fewer do so).
*
* TreeBins use a special form of comparison for search and
* related operations (which is the main reason we cannot use
* existing collections such as TreeMaps). TreeBins contain
* Comparable elements, but may contain others, as well as
* elements that are Comparable but not necessarily Comparable for
* the same T, so we cannot invoke compareTo among them. To handle
* this, the tree is ordered primarily by hash value, then by
* Comparable.compareTo order if applicable. On lookup at a node,
* if elements are not comparable or compare as 0 then both left
* and right children may need to be searched in the case of tied
* hash values. (This corresponds to the full list search that
* would be necessary if all elements were non-Comparable and had
* tied hashes.) On insertion, to keep a total ordering (or as
* close as is required here) across rebalancings, we compare
* classes and identityHashCodes as tie-breakers. The red-black
* balancing code is updated from pre-jdk-collections
* (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
* based in turn on Cormen, Leiserson, and Rivest "Introduction to
* Algorithms" (CLR).
*
* TreeBins also require an additional locking mechanism. While
* list traversal is always possible by readers even during
* updates, tree traversal is not, mainly because of tree-rotations
* that may change the root node and/or its linkages. TreeBins
* include a simple read-write lock mechanism parasitic on the
* main bin-synchronization strategy: Structural adjustments
* associated with an insertion or removal are already bin-locked
* (and so cannot conflict with other writers) but must wait for
* ongoing readers to finish. Since there can be only one such
* waiter, we use a simple scheme using a single "waiter" field to
* block writers. However, readers need never block. If the root
* lock is held, they proceed along the slow traversal path (via
* next-pointers) until the lock becomes available or the list is
* exhausted, whichever comes first. These cases are not fast, but
* maximize aggregate expected throughput.
*
* Maintaining API and serialization compatibility with previous
* versions of this class introduces several oddities. Mainly: We
* leave untouched but unused constructor arguments refering to
* concurrencyLevel. We accept a loadFactor constructor argument,
* but apply it only to initial table capacity (which is the only
* time that we can guarantee to honor it.) We also declare an
* unused "Segment" class that is instantiated in minimal form
* only when serializing.
*
* Also, solely for compatibility with previous versions of this
* class, it extends AbstractMap, even though all of its methods
* are overridden, so it is just useless baggage.
*
* This file is organized to make things a little easier to follow
* while reading than they might otherwise: First the main static
* declarations and utilities, then fields, then main public
* methods (with a few factorings of multiple public methods into
* internal ones), then sizing methods, trees, traversers, and
* bulk operations.
*/
/* ---------------- Constants -------------- */
/**
* The largest possible table capacity. This value must be
* exactly 1<<30 to stay within Java array allocation and indexing
* bounds for power of two table sizes, and is further required
* because the top two bits of 32bit hash fields are used for
* control purposes.
*/
private static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The default initial table capacity. Must be a power of 2
* (i.e., at least 1) and at most MAXIMUM_CAPACITY.
*/
private static final int DEFAULT_CAPACITY = 16;
/**
* The largest possible (non-power of two) array size.
* Needed by toArray and related methods.
*/
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* The default concurrency level for this table. Unused but
* defined for compatibility with previous versions of this class.
*/
private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
/**
* The load factor for this table. Overrides of this value in
* constructors affect only the initial table capacity. The
* actual floating point value isn't normally used -- it is
* simpler to use expressions such as {@code n - (n >>> 2)} for
* the associated resizing threshold.
*/
private static final float LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2, and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* The value should be at least 4 * TREEIFY_THRESHOLD to avoid
* conflicts between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* Minimum number of rebinnings per transfer step. Ranges are
* subdivided to allow multiple resizer threads. This value
* serves as a lower bound to avoid resizers encountering
* excessive memory contention. The value should be at least
* DEFAULT_CAPACITY.
*/
private static final int MIN_TRANSFER_STRIDE = 16;
/**
* The number of bits used for generation stamp in sizeCtl.
* Must be at least 6 for 32bit arrays.
*/
private static int RESIZE_STAMP_BITS = 16;
/**
* The maximum number of threads that can help resize.
* Must fit in 32 - RESIZE_STAMP_BITS bits.
*/
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
/**
* The bit shift for recording size stamp in sizeCtl.
*/
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
/*
* Encodings for Node hash fields. See above for explanation.
*/
static final int MOVED = -1; // hash for forwarding nodes
static final int TREEBIN = -2; // hash for roots of trees
static final int RESERVED = -3; // hash for transient reservations
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
/** Number of CPUS, to place bounds on some sizings */
static final int NCPU = Runtime.getRuntime().availableProcessors();
/** For serialization compatibility. */
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("segments", Segment[].class),
new ObjectStreamField("segmentMask", Integer.TYPE),
new ObjectStreamField("segmentShift", Integer.TYPE)
};
/* ---------------- Nodes -------------- */
/**
* Key-value entry. This class is never exported out as a
* user-mutable Map.Entry (i.e., one supporting setValue; see
* MapEntry below), but can be used for read-only traversals used
* in bulk tasks. Subclasses of Node with a negative hash field
* are special, and contain null keys and values (but are never
* exported). Otherwise, keys and vals are never null.
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next;
Node(int hash, K key, V val, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.val = val;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return val; }
public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
public final String toString(){ return key + "=" + val; }
public final V setValue(V value) {
throw new UnsupportedOperationException();
}
public final boolean equals(Object o) {
Object k, v, u; Map.Entry<?,?> e;
return ((o instanceof Map.Entry) &&
(k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
(v = e.getValue()) != null &&
(k == key || k.equals(key)) &&
(v == (u = val) || v.equals(u)));
}
/**
* Virtualized support for map.get(); overridden in subclasses.
*/
Node<K,V> find(int h, Object k) {
Node<K,V> e = this;
if (k != null) {
do {
K ek;
if (e.hash == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
} while ((e = e.next) != null);
}
return null;
}
}
/* ---------------- Static utilities -------------- */
/**
* Spreads (XORs) higher bits of hash to lower and also forces top
* bit to 0. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
/**
* Returns a power of two table size for the given desired capacity.
* See Hackers Delight, sec 3.2
*/
private static final int tableSizeFor(int c) {
int n = c - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
/**
* Returns x's Class if it is of the form "class C implements
* Comparable<C>", else null.
*/
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
/**
* Returns k.compareTo(x) if x matches kc (k's screened comparable
* class), else 0.
*/
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}
/* ---------------- Table element access -------------- */
/*
* Volatile access methods are used for table elements as well as
* elements of in-progress next table while resizing. All uses of
* the tab arguments must be null checked by callers. All callers
* also paranoically precheck that tab's length is not zero (or an
* equivalent check), thus ensuring that any index argument taking
* the form of a hash value anded with (length - 1) is a valid
* index. Note that, to be correct wrt arbitrary concurrency
* errors by users, these checks must operate on local variables,
* which accounts for some odd-looking inline assignments below.
* Note that calls to setTabAt always occur within locked regions,
* and so in principle require only release ordering, not
* full volatile semantics, but are currently coded as volatile
* writes to be conservative.
*/
@SuppressWarnings("unchecked")
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
/* ---------------- Fields -------------- */
/**
* The array of bins. Lazily initialized upon first insertion.
* Size is always a power of two. Accessed directly by iterators.
*/
transient volatile Node<K,V>[] table;
/**
* The next table to use; non-null only while resizing.
*/
private transient volatile Node<K,V>[] nextTable;
/**
* Base counter value, used mainly when there is no contention,
* but also as a fallback during table initialization
* races. Updated via CAS.
*/
private transient volatile long baseCount;
/**
* Table initialization and resizing control. When negative, the
* table is being initialized or resized: -1 for initialization,
* else -(1 + the number of active resizing threads). Otherwise,
* when table is null, holds the initial table size to use upon
* creation, or 0 for default. After initialization, holds the
* next element count value upon which to resize the table.
*/
private transient volatile int sizeCtl;
/**
* The next table index (plus one) to split while resizing.
*/
private transient volatile int transferIndex;
/**
* Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
*/
private transient volatile int cellsBusy;
/**
* Table of counter cells. When non-null, size is a power of 2.
*/
private transient volatile CounterCell[] counterCells;
// views
private transient KeySetView<K,V> keySet;
private transient ValuesView<K,V> values;
private transient EntrySetView<K,V> entrySet;
/* ---------------- Public operations -------------- */
/**
* Creates a new, empty map with the default initial table size (16).
*/
public ConcurrentHashMap() {
}
/**
* Creates a new, empty map with an initial table size
* accommodating the specified number of elements without the need
* to dynamically resize.
*
* @param initialCapacity The implementation performs internal
* sizing to accommodate this many elements.
* @throws IllegalArgumentException if the initial capacity of
* elements is negative
*/
public ConcurrentHashMap(int initialCapacity) {
if (initialCapacity < 0)
throw new IllegalArgumentException();
int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
MAXIMUM_CAPACITY :
tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
this.sizeCtl = cap;
}
/**
* Creates a new map with the same mappings as the given map.
*
* @param m the map
*/
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
this.sizeCtl = DEFAULT_CAPACITY;
putAll(m);
}
/**
* Creates a new, empty map with an initial table size based on
* the given number of elements ({@code initialCapacity}) and
* initial table density ({@code loadFactor}).
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements,
* given the specified load factor.
* @param loadFactor the load factor (table density) for
* establishing the initial table size
* @throws IllegalArgumentException if the initial capacity of
* elements is negative or the load factor is nonpositive
*
* @since 1.6
*/
public ConcurrentHashMap(int initialCapacity, float loadFactor) {
this(initialCapacity, loadFactor, 1);
}
/**
* Creates a new, empty map with an initial table size based on
* the given number of elements ({@code initialCapacity}), table
* density ({@code loadFactor}), and number of concurrently
* updating threads ({@code concurrencyLevel}).
*
* @param initialCapacity the initial capacity. The implementation
* performs internal sizing to accommodate this many elements,
* given the specified load factor.
* @param loadFactor the load factor (table density) for
* establishing the initial table size
* @param concurrencyLevel the estimated number of concurrently
* updating threads. The implementation may use this value as
* a sizing hint.
* @throws IllegalArgumentException if the initial capacity is
* negative or the load factor or concurrencyLevel are
* nonpositive
*/
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (initialCapacity < concurrencyLevel) // Use at least as many bins
initialCapacity = concurrencyLevel; // as estimated threads
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}
// Original (since JDK1.2) Map methods
/**
* {@inheritDoc}
*/
public int size() {
long n = sumCount();
return ((n < 0L) ? 0 :
(n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
(int)n);
}
/**
* {@inheritDoc}
*/
public boolean isEmpty() {
return sumCount() <= 0L; // ignore transient negative values
}
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code key.equals(k)},
* then this method returns {@code v}; otherwise it returns
* {@code null}. (There can be at most one such mapping.)
*
* @throws NullPointerException if the specified key is null
*/
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
/**
* Tests if the specified object is a key in this table.
*
* @param key possible key
* @return {@code true} if and only if the specified object
* is a key in this table, as determined by the
* {@code equals} method; {@code false} otherwise
* @throws NullPointerException if the specified key is null
*/
public boolean containsKey(Object key) {
return get(key) != null;
}
/**
* Returns {@code true} if this map maps one or more keys to the
* specified value. Note: This method may require a full traversal
* of the map, and is much slower than method {@code containsKey}.
*
* @param value value whose presence in this map is to be tested
* @return {@code true} if this map maps one or more keys to the
* specified value
* @throws NullPointerException if the specified value is null
*/
public boolean containsValue(Object value) {
if (value == null)
throw new NullPointerException();
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
V v;
if ((v = p.val) == value || (v != null && value.equals(v)))
return true;
}
}
return false;
}
/**
* Maps the specified key to the specified value in this table.
* Neither the key nor the value can be null.
*
* <p>The value can be retrieved by calling the {@code get} method
* with a key that is equal to the original key.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}
* @throws NullPointerException if the specified key or value is null
*/
public V put(K key, V value) {
return putVal(key, value, false);
}
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
/**
* Copies all of the mappings from the specified map to this one.
* These mappings replace any mappings that this map had for any of the
* keys currently in the specified map.
*
* @param m mappings to be stored in this map
*/
public void putAll(Map<? extends K, ? extends V> m) {
tryPresize(m.size());
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
putVal(e.getKey(), e.getValue(), false);
}
/**
* Removes the key (and its corresponding value) from this map.
* This method does nothing if the key is not in the map.
*
* @param key the key that needs to be removed
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}
* @throws NullPointerException if the specified key is null
*/
public V remove(Object key) {
return replaceNode(key, null, null);
}
/**
* Implementation for the four public remove/replace methods:
* Replaces node value with v, conditional upon match of cv if
* non-null. If resulting value is null, delete.
*/
final V replaceNode(Object key, V value, Object cv) {
int hash = spread(key.hashCode());
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0 ||
(f = tabAt(tab, i = (n - 1) & hash)) == null)
break;
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
boolean validated = false;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
validated = true;
for (Node<K,V> e = f, pred = null;;) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
V ev = e.val;
if (cv == null || cv == ev ||
(ev != null && cv.equals(ev))) {
oldVal = ev;
if (value != null)
e.val = value;
else if (pred != null)
pred.next = e.next;
else
setTabAt(tab, i, e.next);
}
break;
}
pred = e;
if ((e = e.next) == null)
break;
}
}
else if (f instanceof TreeBin) {
validated = true;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((r = t.root) != null &&
(p = r.findTreeNode(hash, key, null)) != null) {
V pv = p.val;
if (cv == null || cv == pv ||
(pv != null && cv.equals(pv))) {
oldVal = pv;
if (value != null)
p.val = value;
else if (t.removeTreeNode(p))
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
}
if (validated) {
if (oldVal != null) {
if (value == null)
addCount(-1L, -1);
return oldVal;
}
break;
}
}
}
return null;
}
/**
* Removes all of the mappings from this map.
*/
public void clear() {
long delta = 0L; // negative number of deletions
int i = 0;
Node<K,V>[] tab = table;
while (tab != null && i < tab.length) {
int fh;
Node<K,V> f = tabAt(tab, i);
if (f == null)
++i;
else if ((fh = f.hash) == MOVED) {
tab = helpTransfer(tab, f);
i = 0; // restart
}
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> p = (fh >= 0 ? f :
(f instanceof TreeBin) ?
((TreeBin<K,V>)f).first : null);
while (p != null) {
--delta;
p = p.next;
}
setTabAt(tab, i++, null);
}
}
}
}
if (delta != 0L)
addCount(delta, -1);
}
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from this map,
* via the {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll}, and {@code clear}
* operations. It does not support the {@code add} or
* {@code addAll} operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
*
* @return the set view
*/
public KeySetView<K,V> keySet() {
KeySetView<K,V> ks;
return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. The collection
* supports element removal, which removes the corresponding
* mapping from this map, via the {@code Iterator.remove},
* {@code Collection.remove}, {@code removeAll},
* {@code retainAll}, and {@code clear} operations. It does not
* support the {@code add} or {@code addAll} operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
* and {@link Spliterator#NONNULL}.
*
* @return the collection view
*/
public Collection<V> values() {
ValuesView<K,V> vs;
return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. The set supports element
* removal, which removes the corresponding mapping from the map,
* via the {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll}, and {@code clear}
* operations.
*
* <p>The view's iterators and spliterators are
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
*
* @return the set view
*/
public Set<Map.Entry<K,V>> entrySet() {
EntrySetView<K,V> es;
return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
}
/**
* Returns the hash code value for this {@link Map}, i.e.,
* the sum of, for each key-value pair in the map,
* {@code key.hashCode() ^ value.hashCode()}.
*
* @return the hash code value for this map
*/
public int hashCode() {
int h = 0;
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; )
h += p.key.hashCode() ^ p.val.hashCode();
}
return h;
}
/**
* Returns a string representation of this map. The string
* representation consists of a list of key-value mappings (in no
* particular order) enclosed in braces ("{@code {}}"). Adjacent
* mappings are separated by the characters {@code ", "} (comma
* and space). Each key-value mapping is rendered as the key
* followed by an equals sign ("{@code =}") followed by the
* associated value.
*
* @return a string representation of this map
*/
public String toString() {
Node<K,V>[] t;
int f = (t = table) == null ? 0 : t.length;
Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
StringBuilder sb = new StringBuilder();
sb.append('{');
Node<K,V> p;
if ((p = it.advance()) != null) {
for (;;) {
K k = p.key;
V v = p.val;
sb.append(k == this ? "(this Map)" : k);
sb.append('=');
sb.append(v == this ? "(this Map)" : v);
if ((p = it.advance()) == null)
break;
sb.append(',').append(' ');
}
}
return sb.append('}').toString();
}
/**
* Compares the specified object with this map for equality.
* Returns {@code true} if the given object is a map with the same
* mappings as this map. This operation may return misleading
* results if either map is concurrently modified during execution
* of this method.
*
* @param o object to be compared for equality with this map
* @return {@code true} if the specified object is equal to this map
*/
public boolean equals(Object o) {
if (o != this) {
if (!(o instanceof Map))
return false;
Map<?,?> m = (Map<?,?>) o;
Node<K,V>[] t;
int f = (t = table) == null ? 0 : t.length;
Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
for (Node<K,V> p; (p = it.advance()) != null; ) {
V val = p.val;
Object v = m.get(p.key);
if (v == null || (v != val && !v.equals(val)))
return false;
}
for (Map.Entry<?,?> e : m.entrySet()) {
Object mk, mv, v;
if ((mk = e.getKey()) == null ||
(mv = e.getValue()) == null ||
(v = get(mk)) == null ||
(mv != v && !mv.equals(v)))
return false;
}
}
return true;
}
/**
* Stripped-down version of helper class used in previous version,
* declared for the sake of serialization compatibility
*/
static class Segment<K,V> extends ReentrantLock implements Serializable {
private static final long serialVersionUID = 2249069246763182397L;
final float loadFactor;
Segment(float lf) { this.loadFactor = lf; }
}
/**
* Saves the state of the {@code ConcurrentHashMap} instance to a
* stream (i.e., serializes it).
* @param s the stream
* @throws java.io.IOException if an I/O error occurs
* @serialData
* the key (Object) and value (Object)
* for each key-value mapping, followed by a null pair.
* The key-value mappings are emitted in no particular order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// For serialization compatibility
// Emulate segment calculation from previous version of this class
int sshift = 0;
int ssize = 1;
while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
++sshift;
ssize <<= 1;
}
int segmentShift = 32 - sshift;
int segmentMask = ssize - 1;
@SuppressWarnings("unchecked")
Segment<K,V>[] segments = (Segment<K,V>[])
new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
for (int i = 0; i < segments.length; ++i)
segments[i] = new Segment<K,V>(LOAD_FACTOR);
s.putFields().put("segments", segments);
s.putFields().put("segmentShift", segmentShift);
s.putFields().put("segmentMask", segmentMask);
s.writeFields();
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
s.writeObject(p.key);
s.writeObject(p.val);
}
}
s.writeObject(null);
s.writeObject(null);
segments = null; // throw away
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
* @param s the stream
* @throws ClassNotFoundException if the class of a serialized object
* could not be found
* @throws java.io.IOException if an I/O error occurs
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
/*
* To improve performance in typical cases, we create nodes
* while reading, then place in table once size is known.
* However, we must also validate uniqueness and deal with
* overpopulated bins while doing so, which requires
* specialized versions of putVal mechanics.
*/
sizeCtl = -1; // force exclusion for table construction
s.defaultReadObject();
long size = 0L;
Node<K,V> p = null;
for (;;) {
@SuppressWarnings("unchecked")
K k = (K) s.readObject();
@SuppressWarnings("unchecked")
V v = (V) s.readObject();
if (k != null && v != null) {
p = new Node<K,V>(spread(k.hashCode()), k, v, p);
++size;
}
else
break;
}
if (size == 0L)
sizeCtl = 0;
else {
int n;
if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
n = MAXIMUM_CAPACITY;
else {
int sz = (int)size;
n = tableSizeFor(sz + (sz >>> 1) + 1);
}
@SuppressWarnings("unchecked")
Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
int mask = n - 1;
long added = 0L;
while (p != null) {
boolean insertAtFront;
Node<K,V> next = p.next, first;
int h = p.hash, j = h & mask;
if ((first = tabAt(tab, j)) == null)
insertAtFront = true;
else {
K k = p.key;
if (first.hash < 0) {
TreeBin<K,V> t = (TreeBin<K,V>)first;
if (t.putTreeVal(h, k, p.val) == null)
++added;
insertAtFront = false;
}
else {
int binCount = 0;
insertAtFront = true;
Node<K,V> q; K qk;
for (q = first; q != null; q = q.next) {
if (q.hash == h &&
((qk = q.key) == k ||
(qk != null && k.equals(qk)))) {
insertAtFront = false;
break;
}
++binCount;
}
if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
insertAtFront = false;
++added;
p.next = first;
TreeNode<K,V> hd = null, tl = null;
for (q = p; q != null; q = q.next) {
TreeNode<K,V> t = new TreeNode<K,V>
(q.hash, q.key, q.val, null, null);
if ((t.prev = tl) == null)
hd = t;
else
tl.next = t;
tl = t;
}
setTabAt(tab, j, new TreeBin<K,V>(hd));
}
}
}
if (insertAtFront) {
++added;
p.next = first;
setTabAt(tab, j, p);
}
p = next;
}
table = tab;
sizeCtl = n - (n >>> 2);
baseCount = added;
}
}
// ConcurrentMap methods
/**
* {@inheritDoc}
*
* @return the previous value associated with the specified key,
* or {@code null} if there was no mapping for the key
* @throws NullPointerException if the specified key or value is null
*/
public V putIfAbsent(K key, V value) {
return putVal(key, value, true);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the specified key is null
*/
public boolean remove(Object key, Object value) {
if (key == null)
throw new NullPointerException();
return value != null && replaceNode(key, null, value) != null;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if any of the arguments are null
*/
public boolean replace(K key, V oldValue, V newValue) {
if (key == null || oldValue == null || newValue == null)
throw new NullPointerException();
return replaceNode(key, newValue, oldValue) != null;
}
/**
* {@inheritDoc}
*
* @return the previous value associated with the specified key,
* or {@code null} if there was no mapping for the key
* @throws NullPointerException if the specified key or value is null
*/
public V replace(K key, V value) {
if (key == null || value == null)
throw new NullPointerException();
return replaceNode(key, value, null);
}
// Overrides of JDK8+ Map extension method defaults
/**
* Returns the value to which the specified key is mapped, or the
* given default value if this map contains no mapping for the
* key.
*
* @param key the key whose associated value is to be returned
* @param defaultValue the value to return if this map contains
* no mapping for the given key
* @return the mapping for the key, if present; else the default value
* @throws NullPointerException if the specified key is null
*/
public V getOrDefault(Object key, V defaultValue) {
V v;
return (v = get(key)) == null ? defaultValue : v;
}
public void forEach(BiConsumer<? super K, ? super V> action) {
if (action == null) throw new NullPointerException();
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
action.accept(p.key, p.val);
}
}
}
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
if (function == null) throw new NullPointerException();
Node<K,V>[] t;
if ((t = table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
V oldValue = p.val;
for (K key = p.key;;) {
V newValue = function.apply(key, oldValue);
if (newValue == null)
throw new NullPointerException();
if (replaceNode(key, newValue, oldValue) != null ||
(oldValue = get(key)) == null)
break;
}
}
}
}
/**
* If the specified key is not already associated with a value,
* attempts to compute its value using the given mapping function
* and enters it into this map unless {@code null}. The entire
* method invocation is performed atomically, so the function is
* applied at most once per key. Some attempted update operations
* on this map by other threads may be blocked while computation
* is in progress, so the computation should be short and simple,
* and must not attempt to update any other mappings of this map.
*
* @param key key with which the specified value is to be associated
* @param mappingFunction the function to compute a value
* @return the current (existing or computed) value associated with
* the specified key, or null if the computed value is null
* @throws NullPointerException if the specified key or mappingFunction
* is null
* @throws IllegalStateException if the computation detectably
* attempts a recursive update to this map that would
* otherwise never complete
* @throws RuntimeException or Error if the mappingFunction does so,
* in which case the mapping is left unestablished
*/
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (key == null || mappingFunction == null)
throw new NullPointerException();
int h = spread(key.hashCode());
V val = null;
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
if (casTabAt(tab, i, null, r)) {
binCount = 1;
Node<K,V> node = null;
try {
if ((val = mappingFunction.apply(key)) != null)
node = new Node<K,V>(h, key, val, null);
} finally {
setTabAt(tab, i, node);
}
}
}
if (binCount != 0)
break;
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
boolean added = false;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek; V ev;
if (e.hash == h &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
val = e.val;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
if ((val = mappingFunction.apply(key)) != null) {
added = true;
pred.next = new Node<K,V>(h, key, val, null);
}
break;
}
}
}
else if (f instanceof TreeBin) {
binCount = 2;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((r = t.root) != null &&
(p = r.findTreeNode(h, key, null)) != null)
val = p.val;
else if ((val = mappingFunction.apply(key)) != null) {
added = true;
t.putTreeVal(h, key, val);
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (!added)
return val;
break;
}
}
}
if (val != null)
addCount(1L, binCount);
return val;
}
/**
* If the value for the specified key is present, attempts to
* compute a new mapping given the key and its current mapped
* value. The entire method invocation is performed atomically.
* Some attempted update operations on this map by other threads
* may be blocked while computation is in progress, so the
* computation should be short and simple, and must not attempt to
* update any other mappings of this map.
*
* @param key key with which a value may be associated
* @param remappingFunction the function to compute a value
* @return the new value associated with the specified key, or null if none
* @throws NullPointerException if the specified key or remappingFunction
* is null
* @throws IllegalStateException if the computation detectably
* attempts a recursive update to this map that would
* otherwise never complete
* @throws RuntimeException or Error if the remappingFunction does so,
* in which case the mapping is unchanged
*/
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (key == null || remappingFunction == null)
throw new NullPointerException();
int h = spread(key.hashCode());
V val = null;
int delta = 0;
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
break;
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f, pred = null;; ++binCount) {
K ek;
if (e.hash == h &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
val = remappingFunction.apply(key, e.val);
if (val != null)
e.val = val;
else {
delta = -1;
Node<K,V> en = e.next;
if (pred != null)
pred.next = en;
else
setTabAt(tab, i, en);
}
break;
}
pred = e;
if ((e = e.next) == null)
break;
}
}
else if (f instanceof TreeBin) {
binCount = 2;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((r = t.root) != null &&
(p = r.findTreeNode(h, key, null)) != null) {
val = remappingFunction.apply(key, p.val);
if (val != null)
p.val = val;
else {
delta = -1;
if (t.removeTreeNode(p))
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
}
if (binCount != 0)
break;
}
}
if (delta != 0)
addCount((long)delta, binCount);
return val;
}
/**
* Attempts to compute a mapping for the specified key and its
* current mapped value (or {@code null} if there is no current
* mapping). The entire method invocation is performed atomically.
* Some attempted update operations on this map by other threads
* may be blocked while computation is in progress, so the
* computation should be short and simple, and must not attempt to
* update any other mappings of this Map.
*
* @param key key with which the specified value is to be associated
* @param remappingFunction the function to compute a value
* @return the new value associated with the specified key, or null if none
* @throws NullPointerException if the specified key or remappingFunction
* is null
* @throws IllegalStateException if the computation detectably
* attempts a recursive update to this map that would
* otherwise never complete
* @throws RuntimeException or Error if the remappingFunction does so,
* in which case the mapping is unchanged
*/
public V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (key == null || remappingFunction == null)
throw new NullPointerException();
int h = spread(key.hashCode());
V val = null;
int delta = 0;
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
if (casTabAt(tab, i, null, r)) {
binCount = 1;
Node<K,V> node = null;
try {
if ((val = remappingFunction.apply(key, null)) != null) {
delta = 1;
node = new Node<K,V>(h, key, val, null);
}
} finally {
setTabAt(tab, i, node);
}
}
}
if (binCount != 0)
break;
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f, pred = null;; ++binCount) {
K ek;
if (e.hash == h &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
val = remappingFunction.apply(key, e.val);
if (val != null)
e.val = val;
else {
delta = -1;
Node<K,V> en = e.next;
if (pred != null)
pred.next = en;
else
setTabAt(tab, i, en);
}
break;
}
pred = e;
if ((e = e.next) == null) {
val = remappingFunction.apply(key, null);
if (val != null) {
delta = 1;
pred.next =
new Node<K,V>(h, key, val, null);
}
break;
}
}
}
else if (f instanceof TreeBin) {
binCount = 1;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((r = t.root) != null)
p = r.findTreeNode(h, key, null);
else
p = null;
V pv = (p == null) ? null : p.val;
val = remappingFunction.apply(key, pv);
if (val != null) {
if (p != null)
p.val = val;
else {
delta = 1;
t.putTreeVal(h, key, val);
}
}
else if (p != null) {
delta = -1;
if (t.removeTreeNode(p))
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
break;
}
}
}
if (delta != 0)
addCount((long)delta, binCount);
return val;
}
/**
* If the specified key is not already associated with a
* (non-null) value, associates it with the given value.
* Otherwise, replaces the value with the results of the given
* remapping function, or removes if {@code null}. The entire
* method invocation is performed atomically. Some attempted
* update operations on this map by other threads may be blocked
* while computation is in progress, so the computation should be
* short and simple, and must not attempt to update any other
* mappings of this Map.
*
* @param key key with which the specified value is to be associated
* @param value the value to use if absent
* @param remappingFunction the function to recompute a value if present
* @return the new value associated with the specified key, or null if none
* @throws NullPointerException if the specified key or the
* remappingFunction is null
* @throws RuntimeException or Error if the remappingFunction does so,
* in which case the mapping is unchanged
*/
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
if (key == null || value == null || remappingFunction == null)
throw new NullPointerException();
int h = spread(key.hashCode());
V val = null;
int delta = 0;
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
delta = 1;
val = value;
break;
}
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f, pred = null;; ++binCount) {
K ek;
if (e.hash == h &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
val = remappingFunction.apply(e.val, value);
if (val != null)
e.val = val;
else {
delta = -1;
Node<K,V> en = e.next;
if (pred != null)
pred.next = en;
else
setTabAt(tab, i, en);
}
break;
}
pred = e;
if ((e = e.next) == null) {
delta = 1;
val = value;
pred.next =
new Node<K,V>(h, key, val, null);
break;
}
}
}
else if (f instanceof TreeBin) {
binCount = 2;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r = t.root;
TreeNode<K,V> p = (r == null) ? null :
r.findTreeNode(h, key, null);
val = (p == null) ? value :
remappingFunction.apply(p.val, value);
if (val != null) {
if (p != null)
p.val = val;
else {
delta = 1;
t.putTreeVal(h, key, val);
}
}
else if (p != null) {
delta = -1;
if (t.removeTreeNode(p))
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
break;
}
}
}
if (delta != 0)
addCount((long)delta, binCount);
return val;
}
// Hashtable legacy methods
/**
* Legacy method testing if some key maps into the specified value
* in this table. This method is identical in functionality to
* {@link #containsValue(Object)}, and exists solely to ensure
* full compatibility with class {@link java.util.Hashtable},
* which supported this method prior to introduction of the
* Java Collections framework.
*
* @param value a value to search for
* @return {@code true} if and only if some key maps to the
* {@code value} argument in this table as
* determined by the {@code equals} method;
* {@code false} otherwise
* @throws NullPointerException if the specified value is null
*/
public boolean contains(Object value) {
return containsValue(value);
}
/**
* Returns an enumeration of the keys in this table.
*
* @return an enumeration of the keys in this table
* @see #keySet()
*/
public Enumeration<K> keys() {
Node<K,V>[] t;
int f = (t = table) == null ? 0 : t.length;
return new KeyIterator<K,V>(t, f, 0, f, this);
}
/**
* Returns an enumeration of the values in this table.
*
* @return an enumeration of the values in this table
* @see #values()
*/
public Enumeration<V> elements() {
Node<K,V>[] t;
int f = (t = table) == null ? 0 : t.length;
return new ValueIterator<K,V>(t, f, 0, f, this);
}
// ConcurrentHashMap-only methods
/**
* Returns the number of mappings. This method should be used
* instead of {@link #size} because a ConcurrentHashMap may
* contain more mappings than can be represented as an int. The
* value returned is an estimate; the actual count may differ if
* there are concurrent insertions or removals.
*
* @return the number of mappings
* @since 1.8
*/
public long mappingCount() {
long n = sumCount();
return (n < 0L) ? 0L : n; // ignore transient negative values
}
/**
* Creates a new {@link Set} backed by a ConcurrentHashMap
* from the given type to {@code Boolean.TRUE}.
*
* @param <K> the element type of the returned set
* @return the new set
* @since 1.8
*/
public static <K> KeySetView<K,Boolean> newKeySet() {
return new KeySetView<K,Boolean>
(new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
}
/**
* Creates a new {@link Set} backed by a ConcurrentHashMap
* from the given type to {@code Boolean.TRUE}.
*
* @param initialCapacity The implementation performs internal
* sizing to accommodate this many elements.
* @param <K> the element type of the returned set
* @return the new set
* @throws IllegalArgumentException if the initial capacity of
* elements is negative
* @since 1.8
*/
public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
return new KeySetView<K,Boolean>
(new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
}
/**
* Returns a {@link Set} view of the keys in this map, using the
* given common mapped value for any additions (i.e., {@link
* Collection#add} and {@link Collection#addAll(Collection)}).
* This is of course only appropriate if it is acceptable to use
* the same value for all additions from this view.
*
* @param mappedValue the mapped value to use for any additions
* @return the set view
* @throws NullPointerException if the mappedValue is null
*/
public KeySetView<K,V> keySet(V mappedValue) {
if (mappedValue == null)
throw new NullPointerException();
return new KeySetView<K,V>(this, mappedValue);
}
/* ---------------- Special Nodes -------------- */
/**
* A node inserted at head of bins during transfer operations.
*/
static final class ForwardingNode<K,V> extends Node<K,V> {
final Node<K,V>[] nextTable;
ForwardingNode(Node<K,V>[] tab) {
super(MOVED, null, null, null);
this.nextTable = tab;
}
Node<K,V> find(int h, Object k) {
// loop to avoid arbitrarily deep recursion on forwarding nodes
outer: for (Node<K,V>[] tab = nextTable;;) {
Node<K,V> e; int n;
if (k == null || tab == null || (n = tab.length) == 0 ||
(e = tabAt(tab, (n - 1) & h)) == null)
return null;
for (;;) {
int eh; K ek;
if ((eh = e.hash) == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
if (eh < 0) {
if (e instanceof ForwardingNode) {
tab = ((ForwardingNode<K,V>)e).nextTable;
continue outer;
}
else
return e.find(h, k);
}
if ((e = e.next) == null)
return null;
}
}
}
}
/**
* A place-holder node used in computeIfAbsent and compute
*/
static final class ReservationNode<K,V> extends Node<K,V> {
ReservationNode() {
super(RESERVED, null, null, null);
}
Node<K,V> find(int h, Object k) {
return null;
}
}
/* ---------------- Table Initialization and Resizing -------------- */
/**
* Returns the stamp bits for resizing a table of size n.
* Must be negative when shifted left by RESIZE_STAMP_SHIFT.
*/
static final int resizeStamp(int n) {
return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
}
/**
* Initializes table, using the size recorded in sizeCtl.
*/
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if ((tab = table) == null || tab.length == 0) {
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
/**
* Adds to count, and if table is too small and not already
* resizing, initiates transfer. If already resizing, helps
* perform transfer if work is available. Rechecks occupancy
* after a transfer to see if another resize is already needed
* because resizings are lagging additions.
*
* @param x the count to add
* @param check if <0, don't check resize, if <= 1 only check if uncontended
*/
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
fullAddCount(x, uncontended);
return;
}
if (check <= 1)
return;
s = sumCount();
}
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
int rs = resizeStamp(n);
if (sc < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
/**
* Helps transfer if a resize is in progress.
*/
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
int rs = resizeStamp(tab.length);
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}
/**
* Tries to presize table to accommodate the given number of elements.
*
* @param size number of elements (doesn't need to be perfectly accurate)
*/
private final void tryPresize(int size) {
int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
tableSizeFor(size + (size >>> 1) + 1);
int sc;
while ((sc = sizeCtl) >= 0) {
Node<K,V>[] tab = table; int n;
if (tab == null || (n = tab.length) == 0) {
n = (sc > c) ? sc : c;
if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if (table == tab) {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
}
}
else if (c <= sc || n >= MAXIMUM_CAPACITY)
break;
else if (tab == table) {
int rs = resizeStamp(n);
if (sc < 0) {
Node<K,V>[] nt;
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
}
}
}
/**
* Moves and/or copies the nodes in each bin to new table. See
* above for explanation.
*/
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
if (nextTab == null) { // initiating
try {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
transferIndex = n;
}
int nextn = nextTab.length;
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
return;
}
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
if (fh >= 0) {
int runBit = fh & n;
Node<K,V> lastRun = f;
for (Node<K,V> p = f.next; p != null; p = p.next) {
int b = p.hash & n;
if (b != runBit) {
runBit = b;
lastRun = p;
}
}
if (runBit == 0) {
ln = lastRun;
hn = null;
}
else {
hn = lastRun;
ln = null;
}
for (Node<K,V> p = f; p != lastRun; p = p.next) {
int ph = p.hash; K pk = p.key; V pv = p.val;
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
else if (f instanceof TreeBin) {
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> lo = null, loTail = null;
TreeNode<K,V> hi = null, hiTail = null;
int lc = 0, hc = 0;
for (Node<K,V> e = t.first; e != null; e = e.next) {
int h = e.hash;
TreeNode<K,V> p = new TreeNode<K,V>
(h, e.key, e.val, null, null);
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
(hc != 0) ? new TreeBin<K,V>(lo) : t;
hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
(lc != 0) ? new TreeBin<K,V>(hi) : t;
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}
/* ---------------- Counter support -------------- */
/**
* A padded cell for distributing counts. Adapted from LongAdder
* and Striped64. See their internal docs for explanation.
*/
@sun.misc.Contended static final class CounterCell {
volatile long value;
CounterCell(long x) { value = x; }
}
final long sumCount() {
CounterCell[] as = counterCells; CounterCell a;
long sum = baseCount;
if (as != null) {
for (int i = 0; i < as.length; ++i) {
if ((a = as[i]) != null)
sum += a.value;
}
}
return sum;
}
// See LongAdder version for explanation
private final void fullAddCount(long x, boolean wasUncontended) {
int h;
if ((h = ThreadLocalRandom.getProbe()) == 0) {
ThreadLocalRandom.localInit(); // force initialization
h = ThreadLocalRandom.getProbe();
wasUncontended = true;
}
boolean collide = false; // True if last slot nonempty
for (;;) {
CounterCell[] as; CounterCell a; int n; long v;
if ((as = counterCells) != null && (n = as.length) > 0) {
if ((a = as[(n - 1) & h]) == null) {
if (cellsBusy == 0) { // Try to attach new Cell
CounterCell r = new CounterCell(x); // Optimistic create
if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean created = false;
try { // Recheck under lock
CounterCell[] rs; int m, j;
if ((rs = counterCells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
cellsBusy = 0;
}
if (created)
break;
continue; // Slot is now non-empty
}
}
collide = false;
}
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
break;
else if (counterCells != as || n >= NCPU)
collide = false; // At max size or stale
else if (!collide)
collide = true;
else if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
try {
if (counterCells == as) {// Expand table unless stale
CounterCell[] rs = new CounterCell[n << 1];
for (int i = 0; i < n; ++i)
rs[i] = as[i];
counterCells = rs;
}
} finally {
cellsBusy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h = ThreadLocalRandom.advanceProbe(h);
}
else if (cellsBusy == 0 && counterCells == as &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try { // Initialize table
if (counterCells == as) {
CounterCell[] rs = new CounterCell[2];
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}
if (init)
break;
}
else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
break; // Fall back on using base
}
}
/* ---------------- Conversion from/to TreeBins -------------- */
/**
* Replaces all linked nodes in bin at given index unless table is
* too small, in which case resizes instead.
*/
private final void treeifyBin(Node<K,V>[] tab, int index) {
Node<K,V> b; int n, sc;
if (tab != null) {
if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
tryPresize(n << 1);
else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
synchronized (b) {
if (tabAt(tab, index) == b) {
TreeNode<K,V> hd = null, tl = null;
for (Node<K,V> e = b; e != null; e = e.next) {
TreeNode<K,V> p =
new TreeNode<K,V>(e.hash, e.key, e.val,
null, null);
if ((p.prev = tl) == null)
hd = p;
else
tl.next = p;
tl = p;
}
setTabAt(tab, index, new TreeBin<K,V>(hd));
}
}
}
}
}
/**
* Returns a list on non-TreeNodes replacing those in given list.
*/
static <K,V> Node<K,V> untreeify(Node<K,V> b) {
Node<K,V> hd = null, tl = null;
for (Node<K,V> q = b; q != null; q = q.next) {
Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
/* ---------------- TreeNodes -------------- */
/**
* Nodes for use in TreeBins
*/
static final class TreeNode<K,V> extends Node<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next,
TreeNode<K,V> parent) {
super(hash, key, val, next);
this.parent = parent;
}
Node<K,V> find(int h, Object k) {
return findTreeNode(h, k, null);
}
/**
* Returns the TreeNode (or null if not found) for the given key
* starting at given root.
*/
final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
if (k != null) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk; TreeNode<K,V> q;
TreeNode<K,V> pl = p.left, pr = p.right;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.findTreeNode(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
}
return null;
}
}
/* ---------------- TreeBins -------------- */
/**
* TreeNodes used at the heads of bins. TreeBins do not hold user
* keys or values, but instead point to list of TreeNodes and
* their root. They also maintain a parasitic read-write lock
* forcing writers (who hold bin lock) to wait for readers (who do
* not) to complete before tree restructuring operations.
*/
static final class TreeBin<K,V> extends Node<K,V> {
TreeNode<K,V> root;
volatile TreeNode<K,V> first;
volatile Thread waiter;
volatile int lockState;
// values for lockState
static final int WRITER = 1; // set while holding write lock
static final int WAITER = 2; // set when waiting for write lock
static final int READER = 4; // increment value for setting read lock
/**
* Tie-breaking utility for ordering insertions when equal
* hashCodes and non-comparable. We don't require a total
* order, just a consistent insertion rule to maintain
* equivalence across rebalancings. Tie-breaking further than
* necessary simplifies testing a bit.
*/
static int tieBreakOrder(Object a, Object b) {
int d;
if (a == null || b == null ||
(d = a.getClass().getName().
compareTo(b.getClass().getName())) == 0)
d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
-1 : 1);
return d;
}
/**
* Creates bin with initial set of nodes headed by b.
*/
TreeBin(TreeNode<K,V> b) {
super(TREEBIN, null, null, null);
this.first = b;
TreeNode<K,V> r = null;
for (TreeNode<K,V> x = b, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (r == null) {
x.parent = null;
x.red = false;
r = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = r;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
r = balanceInsertion(r, x);
break;
}
}
}
}
this.root = r;
assert checkInvariants(root);
}
/**
* Acquires write lock for tree restructuring.
*/
private final void lockRoot() {
if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
contendedLock(); // offload to separate method
}
/**
* Releases write lock for tree restructuring.
*/
private final void unlockRoot() {
lockState = 0;
}
/**
* Possibly blocks awaiting root lock.
*/
private final void contendedLock() {
boolean waiting = false;
for (int s;;) {
if (((s = lockState) & ~WAITER) == 0) {
if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
if (waiting)
waiter = null;
return;
}
}
else if ((s & WAITER) == 0) {
if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
waiting = true;
waiter = Thread.currentThread();
}
}
else if (waiting)
LockSupport.park(this);
}
}
/**
* Returns matching node or null if none. Tries to search
* using tree comparisons from root, but continues linear
* search when lock not available.
*/
final Node<K,V> find(int h, Object k) {
if (k != null) {
for (Node<K,V> e = first; e != null; ) {
int s; K ek;
if (((s = lockState) & (WAITER|WRITER)) != 0) {
if (e.hash == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
e = e.next;
}
else if (U.compareAndSwapInt(this, LOCKSTATE, s,
s + READER)) {
TreeNode<K,V> r, p;
try {
p = ((r = root) == null ? null :
r.findTreeNode(h, k, null));
} finally {
Thread w;
if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
(READER|WAITER) && (w = waiter) != null)
LockSupport.unpark(w);
}
return p;
}
}
}
return null;
}
/**
* Finds or adds a node.
* @return null if added
*/
final TreeNode<K,V> putTreeVal(int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if (p == null) {
first = root = new TreeNode<K,V>(h, k, v, null, null);
break;
}
else if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.findTreeNode(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.findTreeNode(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
TreeNode<K,V> x, f = first;
first = x = new TreeNode<K,V>(h, k, v, f, xp);
if (f != null)
f.prev = x;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
if (!xp.red)
x.red = true;
else {
lockRoot();
try {
root = balanceInsertion(root, x);
} finally {
unlockRoot();
}
}
break;
}
}
assert checkInvariants(root);
return null;
}
/**
* Removes the given node, that must be present before this
* call. This is messier than typical red-black deletion code
* because we cannot swap the contents of an interior node
* with a leaf successor that is pinned by "next" pointers
* that are accessible independently of lock. So instead we
* swap the tree linkages.
*
* @return true if now too small, so should be untreeified
*/
final boolean removeTreeNode(TreeNode<K,V> p) {
TreeNode<K,V> next = (TreeNode<K,V>)p.next;
TreeNode<K,V> pred = p.prev; // unlink traversal pointers
TreeNode<K,V> r, rl;
if (pred == null)
first = next;
else
pred.next = next;
if (next != null)
next.prev = pred;
if (first == null) {
root = null;
return true;
}
if ((r = root) == null || r.right == null || // too small
(rl = r.left) == null || rl.left == null)
return true;
lockRoot();
try {
TreeNode<K,V> replacement;
TreeNode<K,V> pl = p.left;
TreeNode<K,V> pr = p.right;
if (pl != null && pr != null) {
TreeNode<K,V> s = pr, sl;
while ((sl = s.left) != null) // find successor
s = sl;
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
TreeNode<K,V> sr = s.right;
TreeNode<K,V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
TreeNode<K,V> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
r = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
}
else if (pl != null)
replacement = pl;
else if (pr != null)
replacement = pr;
else
replacement = p;
if (replacement != p) {
TreeNode<K,V> pp = replacement.parent = p.parent;
if (pp == null)
r = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
root = (p.red) ? r : balanceDeletion(r, replacement);
if (p == replacement) { // detach pointers
TreeNode<K,V> pp;
if ((pp = p.parent) != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
p.parent = null;
}
}
} finally {
unlockRoot();
}
assert checkInvariants(root);
return false;
}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
x.red = true;
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
}
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
TreeNode<K,V> x) {
for (TreeNode<K,V> xp, xpl, xpr;;) {
if (x == null || x == root)
return root;
else if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (x.red) {
x.red = false;
return root;
}
else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
TreeNode<K,V> sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
}
else {
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateLeft(root, xp);
}
x = root;
}
}
}
else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateRight(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null)
x = xp;
else {
TreeNode<K,V> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
}
else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}
/**
* Recursive invariant check
*/
static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (TreeNode<K,V>)t.next;
if (tb != null && tb.next != t)
return false;
if (tn != null && tn.prev != t)
return false;
if (tp != null && t != tp.left && t != tp.right)
return false;
if (tl != null && (tl.parent != t || tl.hash > t.hash))
return false;
if (tr != null && (tr.parent != t || tr.hash < t.hash))
return false;
if (t.red && tl != null && tl.red && tr != null && tr.red)
return false;
if (tl != null && !checkInvariants(tl))
return false;
if (tr != null && !checkInvariants(tr))
return false;
return true;
}
private static final sun.misc.Unsafe U;
private static final long LOCKSTATE;
static {
try {
U = sun.misc.Unsafe.getUnsafe();
Class<?> k = TreeBin.class;
LOCKSTATE = U.objectFieldOffset
(k.getDeclaredField("lockState"));
} catch (Exception e) {
throw new Error(e);
}
}
}
/* ----------------Table Traversal -------------- */
/**
* Records the table, its length, and current traversal index for a
* traverser that must process a region of a forwarded table before
* proceeding with current table.
*/
static final class TableStack<K,V> {
int length;
int index;
Node<K,V>[] tab;
TableStack<K,V> next;
}
/**
* Encapsulates traversal for methods such as containsValue; also
* serves as a base class for other iterators and spliterators.
*
* Method advance visits once each still-valid node that was
* reachable upon iterator construction. It might miss some that
* were added to a bin after the bin was visited, which is OK wrt
* consistency guarantees. Maintaining this property in the face
* of possible ongoing resizes requires a fair amount of
* bookkeeping state that is difficult to optimize away amidst
* volatile accesses. Even so, traversal maintains reasonable
* throughput.
*
* Normally, iteration proceeds bin-by-bin traversing lists.
* However, if the table has been resized, then all future steps
* must traverse both the bin at the current index as well as at
* (index + baseSize); and so on for further resizings. To
* paranoically cope with potential sharing by users of iterators
* across threads, iteration terminates if a bounds checks fails
* for a table read.
*/
static class Traverser<K,V> {
Node<K,V>[] tab; // current table; updated if resized
Node<K,V> next; // the next entry to use
TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
int index; // index of bin to use next
int baseIndex; // current index of initial table
int baseLimit; // index bound for initial table
final int baseSize; // initial table size
Traverser(Node<K,V>[] tab, int size, int index, int limit) {
this.tab = tab;
this.baseSize = size;
this.baseIndex = this.index = index;
this.baseLimit = limit;
this.next = null;
}
/**
* Advances if possible, returning next valid node, or null if none.
*/
final Node<K,V> advance() {
Node<K,V> e;
if ((e = next) != null)
e = e.next;
for (;;) {
Node<K,V>[] t; int i, n; // must use locals in checks
if (e != null)
return next = e;
if (baseIndex >= baseLimit || (t = tab) == null ||
(n = t.length) <= (i = index) || i < 0)
return next = null;
if ((e = tabAt(t, i)) != null && e.hash < 0) {
if (e instanceof ForwardingNode) {
tab = ((ForwardingNode<K,V>)e).nextTable;
e = null;
pushState(t, i, n);
continue;
}
else if (e instanceof TreeBin)
e = ((TreeBin<K,V>)e).first;
else
e = null;
}
if (stack != null)
recoverState(n);
else if ((index = i + baseSize) >= n)
index = ++baseIndex; // visit upper slots if present
}
}
/**
* Saves traversal state upon encountering a forwarding node.
*/
private void pushState(Node<K,V>[] t, int i, int n) {
TableStack<K,V> s = spare; // reuse if possible
if (s != null)
spare = s.next;
else
s = new TableStack<K,V>();
s.tab = t;
s.length = n;
s.index = i;
s.next = stack;
stack = s;
}
/**
* Possibly pops traversal state.
*
* @param n length of current table
*/
private void recoverState(int n) {
TableStack<K,V> s; int len;
while ((s = stack) != null && (index += (len = s.length)) >= n) {
n = len;
index = s.index;
tab = s.tab;
s.tab = null;
TableStack<K,V> next = s.next;
s.next = spare; // save for reuse
stack = next;
spare = s;
}
if (s == null && (index += baseSize) >= n)
index = ++baseIndex;
}
}
/**
* Base of key, value, and entry Iterators. Adds fields to
* Traverser to support iterator.remove.
*/
static class BaseIterator<K,V> extends Traverser<K,V> {
final ConcurrentHashMap<K,V> map;
Node<K,V> lastReturned;
BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
ConcurrentHashMap<K,V> map) {
super(tab, size, index, limit);
this.map = map;
advance();
}
public final boolean hasNext() { return next != null; }
public final boolean hasMoreElements() { return next != null; }
public final void remove() {
Node<K,V> p;
if ((p = lastReturned) == null)
throw new IllegalStateException();
lastReturned = null;
map.replaceNode(p.key, null, null);
}
}
static final class KeyIterator<K,V> extends BaseIterator<K,V>
implements Iterator<K>, Enumeration<K> {
KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
ConcurrentHashMap<K,V> map) {
super(tab, index, size, limit, map);
}
public final K next() {
Node<K,V> p;
if ((p = next) == null)
throw new NoSuchElementException();
K k = p.key;
lastReturned = p;
advance();
return k;
}
public final K nextElement() { return next(); }
}
static final class ValueIterator<K,V> extends BaseIterator<K,V>
implements Iterator<V>, Enumeration<V> {
ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
ConcurrentHashMap<K,V> map) {
super(tab, index, size, limit, map);
}
public final V next() {
Node<K,V> p;
if ((p = next) == null)
throw new NoSuchElementException();
V v = p.val;
lastReturned = p;
advance();
return v;
}
public final V nextElement() { return next(); }
}
static final class EntryIterator<K,V> extends BaseIterator<K,V>
implements Iterator<Map.Entry<K,V>> {
EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
ConcurrentHashMap<K,V> map) {
super(tab, index, size, limit, map);
}
public final Map.Entry<K,V> next() {
Node<K,V> p;
if ((p = next) == null)
throw new NoSuchElementException();
K k = p.key;
V v = p.val;
lastReturned = p;
advance();
return new MapEntry<K,V>(k, v, map);
}
}
/**
* Exported Entry for EntryIterator
*/
static final class MapEntry<K,V> implements Map.Entry<K,V> {
final K key; // non-null
V val; // non-null
final ConcurrentHashMap<K,V> map;
MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
this.key = key;
this.val = val;
this.map = map;
}
public K getKey() { return key; }
public V getValue() { return val; }
public int hashCode() { return key.hashCode() ^ val.hashCode(); }
public String toString() { return key + "=" + val; }
public boolean equals(Object o) {
Object k, v; Map.Entry<?,?> e;
return ((o instanceof Map.Entry) &&
(k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
(v = e.getValue()) != null &&
(k == key || k.equals(key)) &&
(v == val || v.equals(val)));
}
/**
* Sets our entry's value and writes through to the map. The
* value to return is somewhat arbitrary here. Since we do not
* necessarily track asynchronous changes, the most recent
* "previous" value could be different from what we return (or
* could even have been removed, in which case the put will
* re-establish). We do not and cannot guarantee more.
*/
public V setValue(V value) {
if (value == null) throw new NullPointerException();
V v = val;
val = value;
map.put(key, value);
return v;
}
}
static final class KeySpliterator<K,V> extends Traverser<K,V>
implements Spliterator<K> {
long est; // size estimate
KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
long est) {
super(tab, size, index, limit);
this.est = est;
}
public Spliterator<K> trySplit() {
int i, f, h;
return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
f, est >>>= 1);
}
public void forEachRemaining(Consumer<? super K> action) {
if (action == null) throw new NullPointerException();
for (Node<K,V> p; (p = advance()) != null;)
action.accept(p.key);
}
public boolean tryAdvance(Consumer<? super K> action) {
if (action == null) throw new NullPointerException();
Node<K,V> p;
if ((p = advance()) == null)
return false;
action.accept(p.key);
return true;
}
public long estimateSize() { return est; }
public int characteristics() {
return Spliterator.DISTINCT | Spliterator.CONCURRENT |
Spliterator.NONNULL;
}
}
static final class ValueSpliterator<K,V> extends Traverser<K,V>
implements Spliterator<V> {
long est; // size estimate
ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
long est) {
super(tab, size, index, limit);
this.est = est;
}
public Spliterator<V> trySplit() {
int i, f, h;
return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
f, est >>>= 1);
}
public void forEachRemaining(Consumer<? super V> action) {
if (action == null) throw new NullPointerException();
for (Node<K,V> p; (p = advance()) != null;)
action.accept(p.val);
}
public boolean tryAdvance(Consumer<? super V> action) {
if (action == null) throw new NullPointerException();
Node<K,V> p;
if ((p = advance()) == null)
return false;
action.accept(p.val);
return true;
}
public long estimateSize() { return est; }
public int characteristics() {
return Spliterator.CONCURRENT | Spliterator.NONNULL;
}
}
static final class EntrySpliterator<K,V> extends Traverser<K,V>
implements Spliterator<Map.Entry<K,V>> {
final ConcurrentHashMap<K,V> map; // To export MapEntry
long est; // size estimate
EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
long est, ConcurrentHashMap<K,V> map) {
super(tab, size, index, limit);
this.map = map;
this.est = est;
}
public Spliterator<Map.Entry<K,V>> trySplit() {
int i, f, h;
return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
f, est >>>= 1, map);
}
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
for (Node<K,V> p; (p = advance()) != null; )
action.accept(new MapEntry<K,V>(p.key, p.val, map));
}
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
Node<K,V> p;
if ((p = advance()) == null)
return false;
action.accept(new MapEntry<K,V>(p.key, p.val, map));
return true;
}
public long estimateSize() { return est; }
public int characteristics() {
return Spliterator.DISTINCT | Spliterator.CONCURRENT |
Spliterator.NONNULL;
}
}
// Parallel bulk operations
/**
* Computes initial batch value for bulk tasks. The returned value
* is approximately exp2 of the number of times (minus one) to
* split task by two before executing leaf action. This value is
* faster to compute and more convenient to use as a guide to
* splitting than is the depth, since it is used while dividing by
* two anyway.
*/
final int batchFor(long b) {
long n;
if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
return 0;
int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
}
/**
* Performs the given action for each (key, value).
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param action the action
* @since 1.8
*/
public void forEach(long parallelismThreshold,
BiConsumer<? super K,? super V> action) {
if (action == null) throw new NullPointerException();
new ForEachMappingTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
action).invoke();
}
/**
* Performs the given action for each non-null transformation
* of each (key, value).
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element, or null if there is no transformation (in
* which case the action is not applied)
* @param action the action
* @param <U> the return type of the transformer
* @since 1.8
*/
public <U> void forEach(long parallelismThreshold,
BiFunction<? super K, ? super V, ? extends U> transformer,
Consumer<? super U> action) {
if (transformer == null || action == null)
throw new NullPointerException();
new ForEachTransformedMappingTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
transformer, action).invoke();
}
/**
* Returns a non-null result from applying the given search
* function on each (key, value), or null if none. Upon
* success, further element processing is suppressed and the
* results of any other parallel invocations of the search
* function are ignored.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param searchFunction a function returning a non-null
* result on success, else null
* @param <U> the return type of the search function
* @return a non-null result from applying the given search
* function on each (key, value), or null if none
* @since 1.8
*/
public <U> U search(long parallelismThreshold,
BiFunction<? super K, ? super V, ? extends U> searchFunction) {
if (searchFunction == null) throw new NullPointerException();
return new SearchMappingsTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
searchFunction, new AtomicReference<U>()).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all (key, value) pairs using the given reducer to
* combine values, or null if none.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element, or null if there is no transformation (in
* which case it is not combined)
* @param reducer a commutative associative combining function
* @param <U> the return type of the transformer
* @return the result of accumulating the given transformation
* of all (key, value) pairs
* @since 1.8
*/
public <U> U reduce(long parallelismThreshold,
BiFunction<? super K, ? super V, ? extends U> transformer,
BiFunction<? super U, ? super U, ? extends U> reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceMappingsTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all (key, value) pairs using the given reducer to
* combine values, and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all (key, value) pairs
* @since 1.8
*/
public double reduceToDouble(long parallelismThreshold,
ToDoubleBiFunction<? super K, ? super V> transformer,
double basis,
DoubleBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceMappingsToDoubleTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all (key, value) pairs using the given reducer to
* combine values, and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all (key, value) pairs
* @since 1.8
*/
public long reduceToLong(long parallelismThreshold,
ToLongBiFunction<? super K, ? super V> transformer,
long basis,
LongBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceMappingsToLongTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all (key, value) pairs using the given reducer to
* combine values, and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all (key, value) pairs
* @since 1.8
*/
public int reduceToInt(long parallelismThreshold,
ToIntBiFunction<? super K, ? super V> transformer,
int basis,
IntBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceMappingsToIntTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Performs the given action for each key.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param action the action
* @since 1.8
*/
public void forEachKey(long parallelismThreshold,
Consumer<? super K> action) {
if (action == null) throw new NullPointerException();
new ForEachKeyTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
action).invoke();
}
/**
* Performs the given action for each non-null transformation
* of each key.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element, or null if there is no transformation (in
* which case the action is not applied)
* @param action the action
* @param <U> the return type of the transformer
* @since 1.8
*/
public <U> void forEachKey(long parallelismThreshold,
Function<? super K, ? extends U> transformer,
Consumer<? super U> action) {
if (transformer == null || action == null)
throw new NullPointerException();
new ForEachTransformedKeyTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
transformer, action).invoke();
}
/**
* Returns a non-null result from applying the given search
* function on each key, or null if none. Upon success,
* further element processing is suppressed and the results of
* any other parallel invocations of the search function are
* ignored.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param searchFunction a function returning a non-null
* result on success, else null
* @param <U> the return type of the search function
* @return a non-null result from applying the given search
* function on each key, or null if none
* @since 1.8
*/
public <U> U searchKeys(long parallelismThreshold,
Function<? super K, ? extends U> searchFunction) {
if (searchFunction == null) throw new NullPointerException();
return new SearchKeysTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
searchFunction, new AtomicReference<U>()).invoke();
}
/**
* Returns the result of accumulating all keys using the given
* reducer to combine values, or null if none.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param reducer a commutative associative combining function
* @return the result of accumulating all keys using the given
* reducer to combine values, or null if none
* @since 1.8
*/
public K reduceKeys(long parallelismThreshold,
BiFunction<? super K, ? super K, ? extends K> reducer) {
if (reducer == null) throw new NullPointerException();
return new ReduceKeysTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all keys using the given reducer to combine values, or
* null if none.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element, or null if there is no transformation (in
* which case it is not combined)
* @param reducer a commutative associative combining function
* @param <U> the return type of the transformer
* @return the result of accumulating the given transformation
* of all keys
* @since 1.8
*/
public <U> U reduceKeys(long parallelismThreshold,
Function<? super K, ? extends U> transformer,
BiFunction<? super U, ? super U, ? extends U> reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceKeysTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all keys using the given reducer to combine values, and
* the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all keys
* @since 1.8
*/
public double reduceKeysToDouble(long parallelismThreshold,
ToDoubleFunction<? super K> transformer,
double basis,
DoubleBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceKeysToDoubleTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all keys using the given reducer to combine values, and
* the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all keys
* @since 1.8
*/
public long reduceKeysToLong(long parallelismThreshold,
ToLongFunction<? super K> transformer,
long basis,
LongBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceKeysToLongTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all keys using the given reducer to combine values, and
* the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all keys
* @since 1.8
*/
public int reduceKeysToInt(long parallelismThreshold,
ToIntFunction<? super K> transformer,
int basis,
IntBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceKeysToIntTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Performs the given action for each value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param action the action
* @since 1.8
*/
public void forEachValue(long parallelismThreshold,
Consumer<? super V> action) {
if (action == null)
throw new NullPointerException();
new ForEachValueTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
action).invoke();
}
/**
* Performs the given action for each non-null transformation
* of each value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element, or null if there is no transformation (in
* which case the action is not applied)
* @param action the action
* @param <U> the return type of the transformer
* @since 1.8
*/
public <U> void forEachValue(long parallelismThreshold,
Function<? super V, ? extends U> transformer,
Consumer<? super U> action) {
if (transformer == null || action == null)
throw new NullPointerException();
new ForEachTransformedValueTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
transformer, action).invoke();
}
/**
* Returns a non-null result from applying the given search
* function on each value, or null if none. Upon success,
* further element processing is suppressed and the results of
* any other parallel invocations of the search function are
* ignored.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param searchFunction a function returning a non-null
* result on success, else null
* @param <U> the return type of the search function
* @return a non-null result from applying the given search
* function on each value, or null if none
* @since 1.8
*/
public <U> U searchValues(long parallelismThreshold,
Function<? super V, ? extends U> searchFunction) {
if (searchFunction == null) throw new NullPointerException();
return new SearchValuesTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
searchFunction, new AtomicReference<U>()).invoke();
}
/**
* Returns the result of accumulating all values using the
* given reducer to combine values, or null if none.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param reducer a commutative associative combining function
* @return the result of accumulating all values
* @since 1.8
*/
public V reduceValues(long parallelismThreshold,
BiFunction<? super V, ? super V, ? extends V> reducer) {
if (reducer == null) throw new NullPointerException();
return new ReduceValuesTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all values using the given reducer to combine values, or
* null if none.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element, or null if there is no transformation (in
* which case it is not combined)
* @param reducer a commutative associative combining function
* @param <U> the return type of the transformer
* @return the result of accumulating the given transformation
* of all values
* @since 1.8
*/
public <U> U reduceValues(long parallelismThreshold,
Function<? super V, ? extends U> transformer,
BiFunction<? super U, ? super U, ? extends U> reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceValuesTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all values using the given reducer to combine values,
* and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all values
* @since 1.8
*/
public double reduceValuesToDouble(long parallelismThreshold,
ToDoubleFunction<? super V> transformer,
double basis,
DoubleBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceValuesToDoubleTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all values using the given reducer to combine values,
* and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all values
* @since 1.8
*/
public long reduceValuesToLong(long parallelismThreshold,
ToLongFunction<? super V> transformer,
long basis,
LongBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceValuesToLongTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all values using the given reducer to combine values,
* and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all values
* @since 1.8
*/
public int reduceValuesToInt(long parallelismThreshold,
ToIntFunction<? super V> transformer,
int basis,
IntBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceValuesToIntTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Performs the given action for each entry.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param action the action
* @since 1.8
*/
public void forEachEntry(long parallelismThreshold,
Consumer<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
action).invoke();
}
/**
* Performs the given action for each non-null transformation
* of each entry.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element, or null if there is no transformation (in
* which case the action is not applied)
* @param action the action
* @param <U> the return type of the transformer
* @since 1.8
*/
public <U> void forEachEntry(long parallelismThreshold,
Function<Map.Entry<K,V>, ? extends U> transformer,
Consumer<? super U> action) {
if (transformer == null || action == null)
throw new NullPointerException();
new ForEachTransformedEntryTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
transformer, action).invoke();
}
/**
* Returns a non-null result from applying the given search
* function on each entry, or null if none. Upon success,
* further element processing is suppressed and the results of
* any other parallel invocations of the search function are
* ignored.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param searchFunction a function returning a non-null
* result on success, else null
* @param <U> the return type of the search function
* @return a non-null result from applying the given search
* function on each entry, or null if none
* @since 1.8
*/
public <U> U searchEntries(long parallelismThreshold,
Function<Map.Entry<K,V>, ? extends U> searchFunction) {
if (searchFunction == null) throw new NullPointerException();
return new SearchEntriesTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
searchFunction, new AtomicReference<U>()).invoke();
}
/**
* Returns the result of accumulating all entries using the
* given reducer to combine values, or null if none.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param reducer a commutative associative combining function
* @return the result of accumulating all entries
* @since 1.8
*/
public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
if (reducer == null) throw new NullPointerException();
return new ReduceEntriesTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all entries using the given reducer to combine values,
* or null if none.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element, or null if there is no transformation (in
* which case it is not combined)
* @param reducer a commutative associative combining function
* @param <U> the return type of the transformer
* @return the result of accumulating the given transformation
* of all entries
* @since 1.8
*/
public <U> U reduceEntries(long parallelismThreshold,
Function<Map.Entry<K,V>, ? extends U> transformer,
BiFunction<? super U, ? super U, ? extends U> reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceEntriesTask<K,V,U>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all entries using the given reducer to combine values,
* and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all entries
* @since 1.8
*/
public double reduceEntriesToDouble(long parallelismThreshold,
ToDoubleFunction<Map.Entry<K,V>> transformer,
double basis,
DoubleBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceEntriesToDoubleTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all entries using the given reducer to combine values,
* and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all entries
* @since 1.8
*/
public long reduceEntriesToLong(long parallelismThreshold,
ToLongFunction<Map.Entry<K,V>> transformer,
long basis,
LongBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceEntriesToLongTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/**
* Returns the result of accumulating the given transformation
* of all entries using the given reducer to combine values,
* and the given basis as an identity value.
*
* @param parallelismThreshold the (estimated) number of elements
* needed for this operation to be executed in parallel
* @param transformer a function returning the transformation
* for an element
* @param basis the identity (initial default value) for the reduction
* @param reducer a commutative associative combining function
* @return the result of accumulating the given transformation
* of all entries
* @since 1.8
*/
public int reduceEntriesToInt(long parallelismThreshold,
ToIntFunction<Map.Entry<K,V>> transformer,
int basis,
IntBinaryOperator reducer) {
if (transformer == null || reducer == null)
throw new NullPointerException();
return new MapReduceEntriesToIntTask<K,V>
(null, batchFor(parallelismThreshold), 0, 0, table,
null, transformer, basis, reducer).invoke();
}
/* ----------------Views -------------- */
/**
* Base class for views.
*/
abstract static class CollectionView<K,V,E>
implements Collection<E>, java.io.Serializable {
private static final long serialVersionUID = 7249069246763182397L;
final ConcurrentHashMap<K,V> map;
CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
/**
* Returns the map backing this view.
*
* @return the map backing this view
*/
public ConcurrentHashMap<K,V> getMap() { return map; }
/**
* Removes all of the elements from this view, by removing all
* the mappings from the map backing this view.
*/
public final void clear() { map.clear(); }
public final int size() { return map.size(); }
public final boolean isEmpty() { return map.isEmpty(); }
// implementations below rely on concrete classes supplying these
// abstract methods
/**
* Returns an iterator over the elements in this collection.
*
* <p>The returned iterator is
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* @return an iterator over the elements in this collection
*/
public abstract Iterator<E> iterator();
public abstract boolean contains(Object o);
public abstract boolean remove(Object o);
private static final String oomeMsg = "Required array size too large";
public final Object[] toArray() {
long sz = map.mappingCount();
if (sz > MAX_ARRAY_SIZE)
throw new OutOfMemoryError(oomeMsg);
int n = (int)sz;
Object[] r = new Object[n];
int i = 0;
for (E e : this) {
if (i == n) {
if (n >= MAX_ARRAY_SIZE)
throw new OutOfMemoryError(oomeMsg);
if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
n = MAX_ARRAY_SIZE;
else
n += (n >>> 1) + 1;
r = Arrays.copyOf(r, n);
}
r[i++] = e;
}
return (i == n) ? r : Arrays.copyOf(r, i);
}
@SuppressWarnings("unchecked")
public final <T> T[] toArray(T[] a) {
long sz = map.mappingCount();
if (sz > MAX_ARRAY_SIZE)
throw new OutOfMemoryError(oomeMsg);
int m = (int)sz;
T[] r = (a.length >= m) ? a :
(T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), m);
int n = r.length;
int i = 0;
for (E e : this) {
if (i == n) {
if (n >= MAX_ARRAY_SIZE)
throw new OutOfMemoryError(oomeMsg);
if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
n = MAX_ARRAY_SIZE;
else
n += (n >>> 1) + 1;
r = Arrays.copyOf(r, n);
}
r[i++] = (T)e;
}
if (a == r && i < n) {
r[i] = null; // null-terminate
return r;
}
return (i == n) ? r : Arrays.copyOf(r, i);
}
/**
* Returns a string representation of this collection.
* The string representation consists of the string representations
* of the collection's elements in the order they are returned by
* its iterator, enclosed in square brackets ({@code "[]"}).
* Adjacent elements are separated by the characters {@code ", "}
* (comma and space). Elements are converted to strings as by
* {@link String#valueOf(Object)}.
*
* @return a string representation of this collection
*/
public final String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
Iterator<E> it = iterator();
if (it.hasNext()) {
for (;;) {
Object e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (!it.hasNext())
break;
sb.append(',').append(' ');
}
}
return sb.append(']').toString();
}
public final boolean containsAll(Collection<?> c) {
if (c != this) {
for (Object e : c) {
if (e == null || !contains(e))
return false;
}
}
return true;
}
public final boolean removeAll(Collection<?> c) {
if (c == null) throw new NullPointerException();
boolean modified = false;
for (Iterator<E> it = iterator(); it.hasNext();) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
public final boolean retainAll(Collection<?> c) {
if (c == null) throw new NullPointerException();
boolean modified = false;
for (Iterator<E> it = iterator(); it.hasNext();) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
}
/**
* A view of a ConcurrentHashMap as a {@link Set} of keys, in
* which additions may optionally be enabled by mapping to a
* common value. This class cannot be directly instantiated.
* See {@link #keySet() keySet()},
* {@link #keySet(Object) keySet(V)},
* {@link #newKeySet() newKeySet()},
* {@link #newKeySet(int) newKeySet(int)}.
*
* @since 1.8
*/
public static class KeySetView<K,V> extends CollectionView<K,V,K>
implements Set<K>, java.io.Serializable {
private static final long serialVersionUID = 7249069246763182397L;
private final V value;
KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
super(map);
this.value = value;
}
/**
* Returns the default mapped value for additions,
* or {@code null} if additions are not supported.
*
* @return the default mapped value for additions, or {@code null}
* if not supported
*/
public V getMappedValue() { return value; }
/**
* {@inheritDoc}
* @throws NullPointerException if the specified key is null
*/
public boolean contains(Object o) { return map.containsKey(o); }
/**
* Removes the key from this map view, by removing the key (and its
* corresponding value) from the backing map. This method does
* nothing if the key is not in the map.
*
* @param o the key to be removed from the backing map
* @return {@code true} if the backing map contained the specified key
* @throws NullPointerException if the specified key is null
*/
public boolean remove(Object o) { return map.remove(o) != null; }
/**
* @return an iterator over the keys of the backing map
*/
public Iterator<K> iterator() {
Node<K,V>[] t;
ConcurrentHashMap<K,V> m = map;
int f = (t = m.table) == null ? 0 : t.length;
return new KeyIterator<K,V>(t, f, 0, f, m);
}
/**
* Adds the specified key to this set view by mapping the key to
* the default mapped value in the backing map, if defined.
*
* @param e key to be added
* @return {@code true} if this set changed as a result of the call
* @throws NullPointerException if the specified key is null
* @throws UnsupportedOperationException if no default mapped value
* for additions was provided
*/
public boolean add(K e) {
V v;
if ((v = value) == null)
throw new UnsupportedOperationException();
return map.putVal(e, v, true) == null;
}
/**
* Adds all of the elements in the specified collection to this set,
* as if by calling {@link #add} on each one.
*
* @param c the elements to be inserted into this set
* @return {@code true} if this set changed as a result of the call
* @throws NullPointerException if the collection or any of its
* elements are {@code null}
* @throws UnsupportedOperationException if no default mapped value
* for additions was provided
*/
public boolean addAll(Collection<? extends K> c) {
boolean added = false;
V v;
if ((v = value) == null)
throw new UnsupportedOperationException();
for (K e : c) {
if (map.putVal(e, v, true) == null)
added = true;
}
return added;
}
public int hashCode() {
int h = 0;
for (K e : this)
h += e.hashCode();
return h;
}
public boolean equals(Object o) {
Set<?> c;
return ((o instanceof Set) &&
((c = (Set<?>)o) == this ||
(containsAll(c) && c.containsAll(this))));
}
public Spliterator<K> spliterator() {
Node<K,V>[] t;
ConcurrentHashMap<K,V> m = map;
long n = m.sumCount();
int f = (t = m.table) == null ? 0 : t.length;
return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
}
public void forEach(Consumer<? super K> action) {
if (action == null) throw new NullPointerException();
Node<K,V>[] t;
if ((t = map.table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; )
action.accept(p.key);
}
}
}
/**
* A view of a ConcurrentHashMap as a {@link Collection} of
* values, in which additions are disabled. This class cannot be
* directly instantiated. See {@link #values()}.
*/
static final class ValuesView<K,V> extends CollectionView<K,V,V>
implements Collection<V>, java.io.Serializable {
private static final long serialVersionUID = 2249069246763182397L;
ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
public final boolean contains(Object o) {
return map.containsValue(o);
}
public final boolean remove(Object o) {
if (o != null) {
for (Iterator<V> it = iterator(); it.hasNext();) {
if (o.equals(it.next())) {
it.remove();
return true;
}
}
}
return false;
}
public final Iterator<V> iterator() {
ConcurrentHashMap<K,V> m = map;
Node<K,V>[] t;
int f = (t = m.table) == null ? 0 : t.length;
return new ValueIterator<K,V>(t, f, 0, f, m);
}
public final boolean add(V e) {
throw new UnsupportedOperationException();
}
public final boolean addAll(Collection<? extends V> c) {
throw new UnsupportedOperationException();
}
public Spliterator<V> spliterator() {
Node<K,V>[] t;
ConcurrentHashMap<K,V> m = map;
long n = m.sumCount();
int f = (t = m.table) == null ? 0 : t.length;
return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
}
public void forEach(Consumer<? super V> action) {
if (action == null) throw new NullPointerException();
Node<K,V>[] t;
if ((t = map.table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; )
action.accept(p.val);
}
}
}
/**
* A view of a ConcurrentHashMap as a {@link Set} of (key, value)
* entries. This class cannot be directly instantiated. See
* {@link #entrySet()}.
*/
static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
implements Set<Map.Entry<K,V>>, java.io.Serializable {
private static final long serialVersionUID = 2249069246763182397L;
EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
public boolean contains(Object o) {
Object k, v, r; Map.Entry<?,?> e;
return ((o instanceof Map.Entry) &&
(k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
(r = map.get(k)) != null &&
(v = e.getValue()) != null &&
(v == r || v.equals(r)));
}
public boolean remove(Object o) {
Object k, v; Map.Entry<?,?> e;
return ((o instanceof Map.Entry) &&
(k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
(v = e.getValue()) != null &&
map.remove(k, v));
}
/**
* @return an iterator over the entries of the backing map
*/
public Iterator<Map.Entry<K,V>> iterator() {
ConcurrentHashMap<K,V> m = map;
Node<K,V>[] t;
int f = (t = m.table) == null ? 0 : t.length;
return new EntryIterator<K,V>(t, f, 0, f, m);
}
public boolean add(Entry<K,V> e) {
return map.putVal(e.getKey(), e.getValue(), false) == null;
}
public boolean addAll(Collection<? extends Entry<K,V>> c) {
boolean added = false;
for (Entry<K,V> e : c) {
if (add(e))
added = true;
}
return added;
}
public final int hashCode() {
int h = 0;
Node<K,V>[] t;
if ((t = map.table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; ) {
h += p.hashCode();
}
}
return h;
}
public final boolean equals(Object o) {
Set<?> c;
return ((o instanceof Set) &&
((c = (Set<?>)o) == this ||
(containsAll(c) && c.containsAll(this))));
}
public Spliterator<Map.Entry<K,V>> spliterator() {
Node<K,V>[] t;
ConcurrentHashMap<K,V> m = map;
long n = m.sumCount();
int f = (t = m.table) == null ? 0 : t.length;
return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
}
public void forEach(Consumer<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
Node<K,V>[] t;
if ((t = map.table) != null) {
Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
for (Node<K,V> p; (p = it.advance()) != null; )
action.accept(new MapEntry<K,V>(p.key, p.val, map));
}
}
}
// -------------------------------------------------------
/**
* Base class for bulk tasks. Repeats some fields and code from
* class Traverser, because we need to subclass CountedCompleter.
*/
@SuppressWarnings("serial")
abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
Node<K,V>[] tab; // same as Traverser
Node<K,V> next;
TableStack<K,V> stack, spare;
int index;
int baseIndex;
int baseLimit;
final int baseSize;
int batch; // split control
BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
super(par);
this.batch = b;
this.index = this.baseIndex = i;
if ((this.tab = t) == null)
this.baseSize = this.baseLimit = 0;
else if (par == null)
this.baseSize = this.baseLimit = t.length;
else {
this.baseLimit = f;
this.baseSize = par.baseSize;
}
}
/**
* Same as Traverser version
*/
final Node<K,V> advance() {
Node<K,V> e;
if ((e = next) != null)
e = e.next;
for (;;) {
Node<K,V>[] t; int i, n;
if (e != null)
return next = e;
if (baseIndex >= baseLimit || (t = tab) == null ||
(n = t.length) <= (i = index) || i < 0)
return next = null;
if ((e = tabAt(t, i)) != null && e.hash < 0) {
if (e instanceof ForwardingNode) {
tab = ((ForwardingNode<K,V>)e).nextTable;
e = null;
pushState(t, i, n);
continue;
}
else if (e instanceof TreeBin)
e = ((TreeBin<K,V>)e).first;
else
e = null;
}
if (stack != null)
recoverState(n);
else if ((index = i + baseSize) >= n)
index = ++baseIndex;
}
}
private void pushState(Node<K,V>[] t, int i, int n) {
TableStack<K,V> s = spare;
if (s != null)
spare = s.next;
else
s = new TableStack<K,V>();
s.tab = t;
s.length = n;
s.index = i;
s.next = stack;
stack = s;
}
private void recoverState(int n) {
TableStack<K,V> s; int len;
while ((s = stack) != null && (index += (len = s.length)) >= n) {
n = len;
index = s.index;
tab = s.tab;
s.tab = null;
TableStack<K,V> next = s.next;
s.next = spare; // save for reuse
stack = next;
spare = s;
}
if (s == null && (index += baseSize) >= n)
index = ++baseIndex;
}
}
/*
* Task classes. Coded in a regular but ugly format/style to
* simplify checks that each variant differs in the right way from
* others. The null screenings exist because compilers cannot tell
* that we've already null-checked task arguments, so we force
* simplest hoisted bypass to help avoid convoluted traps.
*/
@SuppressWarnings("serial")
static final class ForEachKeyTask<K,V>
extends BulkTask<K,V,Void> {
final Consumer<? super K> action;
ForEachKeyTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Consumer<? super K> action) {
super(p, b, i, f, t);
this.action = action;
}
public final void compute() {
final Consumer<? super K> action;
if ((action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachKeyTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
action).fork();
}
for (Node<K,V> p; (p = advance()) != null;)
action.accept(p.key);
propagateCompletion();
}
}
}
@SuppressWarnings("serial")
static final class ForEachValueTask<K,V>
extends BulkTask<K,V,Void> {
final Consumer<? super V> action;
ForEachValueTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Consumer<? super V> action) {
super(p, b, i, f, t);
this.action = action;
}
public final void compute() {
final Consumer<? super V> action;
if ((action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachValueTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
action).fork();
}
for (Node<K,V> p; (p = advance()) != null;)
action.accept(p.val);
propagateCompletion();
}
}
}
@SuppressWarnings("serial")
static final class ForEachEntryTask<K,V>
extends BulkTask<K,V,Void> {
final Consumer<? super Entry<K,V>> action;
ForEachEntryTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Consumer<? super Entry<K,V>> action) {
super(p, b, i, f, t);
this.action = action;
}
public final void compute() {
final Consumer<? super Entry<K,V>> action;
if ((action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachEntryTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
action).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
action.accept(p);
propagateCompletion();
}
}
}
@SuppressWarnings("serial")
static final class ForEachMappingTask<K,V>
extends BulkTask<K,V,Void> {
final BiConsumer<? super K, ? super V> action;
ForEachMappingTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
BiConsumer<? super K,? super V> action) {
super(p, b, i, f, t);
this.action = action;
}
public final void compute() {
final BiConsumer<? super K, ? super V> action;
if ((action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachMappingTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
action).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
action.accept(p.key, p.val);
propagateCompletion();
}
}
}
@SuppressWarnings("serial")
static final class ForEachTransformedKeyTask<K,V,U>
extends BulkTask<K,V,Void> {
final Function<? super K, ? extends U> transformer;
final Consumer<? super U> action;
ForEachTransformedKeyTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
super(p, b, i, f, t);
this.transformer = transformer; this.action = action;
}
public final void compute() {
final Function<? super K, ? extends U> transformer;
final Consumer<? super U> action;
if ((transformer = this.transformer) != null &&
(action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachTransformedKeyTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
transformer, action).fork();
}
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p.key)) != null)
action.accept(u);
}
propagateCompletion();
}
}
}
@SuppressWarnings("serial")
static final class ForEachTransformedValueTask<K,V,U>
extends BulkTask<K,V,Void> {
final Function<? super V, ? extends U> transformer;
final Consumer<? super U> action;
ForEachTransformedValueTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
super(p, b, i, f, t);
this.transformer = transformer; this.action = action;
}
public final void compute() {
final Function<? super V, ? extends U> transformer;
final Consumer<? super U> action;
if ((transformer = this.transformer) != null &&
(action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachTransformedValueTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
transformer, action).fork();
}
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p.val)) != null)
action.accept(u);
}
propagateCompletion();
}
}
}
@SuppressWarnings("serial")
static final class ForEachTransformedEntryTask<K,V,U>
extends BulkTask<K,V,Void> {
final Function<Map.Entry<K,V>, ? extends U> transformer;
final Consumer<? super U> action;
ForEachTransformedEntryTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
super(p, b, i, f, t);
this.transformer = transformer; this.action = action;
}
public final void compute() {
final Function<Map.Entry<K,V>, ? extends U> transformer;
final Consumer<? super U> action;
if ((transformer = this.transformer) != null &&
(action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachTransformedEntryTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
transformer, action).fork();
}
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p)) != null)
action.accept(u);
}
propagateCompletion();
}
}
}
@SuppressWarnings("serial")
static final class ForEachTransformedMappingTask<K,V,U>
extends BulkTask<K,V,Void> {
final BiFunction<? super K, ? super V, ? extends U> transformer;
final Consumer<? super U> action;
ForEachTransformedMappingTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
BiFunction<? super K, ? super V, ? extends U> transformer,
Consumer<? super U> action) {
super(p, b, i, f, t);
this.transformer = transformer; this.action = action;
}
public final void compute() {
final BiFunction<? super K, ? super V, ? extends U> transformer;
final Consumer<? super U> action;
if ((transformer = this.transformer) != null &&
(action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachTransformedMappingTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
transformer, action).fork();
}
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p.key, p.val)) != null)
action.accept(u);
}
propagateCompletion();
}
}
}
@SuppressWarnings("serial")
static final class SearchKeysTask<K,V,U>
extends BulkTask<K,V,U> {
final Function<? super K, ? extends U> searchFunction;
final AtomicReference<U> result;
SearchKeysTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Function<? super K, ? extends U> searchFunction,
AtomicReference<U> result) {
super(p, b, i, f, t);
this.searchFunction = searchFunction; this.result = result;
}
public final U getRawResult() { return result.get(); }
public final void compute() {
final Function<? super K, ? extends U> searchFunction;
final AtomicReference<U> result;
if ((searchFunction = this.searchFunction) != null &&
(result = this.result) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
if (result.get() != null)
return;
addToPendingCount(1);
new SearchKeysTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
searchFunction, result).fork();
}
while (result.get() == null) {
U u;
Node<K,V> p;
if ((p = advance()) == null) {
propagateCompletion();
break;
}
if ((u = searchFunction.apply(p.key)) != null) {
if (result.compareAndSet(null, u))
quietlyCompleteRoot();
break;
}
}
}
}
}
@SuppressWarnings("serial")
static final class SearchValuesTask<K,V,U>
extends BulkTask<K,V,U> {
final Function<? super V, ? extends U> searchFunction;
final AtomicReference<U> result;
SearchValuesTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Function<? super V, ? extends U> searchFunction,
AtomicReference<U> result) {
super(p, b, i, f, t);
this.searchFunction = searchFunction; this.result = result;
}
public final U getRawResult() { return result.get(); }
public final void compute() {
final Function<? super V, ? extends U> searchFunction;
final AtomicReference<U> result;
if ((searchFunction = this.searchFunction) != null &&
(result = this.result) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
if (result.get() != null)
return;
addToPendingCount(1);
new SearchValuesTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
searchFunction, result).fork();
}
while (result.get() == null) {
U u;
Node<K,V> p;
if ((p = advance()) == null) {
propagateCompletion();
break;
}
if ((u = searchFunction.apply(p.val)) != null) {
if (result.compareAndSet(null, u))
quietlyCompleteRoot();
break;
}
}
}
}
}
@SuppressWarnings("serial")
static final class SearchEntriesTask<K,V,U>
extends BulkTask<K,V,U> {
final Function<Entry<K,V>, ? extends U> searchFunction;
final AtomicReference<U> result;
SearchEntriesTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Function<Entry<K,V>, ? extends U> searchFunction,
AtomicReference<U> result) {
super(p, b, i, f, t);
this.searchFunction = searchFunction; this.result = result;
}
public final U getRawResult() { return result.get(); }
public final void compute() {
final Function<Entry<K,V>, ? extends U> searchFunction;
final AtomicReference<U> result;
if ((searchFunction = this.searchFunction) != null &&
(result = this.result) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
if (result.get() != null)
return;
addToPendingCount(1);
new SearchEntriesTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
searchFunction, result).fork();
}
while (result.get() == null) {
U u;
Node<K,V> p;
if ((p = advance()) == null) {
propagateCompletion();
break;
}
if ((u = searchFunction.apply(p)) != null) {
if (result.compareAndSet(null, u))
quietlyCompleteRoot();
return;
}
}
}
}
}
@SuppressWarnings("serial")
static final class SearchMappingsTask<K,V,U>
extends BulkTask<K,V,U> {
final BiFunction<? super K, ? super V, ? extends U> searchFunction;
final AtomicReference<U> result;
SearchMappingsTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
BiFunction<? super K, ? super V, ? extends U> searchFunction,
AtomicReference<U> result) {
super(p, b, i, f, t);
this.searchFunction = searchFunction; this.result = result;
}
public final U getRawResult() { return result.get(); }
public final void compute() {
final BiFunction<? super K, ? super V, ? extends U> searchFunction;
final AtomicReference<U> result;
if ((searchFunction = this.searchFunction) != null &&
(result = this.result) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
if (result.get() != null)
return;
addToPendingCount(1);
new SearchMappingsTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
searchFunction, result).fork();
}
while (result.get() == null) {
U u;
Node<K,V> p;
if ((p = advance()) == null) {
propagateCompletion();
break;
}
if ((u = searchFunction.apply(p.key, p.val)) != null) {
if (result.compareAndSet(null, u))
quietlyCompleteRoot();
break;
}
}
}
}
}
@SuppressWarnings("serial")
static final class ReduceKeysTask<K,V>
extends BulkTask<K,V,K> {
final BiFunction<? super K, ? super K, ? extends K> reducer;
K result;
ReduceKeysTask<K,V> rights, nextRight;
ReduceKeysTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
ReduceKeysTask<K,V> nextRight,
BiFunction<? super K, ? super K, ? extends K> reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.reducer = reducer;
}
public final K getRawResult() { return result; }
public final void compute() {
final BiFunction<? super K, ? super K, ? extends K> reducer;
if ((reducer = this.reducer) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new ReduceKeysTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, reducer)).fork();
}
K r = null;
for (Node<K,V> p; (p = advance()) != null; ) {
K u = p.key;
r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
}
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
ReduceKeysTask<K,V>
t = (ReduceKeysTask<K,V>)c,
s = t.rights;
while (s != null) {
K tr, sr;
if ((sr = s.result) != null)
t.result = (((tr = t.result) == null) ? sr :
reducer.apply(tr, sr));
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class ReduceValuesTask<K,V>
extends BulkTask<K,V,V> {
final BiFunction<? super V, ? super V, ? extends V> reducer;
V result;
ReduceValuesTask<K,V> rights, nextRight;
ReduceValuesTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
ReduceValuesTask<K,V> nextRight,
BiFunction<? super V, ? super V, ? extends V> reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.reducer = reducer;
}
public final V getRawResult() { return result; }
public final void compute() {
final BiFunction<? super V, ? super V, ? extends V> reducer;
if ((reducer = this.reducer) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new ReduceValuesTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, reducer)).fork();
}
V r = null;
for (Node<K,V> p; (p = advance()) != null; ) {
V v = p.val;
r = (r == null) ? v : reducer.apply(r, v);
}
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
ReduceValuesTask<K,V>
t = (ReduceValuesTask<K,V>)c,
s = t.rights;
while (s != null) {
V tr, sr;
if ((sr = s.result) != null)
t.result = (((tr = t.result) == null) ? sr :
reducer.apply(tr, sr));
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class ReduceEntriesTask<K,V>
extends BulkTask<K,V,Map.Entry<K,V>> {
final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
Map.Entry<K,V> result;
ReduceEntriesTask<K,V> rights, nextRight;
ReduceEntriesTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
ReduceEntriesTask<K,V> nextRight,
BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.reducer = reducer;
}
public final Map.Entry<K,V> getRawResult() { return result; }
public final void compute() {
final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
if ((reducer = this.reducer) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new ReduceEntriesTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, reducer)).fork();
}
Map.Entry<K,V> r = null;
for (Node<K,V> p; (p = advance()) != null; )
r = (r == null) ? p : reducer.apply(r, p);
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
ReduceEntriesTask<K,V>
t = (ReduceEntriesTask<K,V>)c,
s = t.rights;
while (s != null) {
Map.Entry<K,V> tr, sr;
if ((sr = s.result) != null)
t.result = (((tr = t.result) == null) ? sr :
reducer.apply(tr, sr));
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceKeysTask<K,V,U>
extends BulkTask<K,V,U> {
final Function<? super K, ? extends U> transformer;
final BiFunction<? super U, ? super U, ? extends U> reducer;
U result;
MapReduceKeysTask<K,V,U> rights, nextRight;
MapReduceKeysTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceKeysTask<K,V,U> nextRight,
Function<? super K, ? extends U> transformer,
BiFunction<? super U, ? super U, ? extends U> reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.reducer = reducer;
}
public final U getRawResult() { return result; }
public final void compute() {
final Function<? super K, ? extends U> transformer;
final BiFunction<? super U, ? super U, ? extends U> reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceKeysTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, reducer)).fork();
}
U r = null;
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p.key)) != null)
r = (r == null) ? u : reducer.apply(r, u);
}
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceKeysTask<K,V,U>
t = (MapReduceKeysTask<K,V,U>)c,
s = t.rights;
while (s != null) {
U tr, sr;
if ((sr = s.result) != null)
t.result = (((tr = t.result) == null) ? sr :
reducer.apply(tr, sr));
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceValuesTask<K,V,U>
extends BulkTask<K,V,U> {
final Function<? super V, ? extends U> transformer;
final BiFunction<? super U, ? super U, ? extends U> reducer;
U result;
MapReduceValuesTask<K,V,U> rights, nextRight;
MapReduceValuesTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceValuesTask<K,V,U> nextRight,
Function<? super V, ? extends U> transformer,
BiFunction<? super U, ? super U, ? extends U> reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.reducer = reducer;
}
public final U getRawResult() { return result; }
public final void compute() {
final Function<? super V, ? extends U> transformer;
final BiFunction<? super U, ? super U, ? extends U> reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceValuesTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, reducer)).fork();
}
U r = null;
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p.val)) != null)
r = (r == null) ? u : reducer.apply(r, u);
}
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceValuesTask<K,V,U>
t = (MapReduceValuesTask<K,V,U>)c,
s = t.rights;
while (s != null) {
U tr, sr;
if ((sr = s.result) != null)
t.result = (((tr = t.result) == null) ? sr :
reducer.apply(tr, sr));
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceEntriesTask<K,V,U>
extends BulkTask<K,V,U> {
final Function<Map.Entry<K,V>, ? extends U> transformer;
final BiFunction<? super U, ? super U, ? extends U> reducer;
U result;
MapReduceEntriesTask<K,V,U> rights, nextRight;
MapReduceEntriesTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceEntriesTask<K,V,U> nextRight,
Function<Map.Entry<K,V>, ? extends U> transformer,
BiFunction<? super U, ? super U, ? extends U> reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.reducer = reducer;
}
public final U getRawResult() { return result; }
public final void compute() {
final Function<Map.Entry<K,V>, ? extends U> transformer;
final BiFunction<? super U, ? super U, ? extends U> reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceEntriesTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, reducer)).fork();
}
U r = null;
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p)) != null)
r = (r == null) ? u : reducer.apply(r, u);
}
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceEntriesTask<K,V,U>
t = (MapReduceEntriesTask<K,V,U>)c,
s = t.rights;
while (s != null) {
U tr, sr;
if ((sr = s.result) != null)
t.result = (((tr = t.result) == null) ? sr :
reducer.apply(tr, sr));
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceMappingsTask<K,V,U>
extends BulkTask<K,V,U> {
final BiFunction<? super K, ? super V, ? extends U> transformer;
final BiFunction<? super U, ? super U, ? extends U> reducer;
U result;
MapReduceMappingsTask<K,V,U> rights, nextRight;
MapReduceMappingsTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceMappingsTask<K,V,U> nextRight,
BiFunction<? super K, ? super V, ? extends U> transformer,
BiFunction<? super U, ? super U, ? extends U> reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.reducer = reducer;
}
public final U getRawResult() { return result; }
public final void compute() {
final BiFunction<? super K, ? super V, ? extends U> transformer;
final BiFunction<? super U, ? super U, ? extends U> reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceMappingsTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, reducer)).fork();
}
U r = null;
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p.key, p.val)) != null)
r = (r == null) ? u : reducer.apply(r, u);
}
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceMappingsTask<K,V,U>
t = (MapReduceMappingsTask<K,V,U>)c,
s = t.rights;
while (s != null) {
U tr, sr;
if ((sr = s.result) != null)
t.result = (((tr = t.result) == null) ? sr :
reducer.apply(tr, sr));
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceKeysToDoubleTask<K,V>
extends BulkTask<K,V,Double> {
final ToDoubleFunction<? super K> transformer;
final DoubleBinaryOperator reducer;
final double basis;
double result;
MapReduceKeysToDoubleTask<K,V> rights, nextRight;
MapReduceKeysToDoubleTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceKeysToDoubleTask<K,V> nextRight,
ToDoubleFunction<? super K> transformer,
double basis,
DoubleBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Double getRawResult() { return result; }
public final void compute() {
final ToDoubleFunction<? super K> transformer;
final DoubleBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
double r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceKeysToDoubleTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceKeysToDoubleTask<K,V>
t = (MapReduceKeysToDoubleTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsDouble(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceValuesToDoubleTask<K,V>
extends BulkTask<K,V,Double> {
final ToDoubleFunction<? super V> transformer;
final DoubleBinaryOperator reducer;
final double basis;
double result;
MapReduceValuesToDoubleTask<K,V> rights, nextRight;
MapReduceValuesToDoubleTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceValuesToDoubleTask<K,V> nextRight,
ToDoubleFunction<? super V> transformer,
double basis,
DoubleBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Double getRawResult() { return result; }
public final void compute() {
final ToDoubleFunction<? super V> transformer;
final DoubleBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
double r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceValuesToDoubleTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceValuesToDoubleTask<K,V>
t = (MapReduceValuesToDoubleTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsDouble(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceEntriesToDoubleTask<K,V>
extends BulkTask<K,V,Double> {
final ToDoubleFunction<Map.Entry<K,V>> transformer;
final DoubleBinaryOperator reducer;
final double basis;
double result;
MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
MapReduceEntriesToDoubleTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceEntriesToDoubleTask<K,V> nextRight,
ToDoubleFunction<Map.Entry<K,V>> transformer,
double basis,
DoubleBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Double getRawResult() { return result; }
public final void compute() {
final ToDoubleFunction<Map.Entry<K,V>> transformer;
final DoubleBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
double r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceEntriesToDoubleTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceEntriesToDoubleTask<K,V>
t = (MapReduceEntriesToDoubleTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsDouble(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceMappingsToDoubleTask<K,V>
extends BulkTask<K,V,Double> {
final ToDoubleBiFunction<? super K, ? super V> transformer;
final DoubleBinaryOperator reducer;
final double basis;
double result;
MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
MapReduceMappingsToDoubleTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceMappingsToDoubleTask<K,V> nextRight,
ToDoubleBiFunction<? super K, ? super V> transformer,
double basis,
DoubleBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Double getRawResult() { return result; }
public final void compute() {
final ToDoubleBiFunction<? super K, ? super V> transformer;
final DoubleBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
double r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceMappingsToDoubleTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceMappingsToDoubleTask<K,V>
t = (MapReduceMappingsToDoubleTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsDouble(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceKeysToLongTask<K,V>
extends BulkTask<K,V,Long> {
final ToLongFunction<? super K> transformer;
final LongBinaryOperator reducer;
final long basis;
long result;
MapReduceKeysToLongTask<K,V> rights, nextRight;
MapReduceKeysToLongTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceKeysToLongTask<K,V> nextRight,
ToLongFunction<? super K> transformer,
long basis,
LongBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Long getRawResult() { return result; }
public final void compute() {
final ToLongFunction<? super K> transformer;
final LongBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
long r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceKeysToLongTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceKeysToLongTask<K,V>
t = (MapReduceKeysToLongTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsLong(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceValuesToLongTask<K,V>
extends BulkTask<K,V,Long> {
final ToLongFunction<? super V> transformer;
final LongBinaryOperator reducer;
final long basis;
long result;
MapReduceValuesToLongTask<K,V> rights, nextRight;
MapReduceValuesToLongTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceValuesToLongTask<K,V> nextRight,
ToLongFunction<? super V> transformer,
long basis,
LongBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Long getRawResult() { return result; }
public final void compute() {
final ToLongFunction<? super V> transformer;
final LongBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
long r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceValuesToLongTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceValuesToLongTask<K,V>
t = (MapReduceValuesToLongTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsLong(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceEntriesToLongTask<K,V>
extends BulkTask<K,V,Long> {
final ToLongFunction<Map.Entry<K,V>> transformer;
final LongBinaryOperator reducer;
final long basis;
long result;
MapReduceEntriesToLongTask<K,V> rights, nextRight;
MapReduceEntriesToLongTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceEntriesToLongTask<K,V> nextRight,
ToLongFunction<Map.Entry<K,V>> transformer,
long basis,
LongBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Long getRawResult() { return result; }
public final void compute() {
final ToLongFunction<Map.Entry<K,V>> transformer;
final LongBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
long r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceEntriesToLongTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsLong(r, transformer.applyAsLong(p));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceEntriesToLongTask<K,V>
t = (MapReduceEntriesToLongTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsLong(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceMappingsToLongTask<K,V>
extends BulkTask<K,V,Long> {
final ToLongBiFunction<? super K, ? super V> transformer;
final LongBinaryOperator reducer;
final long basis;
long result;
MapReduceMappingsToLongTask<K,V> rights, nextRight;
MapReduceMappingsToLongTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceMappingsToLongTask<K,V> nextRight,
ToLongBiFunction<? super K, ? super V> transformer,
long basis,
LongBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Long getRawResult() { return result; }
public final void compute() {
final ToLongBiFunction<? super K, ? super V> transformer;
final LongBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
long r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceMappingsToLongTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceMappingsToLongTask<K,V>
t = (MapReduceMappingsToLongTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsLong(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceKeysToIntTask<K,V>
extends BulkTask<K,V,Integer> {
final ToIntFunction<? super K> transformer;
final IntBinaryOperator reducer;
final int basis;
int result;
MapReduceKeysToIntTask<K,V> rights, nextRight;
MapReduceKeysToIntTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceKeysToIntTask<K,V> nextRight,
ToIntFunction<? super K> transformer,
int basis,
IntBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Integer getRawResult() { return result; }
public final void compute() {
final ToIntFunction<? super K> transformer;
final IntBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
int r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceKeysToIntTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceKeysToIntTask<K,V>
t = (MapReduceKeysToIntTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsInt(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceValuesToIntTask<K,V>
extends BulkTask<K,V,Integer> {
final ToIntFunction<? super V> transformer;
final IntBinaryOperator reducer;
final int basis;
int result;
MapReduceValuesToIntTask<K,V> rights, nextRight;
MapReduceValuesToIntTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceValuesToIntTask<K,V> nextRight,
ToIntFunction<? super V> transformer,
int basis,
IntBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Integer getRawResult() { return result; }
public final void compute() {
final ToIntFunction<? super V> transformer;
final IntBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
int r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceValuesToIntTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceValuesToIntTask<K,V>
t = (MapReduceValuesToIntTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsInt(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceEntriesToIntTask<K,V>
extends BulkTask<K,V,Integer> {
final ToIntFunction<Map.Entry<K,V>> transformer;
final IntBinaryOperator reducer;
final int basis;
int result;
MapReduceEntriesToIntTask<K,V> rights, nextRight;
MapReduceEntriesToIntTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceEntriesToIntTask<K,V> nextRight,
ToIntFunction<Map.Entry<K,V>> transformer,
int basis,
IntBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Integer getRawResult() { return result; }
public final void compute() {
final ToIntFunction<Map.Entry<K,V>> transformer;
final IntBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
int r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceEntriesToIntTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsInt(r, transformer.applyAsInt(p));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceEntriesToIntTask<K,V>
t = (MapReduceEntriesToIntTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsInt(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
@SuppressWarnings("serial")
static final class MapReduceMappingsToIntTask<K,V>
extends BulkTask<K,V,Integer> {
final ToIntBiFunction<? super K, ? super V> transformer;
final IntBinaryOperator reducer;
final int basis;
int result;
MapReduceMappingsToIntTask<K,V> rights, nextRight;
MapReduceMappingsToIntTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceMappingsToIntTask<K,V> nextRight,
ToIntBiFunction<? super K, ? super V> transformer,
int basis,
IntBinaryOperator reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Integer getRawResult() { return result; }
public final void compute() {
final ToIntBiFunction<? super K, ? super V> transformer;
final IntBinaryOperator reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
int r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceMappingsToIntTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked")
MapReduceMappingsToIntTask<K,V>
t = (MapReduceMappingsToIntTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.applyAsInt(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
}
// Unsafe mechanics
private static final sun.misc.Unsafe U;
private static final long SIZECTL;
private static final long TRANSFERINDEX;
private static final long BASECOUNT;
private static final long CELLSBUSY;
private static final long CELLVALUE;
private static final long ABASE;
private static final int ASHIFT;
static {
try {
U = sun.misc.Unsafe.getUnsafe();
Class<?> k = ConcurrentHashMap.class;
SIZECTL = U.objectFieldOffset
(k.getDeclaredField("sizeCtl"));
TRANSFERINDEX = U.objectFieldOffset
(k.getDeclaredField("transferIndex"));
BASECOUNT = U.objectFieldOffset
(k.getDeclaredField("baseCount"));
CELLSBUSY = U.objectFieldOffset
(k.getDeclaredField("cellsBusy"));
Class<?> ck = CounterCell.class;
CELLVALUE = U.objectFieldOffset
(ck.getDeclaredField("value"));
Class<?> ak = Node[].class;
ABASE = U.arrayBaseOffset(ak);
int scale = U.arrayIndexScale(ak);
if ((scale & (scale - 1)) != 0)
throw new Error("data type scale not a power of two");
ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
} catch (Exception e) {
throw new Error(e);
}
}
}
| [
"[email protected]"
] | |
f6514d53910b4638ee6749aca68899beab3bee93 | c13e0c17fc8d69253f921f9fe0364afbf19a84b9 | /algorithms/src/main/java/DS/Trie.java | 5b58e264c8c0b863048f78762198c216f1f7ce9d | [] | no_license | aravindmchakkaravarthy/preparation | c7a4983d90458a83447468e3d6aa4be23ae1c378 | 789e90612fade4320b0eb1437960d4a189479fb0 | refs/heads/master | 2022-12-25T18:11:10.290988 | 2020-10-05T02:15:38 | 2020-10-05T02:15:38 | 278,520,347 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,399 | java | package DS;
import java.util.HashMap;
import java.util.Map;
/**
* Implement a trie with insert, search, and startsWith methods.
*
* Example:
*
* Trie trie = new Trie();
*
* trie.insert("apple");
* trie.search("apple"); // returns true
* trie.search("app"); // returns false
* trie.startsWith("app"); // returns true
* trie.insert("app");
* trie.search("app"); // returns true
* Note:
*
* You may assume that all inputs are consist of lowercase letters a-z.
* All inputs are guaranteed to be non-empty strings.
*/
public class Trie {
static class TrieNode{
HashMap<Character, TrieNode> children = new HashMap<>();
boolean isWord;
}
TrieNode root;
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode curr = root;
for(int i=0;i<word.length();i++){
Map<Character, TrieNode> children = curr.children;
char c = word.charAt(i);
if(!children.containsKey(c)){
TrieNode child = new TrieNode();
children.put(c, child);
}
curr = children.get(c);
}
curr.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode trie = getMatchingTrie(word);
return (trie != null) && trie.isWord;
}
public TrieNode getMatchingTrie(String word){
TrieNode curr = root;
for(char c: word.toCharArray()){
Map<Character, TrieNode> children = curr.children;
if(!children.containsKey(c)){
return null;
}else{
curr = children.get(c);
}
}
return curr;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return getMatchingTrie(prefix) != null;
}
public static void main(String[] args){
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple")); // returns true
System.out.println(trie.search("app")); // returns false
System.out.println(trie.startsWith("app")); // returns true
trie.insert("app");
System.out.println(trie.search("app")); // returns true
}
}
| [
"[email protected]"
] | |
54a82acf7d1158924a5cb0112ae3b302da1794ff | e7c9bd197af45f28e4c310c34102c8364c7901c8 | /chapter_002/src/main/java/ru/job4j/exeptions/FindEl.java | 6584a3eb8d3c78117bb32eb3ebb85eac7bf495f9 | [] | no_license | magidin91/job4j | 89d91a5a349771ef3ce9d6a2af872227e1761013 | 5defd1bb400461523b6d7ebd1301cf519ccfdd45 | refs/heads/master | 2022-09-18T19:14:26.873001 | 2021-09-11T13:04:48 | 2021-09-11T13:04:48 | 229,655,266 | 0 | 1 | null | 2022-09-08T01:07:07 | 2019-12-23T01:32:20 | Java | UTF-8 | Java | false | false | 701 | java | package ru.job4j.exeptions;
public class FindEl {
public static int indexOf(String[] value, String key) throws ElementNotFoundException {
int rsl = -1;
for (int i = 0; i < value.length; i++) {
if (value[i].equals(key)) {
rsl = i;
break;
}
}
if (rsl == -1) {
throw new ElementNotFoundException("Элемента нет");
}
return rsl;
}
public static void main(String[] args) {
try {
System.out.println(FindEl.indexOf(new String[]{"a", "b", "c"}, "d"));
} catch (ElementNotFoundException e) {
e.printStackTrace();
}
}
} | [
"[email protected]"
] | |
5bf038786ad87bdbb3e0f7af5523a1697c47cbe1 | 27c9a7a203d74b92f9a7f6786fe7f0b6534e93be | /optaplanner-persistence/optaplanner-persistence-jackson/src/test/java/org/optaplanner/persistence/jackson/api/score/buildin/hardmediumsoftlong/HardMediumSoftLongScoreJacksonJsonSerializerAndDeserializerTest.java | 87fe8d2e92a796d917d2c54e98191d7e70131e6b | [
"Apache-2.0"
] | permissive | jaymay09/optaplanner | b2ee7793c4767e1be7282063b838804b028e1022 | 2d6eefba61b2991f0b1fa1fe5207ea883ed6d106 | refs/heads/master | 2021-09-10T01:37:38.369867 | 2018-03-20T15:15:54 | 2018-03-20T15:16:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,463 | java | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.optaplanner.persistence.jackson.api.score.buildin.hardmediumsoftlong;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.junit.Test;
import org.optaplanner.core.api.score.buildin.hardmediumsoftlong.HardMediumSoftLongScore;
import org.optaplanner.persistence.jackson.api.score.AbstractScoreJacksonJsonSerializerAndDeserializerTest;
import org.optaplanner.persistence.jackson.api.score.ScoreJacksonJsonSerializer;
public class HardMediumSoftLongScoreJacksonJsonSerializerAndDeserializerTest extends AbstractScoreJacksonJsonSerializerAndDeserializerTest {
@Test
public void serializeAndDeserialize() {
assertSerializeAndDeserialize(null, new TestHardMediumSoftLongScoreWrapper(null));
HardMediumSoftLongScore score = HardMediumSoftLongScore.valueOf(1200L, 30L, 4L);
assertSerializeAndDeserialize(score, new TestHardMediumSoftLongScoreWrapper(score));
score = HardMediumSoftLongScore.valueOfUninitialized(-7, 1200L, 30L, 4L);
assertSerializeAndDeserialize(score, new TestHardMediumSoftLongScoreWrapper(score));
}
public static class TestHardMediumSoftLongScoreWrapper extends TestScoreWrapper<HardMediumSoftLongScore> {
@JsonSerialize(using = HardMediumSoftLongScoreJacksonJsonSerializer.class)
@JsonDeserialize(using = HardMediumSoftLongScoreJacksonJsonDeserializer.class)
private HardMediumSoftLongScore score;
@SuppressWarnings("unused")
private TestHardMediumSoftLongScoreWrapper() {
}
public TestHardMediumSoftLongScoreWrapper(HardMediumSoftLongScore score) {
this.score = score;
}
@Override
public HardMediumSoftLongScore getScore() {
return score;
}
}
}
| [
"[email protected]"
] | |
657facd07546b7188a4ecf4d92e3b5ea798b6a0c | ac1cd95653f54abbc41a3373bc08cccca887ea6e | /1.16.4-vortex/minecraft/src/main/java/net/minecraft/block/StairsBlock.java | 515bfe65028d7e888832fc85726e311d79edd89f | [] | no_license | DragonflyClient/dragonfly-injection-client | 1e3dccfefd0e9332cfeb6138224fff48d2d2d6a1 | 701fb3604972dc716a0197a4cf9d3e6bfbc09b94 | refs/heads/main | 2023-03-13T01:09:20.813860 | 2021-01-11T21:37:12 | 2021-01-11T21:37:12 | 320,880,114 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,567 | java | package net.minecraft.block;
import java.util.Random;
import java.util.stream.IntStream;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.FluidState;
import net.minecraft.fluid.Fluids;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.pathfinding.PathType;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.DirectionProperty;
import net.minecraft.state.EnumProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.state.properties.Half;
import net.minecraft.state.properties.StairsShape;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.Mirror;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public class StairsBlock extends Block implements IWaterLoggable {
public static final DirectionProperty FACING = HorizontalBlock.HORIZONTAL_FACING;
public static final EnumProperty<Half> HALF = BlockStateProperties.HALF;
public static final EnumProperty<StairsShape> SHAPE = BlockStateProperties.STAIRS_SHAPE;
public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;
protected static final VoxelShape AABB_SLAB_TOP = SlabBlock.TOP_SHAPE;
protected static final VoxelShape AABB_SLAB_BOTTOM = SlabBlock.BOTTOM_SHAPE;
protected static final VoxelShape NWD_CORNER = Block.makeCuboidShape(0.0D, 0.0D, 0.0D, 8.0D, 8.0D, 8.0D);
protected static final VoxelShape SWD_CORNER = Block.makeCuboidShape(0.0D, 0.0D, 8.0D, 8.0D, 8.0D, 16.0D);
protected static final VoxelShape NWU_CORNER = Block.makeCuboidShape(0.0D, 8.0D, 0.0D, 8.0D, 16.0D, 8.0D);
protected static final VoxelShape SWU_CORNER = Block.makeCuboidShape(0.0D, 8.0D, 8.0D, 8.0D, 16.0D, 16.0D);
protected static final VoxelShape NED_CORNER = Block.makeCuboidShape(8.0D, 0.0D, 0.0D, 16.0D, 8.0D, 8.0D);
protected static final VoxelShape SED_CORNER = Block.makeCuboidShape(8.0D, 0.0D, 8.0D, 16.0D, 8.0D, 16.0D);
protected static final VoxelShape NEU_CORNER = Block.makeCuboidShape(8.0D, 8.0D, 0.0D, 16.0D, 16.0D, 8.0D);
protected static final VoxelShape SEU_CORNER = Block.makeCuboidShape(8.0D, 8.0D, 8.0D, 16.0D, 16.0D, 16.0D);
protected static final VoxelShape[] SLAB_TOP_SHAPES = makeShapes(AABB_SLAB_TOP, NWD_CORNER, NED_CORNER, SWD_CORNER, SED_CORNER);
protected static final VoxelShape[] SLAB_BOTTOM_SHAPES = makeShapes(AABB_SLAB_BOTTOM, NWU_CORNER, NEU_CORNER, SWU_CORNER, SEU_CORNER);
private static final int[] PALETTE_SHAPE_MAP = new int[]{12, 5, 3, 10, 14, 13, 7, 11, 13, 7, 11, 14, 8, 4, 1, 2, 4, 1, 2, 8};
private final Block modelBlock;
private final BlockState modelState;
private static VoxelShape[] makeShapes(VoxelShape slabShape, VoxelShape nwCorner, VoxelShape neCorner, VoxelShape swCorner, VoxelShape seCorner) {
return IntStream.range(0, 16).mapToObj((p_199780_5_) -> {
return combineShapes(p_199780_5_, slabShape, nwCorner, neCorner, swCorner, seCorner);
}).toArray((p_199778_0_) -> {
return new VoxelShape[p_199778_0_];
});
}
private static VoxelShape combineShapes(int bitfield, VoxelShape slabShape, VoxelShape nwCorner, VoxelShape neCorner, VoxelShape swCorner, VoxelShape seCorner) {
VoxelShape voxelshape = slabShape;
if ((bitfield & 1) != 0) {
voxelshape = VoxelShapes.or(slabShape, nwCorner);
}
if ((bitfield & 2) != 0) {
voxelshape = VoxelShapes.or(voxelshape, neCorner);
}
if ((bitfield & 4) != 0) {
voxelshape = VoxelShapes.or(voxelshape, swCorner);
}
if ((bitfield & 8) != 0) {
voxelshape = VoxelShapes.or(voxelshape, seCorner);
}
return voxelshape;
}
protected StairsBlock(BlockState state, AbstractBlock.Properties properties) {
super(properties);
this.setDefaultState(this.stateContainer.getBaseState().with(FACING, Direction.NORTH).with(HALF, Half.BOTTOM).with(SHAPE, StairsShape.STRAIGHT).with(WATERLOGGED, Boolean.valueOf(false)));
this.modelBlock = state.getBlock();
this.modelState = state;
}
public boolean isTransparent(BlockState state) {
return true;
}
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) {
return (state.get(HALF) == Half.TOP ? SLAB_TOP_SHAPES : SLAB_BOTTOM_SHAPES)[PALETTE_SHAPE_MAP[this.getPaletteId(state)]];
}
private int getPaletteId(BlockState state) {
return state.get(SHAPE).ordinal() * 4 + state.get(FACING).getHorizontalIndex();
}
@OnlyIn(Dist.CLIENT)
public void animateTick(BlockState stateIn, World worldIn, BlockPos pos, Random rand) {
this.modelBlock.animateTick(stateIn, worldIn, pos, rand);
}
public void onBlockClicked(BlockState state, World worldIn, BlockPos pos, PlayerEntity player) {
this.modelState.onBlockClicked(worldIn, pos, player);
}
public void onPlayerDestroy(IWorld worldIn, BlockPos pos, BlockState state) {
this.modelBlock.onPlayerDestroy(worldIn, pos, state);
}
public float getExplosionResistance() {
return this.modelBlock.getExplosionResistance();
}
public void onBlockAdded(BlockState state, World worldIn, BlockPos pos, BlockState oldState, boolean isMoving) {
if (!state.isIn(state.getBlock())) {
this.modelState.neighborChanged(worldIn, pos, Blocks.AIR, pos, false);
this.modelBlock.onBlockAdded(this.modelState, worldIn, pos, oldState, false);
}
}
public void onReplaced(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving) {
if (!state.isIn(newState.getBlock())) {
this.modelState.onReplaced(worldIn, pos, newState, isMoving);
}
}
public void onEntityWalk(World worldIn, BlockPos pos, Entity entityIn) {
this.modelBlock.onEntityWalk(worldIn, pos, entityIn);
}
public boolean ticksRandomly(BlockState state) {
return this.modelBlock.ticksRandomly(state);
}
public void randomTick(BlockState state, ServerWorld worldIn, BlockPos pos, Random random) {
this.modelBlock.randomTick(state, worldIn, pos, random);
}
public void tick(BlockState state, ServerWorld worldIn, BlockPos pos, Random rand) {
this.modelBlock.tick(state, worldIn, pos, rand);
}
public ActionResultType onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {
return this.modelState.onBlockActivated(worldIn, player, handIn, hit);
}
public void onExplosionDestroy(World worldIn, BlockPos pos, Explosion explosionIn) {
this.modelBlock.onExplosionDestroy(worldIn, pos, explosionIn);
}
public BlockState getStateForPlacement(BlockItemUseContext context) {
Direction direction = context.getFace();
BlockPos blockpos = context.getPos();
FluidState fluidstate = context.getWorld().getFluidState(blockpos);
BlockState blockstate = this.getDefaultState().with(FACING, context.getPlacementHorizontalFacing()).with(HALF, direction != Direction.DOWN && (direction == Direction.UP || !(context.getHitVec().y - (double)blockpos.getY() > 0.5D)) ? Half.BOTTOM : Half.TOP).with(WATERLOGGED, Boolean.valueOf(fluidstate.getFluid() == Fluids.WATER));
return blockstate.with(SHAPE, getShapeProperty(blockstate, context.getWorld(), blockpos));
}
public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos) {
if (stateIn.get(WATERLOGGED)) {
worldIn.getPendingFluidTicks().scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickRate(worldIn));
}
return facing.getAxis().isHorizontal() ? stateIn.with(SHAPE, getShapeProperty(stateIn, worldIn, currentPos)) : super.updatePostPlacement(stateIn, facing, facingState, worldIn, currentPos, facingPos);
}
private static StairsShape getShapeProperty(BlockState state, IBlockReader worldIn, BlockPos pos) {
Direction direction = state.get(FACING);
BlockState blockstate = worldIn.getBlockState(pos.offset(direction));
if (isBlockStairs(blockstate) && state.get(HALF) == blockstate.get(HALF)) {
Direction direction1 = blockstate.get(FACING);
if (direction1.getAxis() != state.get(FACING).getAxis() && isDifferentStairs(state, worldIn, pos, direction1.getOpposite())) {
if (direction1 == direction.rotateYCCW()) {
return StairsShape.OUTER_LEFT;
}
return StairsShape.OUTER_RIGHT;
}
}
BlockState blockstate1 = worldIn.getBlockState(pos.offset(direction.getOpposite()));
if (isBlockStairs(blockstate1) && state.get(HALF) == blockstate1.get(HALF)) {
Direction direction2 = blockstate1.get(FACING);
if (direction2.getAxis() != state.get(FACING).getAxis() && isDifferentStairs(state, worldIn, pos, direction2)) {
if (direction2 == direction.rotateYCCW()) {
return StairsShape.INNER_LEFT;
}
return StairsShape.INNER_RIGHT;
}
}
return StairsShape.STRAIGHT;
}
private static boolean isDifferentStairs(BlockState state, IBlockReader worldIn, BlockPos pos, Direction face) {
BlockState blockstate = worldIn.getBlockState(pos.offset(face));
return !isBlockStairs(blockstate) || blockstate.get(FACING) != state.get(FACING) || blockstate.get(HALF) != state.get(HALF);
}
public static boolean isBlockStairs(BlockState state) {
return state.getBlock() instanceof StairsBlock;
}
public BlockState rotate(BlockState state, Rotation rot) {
return state.with(FACING, rot.rotate(state.get(FACING)));
}
public BlockState mirror(BlockState state, Mirror mirrorIn) {
Direction direction = state.get(FACING);
StairsShape stairsshape = state.get(SHAPE);
switch(mirrorIn) {
case LEFT_RIGHT:
if (direction.getAxis() == Direction.Axis.Z) {
switch(stairsshape) {
case INNER_LEFT:
return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.INNER_RIGHT);
case INNER_RIGHT:
return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.INNER_LEFT);
case OUTER_LEFT:
return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.OUTER_RIGHT);
case OUTER_RIGHT:
return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.OUTER_LEFT);
default:
return state.rotate(Rotation.CLOCKWISE_180);
}
}
break;
case FRONT_BACK:
if (direction.getAxis() == Direction.Axis.X) {
switch(stairsshape) {
case INNER_LEFT:
return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.INNER_LEFT);
case INNER_RIGHT:
return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.INNER_RIGHT);
case OUTER_LEFT:
return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.OUTER_RIGHT);
case OUTER_RIGHT:
return state.rotate(Rotation.CLOCKWISE_180).with(SHAPE, StairsShape.OUTER_LEFT);
case STRAIGHT:
return state.rotate(Rotation.CLOCKWISE_180);
}
}
}
return super.mirror(state, mirrorIn);
}
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
builder.add(FACING, HALF, SHAPE, WATERLOGGED);
}
public FluidState getFluidState(BlockState state) {
return state.get(WATERLOGGED) ? Fluids.WATER.getStillFluidState(false) : super.getFluidState(state);
}
public boolean allowsMovement(BlockState state, IBlockReader worldIn, BlockPos pos, PathType type) {
return false;
}
}
| [
"[email protected]"
] | |
8e474d8631c65c210792674926c5a68bf38259fe | ca17d7e045d11a13509cc18be4a44bb136ef2a4a | /ProtocolTesterFramework/app/src/main/java/claudiu/protocoltesterframework/ParallelTest.java | ddce3f03135539f35226a26dda9aeeb393623ba1 | [
"MIT"
] | permissive | bogdanghita/remoty-client-android | ff7ea32c8e15831998468766212aaa6696d856f1 | 27a2e5697da3fa5c4c6c0407a94a234a6c377072 | refs/heads/master | 2020-08-07T06:28:48.064769 | 2019-10-28T09:50:40 | 2019-10-28T09:50:40 | 213,332,561 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,052 | java | package claudiu.protocoltesterframework;
import android.util.Log;
import java.io.IOException;
import java.net.SocketException;
/**
* Created by Claudiu on 13/Aug/2015.
*/
public class ParallelTest extends AbstractTest {
private final int parallels = 5;
@Override
protected void changeParams() throws SocketException {
mRepeats = 10;
//mTcpSocket.setKeepAlive(false);
mTcpSocket.setKeepAlive(true);
//mTcpSocket.setTcpNoDelay(false);
mTcpSocket.setTcpNoDelay(true);
mTcpSocket.setTimeout(10000);
}
@Override
public void test() throws IOException {
byte[] message = new byte[0];
for (int i = 0; i < parallels; i++)
message = mTcpSocket.receive();
Log.d(MainActivity.FRAMEWORK, "Message sent.");
for (int i = 0; i < parallels; i++)
mTcpSocket.send(message);
Log.d(MainActivity.FRAMEWORK, "Message received.");
}
@Override
public void getResults() {
}
}
| [
"claudiu_mihai_toma@localhost"
] | claudiu_mihai_toma@localhost |
07f0acf21c843692d3dee1e20af883cdd2a50bdd | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/23/23_d6ad653fd21e253e187fc58f0a2ea96949051373/UDPInput/23_d6ad653fd21e253e187fc58f0a2ea96949051373_UDPInput_t.java | bd8fb090d992b74e87a74b15494c69aef09cae65 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 3,507 | java | package com.eyetribe;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import android.util.Log;
public class UDPInput{
private ReceiveMessage receiveMessage = new ReceiveMessage();
private Thread thread = new Thread(receiveMessage);
private DatagramSocket socketToServer;
private byte byteArray[] = new byte[50];
private String gazeString = "";
private List<Listener> listeners = new ArrayList<Listener>();
private int port = 8866;
private boolean flag = true;
private String x;
private String y;
private String[] gazeData;
public static final String LOG_TAG = "EyeTribeBrowser";
public UDPInput(){
thread.start();
}
public void read() {
receiveMessage.read();
}
public void pauseReading(){
receiveMessage.pauseReading();
}
public void close() {
receiveMessage.stop();
}
public interface Listener {
void handleGazeDataSet(UDPInput sender);
}
public String getGazeString(){
return gazeString;
}
public String getX(){
return x;
}
public String getY(){
return y;
}
public void sendSignal(){
for (Listener listener : listeners) {
listener.handleGazeDataSet(this);
}
}
public class ReceiveMessage implements Runnable{
private volatile boolean running = true;
private volatile boolean reading = false;
private Semaphore readToken = new Semaphore(0);
public void run() {
while(running){
try {
readToken.acquire();
doRead();
readToken.release();
}
catch(InterruptedException e) {
// Do nothing.
}
}
}
public void read() {
if(!reading) {
try {
if(socketToServer == null) {
Log.i(LOG_TAG, "Creating datagram socket.");
socketToServer = new DatagramSocket(port);
}
readToken.release();
}
catch(SocketException e) {
e.printStackTrace();
}
reading = true;
}
}
public void pauseReading() {
if(reading) {
try {
readToken.acquire();
}
catch(InterruptedException e) {
// Do nothing.
}
if(socketToServer != null) {
Log.i(LOG_TAG, "Closing datagram socket.");
socketToServer.close();
socketToServer = null;
}
reading = false;
}
}
public void stop(){
this.running = false;
}
private void doRead() {
try{
DatagramPacket receivePacket = new DatagramPacket(byteArray, byteArray.length);
socketToServer.receive(receivePacket);
gazeString = new String(receivePacket.getData());
gazeData = gazeString.split(" ");
x = gazeData[2].replace(",", ".");
y = gazeData[3].replace(",", ".");
sendSignal();
}
catch(IOException e){
e.printStackTrace();
}
}
}
public void addListener(Listener listener) {
this.listeners.add(listener);
}
public void removeListener(Listener listener) {
this.listeners.remove(listener);
}
}
| [
"[email protected]"
] | |
2b3b98b7ece2c72bad483484a2b618a0a12736a7 | 802a56ccac74a57d0ca1a2bfd1c7ec19becbeaa3 | /app/src/test/java/com/example/wuqi/weathertest/ExampleUnitTest.java | 308c4625cc95d5ec936d2b30af2f7b2c7e614424 | [] | no_license | BlackJackToken/weathertest | 4ebf87b66587b81eba4f62244929d2b2b732ca5d | a5da535b4a8dc7b82b35592185cafc843436776c | refs/heads/master | 2021-09-02T12:06:38.114762 | 2018-01-02T13:05:31 | 2018-01-02T13:05:31 | 115,299,953 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 406 | java | package com.example.wuqi.weathertest;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
4c5be0afaea9675605c4a9a69e49485ab6efd5c4 | b0c76af37c698088d10184da15c0ce2b719cbb87 | /client/src/main/java/com/github/atcw/client/gui/SuperController.java | 58343cc5fb5c524f193b33bba0830603a638c2ed | [] | no_license | atcw/buchstabenmagie | cc0600ad6c45768844f1a760cb0cdb2fad5a6dfb | 1edca6c2ce6b5e50d6e791b4ba064cb37bcbc84a | refs/heads/master | 2020-03-22T21:58:25.511435 | 2018-07-12T16:34:46 | 2018-07-12T16:34:46 | 140,725,365 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,354 | java | package com.github.atcw.client.gui;
import com.github.atcw.client.gui.login.LoginPresenter;
import com.github.atcw.client.gui.login.LoginPresenterImpl;
import com.github.atcw.client.gui.login.LoginView;
import com.github.atcw.client.gui.login.LoginViewImpl;
import com.github.atcw.client.gui.main.MainMenuPresenter;
import com.github.atcw.client.gui.main.MainMenuPresenterImpl;
import com.github.atcw.client.gui.main.MainMenuView;
import com.github.atcw.client.gui.main.MainMenuViewImpl;
import com.github.atcw.client.gui.network.Network;
public class SuperController {
private final Network network;
private Presenter presenter;
public SuperController(Network network) {
this.network = network;
}
private void disconnect() {
if(presenter != null) {
network.disconnectFromOutput(presenter);
presenter = null;
}
}
public void openLogin() {
disconnect();
LoginPresenter presenter = new LoginPresenterImpl(network, this);
network.connectToOutput(presenter);
LoginView loginView = new LoginViewImpl();
presenter.init(loginView);
this.presenter = presenter;
}
public void openMainMenu() {
disconnect();
MainMenuPresenter presenter = new MainMenuPresenterImpl();
network.connectToOutput(presenter);
MainMenuView loginView = new MainMenuViewImpl();
presenter.init(loginView);
this.presenter = presenter;
}
}
| [
"[email protected]"
] | |
780404f749d9a0d91841847d86bb233cb682c0cc | e80f4262560208e61ac599ffbaeec56792e2c5e6 | /src/main/java/com/philips/pms/objects/Alarms.java | 84ae4d41ee3cf3a07e8e3958221eb30148aadec7 | [] | no_license | prakritiwadhwa7/PatientMonitoringSystem | 86bf1ee0b6d85b87b6546e543380d49cb556015b | 9877dc33942c0120fb9da51cb5112881fc758bc8 | refs/heads/master | 2020-08-01T08:51:00.736909 | 2019-09-25T20:56:34 | 2019-09-25T20:56:34 | 210,938,783 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 221 | java | package com.philips.pms.objects;
public class Alarms {
String doctor="Raman";
Boolean Light=false;
@Override
public String toString() {
return "alarms [doctor=" + doctor + ", Light=" + Light + "]";
}
}
| [
"[email protected]"
] | |
652d71a496345a8dba6959899342640cc01ed695 | 13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3 | /crash-reproduction-new-fitness/results/TIME-8b-1-25-Single_Objective_GGA-IntegrationSingleObjective-BasicBlockCoverage-opt/org/joda/time/DateTimeZone_ESTest.java | 8d57df1393d080f633acf84caba67a0f4f965881 | [
"MIT",
"CC-BY-4.0"
] | permissive | STAMP-project/Botsing-basic-block-coverage-application | 6c1095c6be945adc0be2b63bbec44f0014972793 | 80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da | refs/heads/master | 2022-07-28T23:05:55.253779 | 2022-04-20T13:54:11 | 2022-04-20T13:54:11 | 285,771,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 967 | java | /*
* This file was automatically generated by EvoSuite
* Sat Oct 30 11:08:45 UTC 2021
*/
package org.joda.time;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.joda.time.DateTimeZone;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true)
public class DateTimeZone_ESTest extends DateTimeZone_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
int int0 = 0;
int int1 = (-918);
try {
DateTimeZone.forOffsetHoursMinutes(0, (-918));
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Minutes out of range: -918
//
verifyException("org.joda.time.DateTimeZone", e);
}
}
}
| [
"[email protected]"
] | |
2fb4295ec11a8f98bc216c62902a4e23f6a2c2c5 | ecb87261886e57d45ea42b8d0e35f6080b59a7ea | /src/Lession2/Main.java | d52dc9fc22028d8e1c119c53a2787778a2c59445 | [] | no_license | korotaevilia/JavaFirstLession | 5a5743fdcc97c5b538e80cbc28ccdb82af593267 | d69f93256e28eaff614357405c0a8f8d1db40ea4 | refs/heads/master | 2020-06-25T08:31:49.598693 | 2019-08-27T17:09:16 | 2019-08-27T17:09:16 | 199,259,783 | 0 | 0 | null | 2019-08-27T23:30:07 | 2019-07-28T08:04:25 | Java | UTF-8 | Java | false | false | 5,778 | java | package Lession2;
import java.sql.Array;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
FirstExample(); //результаты
System.out.println();
SecondExample();
System.out.println();
ThirdExample();
System.out.println();
FourthExample();
System.out.println();
FifthExample();
System.out.println();
int[] sixthMass = {7, 2, 3, 1}; //для передачи в параметр 6го задания
System.out.println(SixthExample(sixthMass));
int seventhNum = 2; //пример с положительным числом
int[] seventhMass = {1, 2, 3, 4, 5, 6, 7};
SeventhExample(seventhNum, seventhMass);
int seventhNum2 = -1;
int[] seventhMass2 = {1, 2, 3, 4, 5, 6, 7}; //пример с отрицательным числом
SeventhExample(seventhNum2, seventhMass2);
EightExample();
}
//Первое задание
public static void FirstExample() {
int[] mass = {1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1};
for (int i : mass) {
if (mass[i] == 1) {
mass[i] = 0;
} else {
mass[i] = 1;
}
System.out.print(mass[i]);
}
}
//Второе задание
public static void SecondExample() {
int[] mass = new int[8];
for (int i = 0, ii = 0; (ii < 8); i += 3, ii = ii + 1) { // i отвечает за сам элемент , ii за порядковый номер в массиве
mass[ii] = i;
System.out.print(mass[ii] + " ");
}
}
//Третье задание
public static void ThirdExample() {
int[] mass = {1, 5, 3, 2, 11, 4, 5, 2, 4, 8, 9, 1};
for (int i = 0; (i < mass.length); i++) {
if (mass[i] < 6) {
mass[i] = mass[i] * 2;
}
}
System.out.print(Arrays.toString(mass));
}
//Четвертое задание
public static void FourthExample() {
int[][] mass = new int[4][4];
for (int i = 0; i < mass.length; i++) {
System.out.println();
for (int j = 0; j < mass[i].length; j++) {
if (i == j) { // сразу и заполняется массив и диагональный элемент = 1
mass[i][j] = 1;
} else {
mass[i][j] = 0;
}
System.out.print(mass[i][j]);
}
}
}
//Пятое задание
public static void FifthExample() {
int[] mass = {1, 2, 3, 4, 5, 6, -20, 8, 9, 150, 11, 12};
int max = mass[1]; //и максимальный и минимальный элементы принимаются за 1й эл. массива
int min = mass[1];
for (int i = 0; i < mass.length; i++) {
if (mass[i] > max) {
max = mass[i];
}
if (mass[i] < min) {
min = mass[i];
}
}
System.out.println("min = " + min + " max= " + max);
}
//Шестое задание
public static boolean SixthExample(int[] mass) {
// mass = {1, 2, 3, 6};
int leftSum = 0;
int rightSum = 0;
for (int i = 0; i < mass.length; i++) { //левая сумма
leftSum = leftSum + mass[i];
rightSum = 0;
for (int j = i + 1; j < mass.length; j++) { // считаем для сравнения сумму после i элемента
rightSum = rightSum + mass[j];
}
if (leftSum == rightSum) return true;
}
return false; // если ничего не нашли
}
//Седьмое задание
public static void SeventhExample(int n, int[] mass) {
// 1 и 1,2,3,4,5,6,7
if (n > 0) {
for (int i = 0; i < n; i++) { //повтор сдвига на n элементов
int cache = mass[mass.length - 1]; //сохранение 1го элемента
for (int j = (mass.length - 1); j > 0; j--) {
mass[j] = mass[j - 1]; //сдвиг всех остальных на 1
}
mass[0] = cache;
}
} else if (n < 0) {
for (int i = 0; i > n; i--) {
int cache = mass[0]; //сохранение 1го элемента
for (int j = 0; j < mass.length - 1; j++) {
mass[j] = mass[j + 1]; //сдвиг всех остальных на 1
}
mass[mass.length - 1] = cache;
}
}
System.out.println(Arrays.toString(mass));
}
//Дополнительное задание
public static void EightExample() {
int[] mass = {6, 5, 1, 3, 9};
for (int i = mass.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (mass[j] > mass[j + 1]) {
int buf = mass[j]; //сохраняется в переменную , чтоб не затерся
mass[j] = mass[j + 1];
mass[j + 1] = buf;
}
}
}
System.out.println(Arrays.toString(mass));
}
}
| [
"[email protected]"
] | |
c06593709885d150a62f858bd6e4a44675d26c29 | 3ed578548ab2e11953c9fc703cacdcefbdcd9037 | /URLShortener/src/com/url/model/strategy/StrategyContext.java | ac92a918218aa0d657c3b23944fa4f343d2fd220 | [] | no_license | muneebIfkaar/URLShortener | 2dcb3e699d7fb4e7ea04359132fee2235a25bc0b | c47ce2fd23586f150d2db73658ad6c6c38e9d050 | refs/heads/master | 2020-03-24T20:23:20.334367 | 2018-08-01T06:19:38 | 2018-08-01T06:19:38 | 142,975,495 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 373 | java | package com.url.model.strategy;
import com.url.model.beans.StrategyResponseBean;
import com.url.model.strategy.interfaces.IStrategy;
public class StrategyContext {
private final IStrategy strategy;
public StrategyContext(IStrategy strategy) {
this.strategy = strategy;
}
public StrategyResponseBean execute(Object obj) {
return strategy.execute(obj);
}
}
| [
"[email protected]"
] | |
fc47a28e4f880dff3daf8fac469af925ea9c8324 | ed3cb95dcc590e98d09117ea0b4768df18e8f99e | /project_1_2/src/h/e/c/Calc_1_2_7420.java | 68a07d30c2b3d9a13e100f1cde0bdd2af14765b8 | [] | no_license | chalstrick/bigRepo1 | ac7fd5785d475b3c38f1328e370ba9a85a751cff | dad1852eef66fcec200df10083959c674fdcc55d | refs/heads/master | 2016-08-11T17:59:16.079541 | 2015-12-18T14:26:49 | 2015-12-18T14:26:49 | 48,244,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 131 | java | package h.e.c;
public class Calc_1_2_7420 {
/** @return the sum of a and b */
public int add(int a, int b) {
return a+b;
}
}
| [
"[email protected]"
] | |
6b115f0fcc9e0293e8154a72b2b032872aded5e3 | e4acfacc5be1abe51be445b41814d5668b4cb0fb | /hw/hw4/hw4/puzzle/EightPuzzleSolver.java | 6b8232becfa96a6225df5b81a8d8e03898b5ea83 | [
"MIT"
] | permissive | Zhenye-Na/data-structures-ucb | 24a53bbc9a6c478caaedefddef1083eac7cf04d0 | ac1e4cdf63461673717dafdaed6b4c67af822ba4 | refs/heads/master | 2022-09-18T19:05:55.055858 | 2022-05-20T20:47:31 | 2022-07-22T05:40:11 | 125,691,541 | 81 | 37 | MIT | 2022-07-22T05:40:12 | 2018-03-18T04:10:21 | Java | UTF-8 | Java | false | false | 935 | java | package hw4.puzzle;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
public class EightPuzzleSolver {
/***********************************************************************
* Test routine for your Solver class. Uncomment and run to test
* your basic functionality.
**********************************************************************/
public static void main(String[] args) {
In in = new In(args[0]);
int N = in.readInt();
int[][] tiles = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
tiles[i][j] = in.readInt();
}
}
Board initial = new Board(tiles);
Solver solver = new Solver(initial);
StdOut.println("Minimum number of moves = " + solver.moves());
for (WorldState ws : solver.solution()) {
StdOut.println(ws);
}
}
}
| [
"[email protected]"
] | |
9b0af1b5ce557e771d35f8a01e69b69896442ca2 | d633710316bf8f3ac52c78e26dfdcd1bd5b3e942 | /EmbeddedSocialClient/sdk/src/main/java/com/microsoft/embeddedsocial/ui/util/ContentUpdateHelper.java | a0bfc9c7f5a1d9ab9b3cf9693ef629cbb9e32960 | [
"MIT"
] | permissive | tslilyai/EmbeddedSocial-Android-SDK | 5b83809de69b700c592fa59e1e23f98000748c1c | 4bff0a9b4687f5215440969b95b010c64c60f16b | refs/heads/master | 2021-09-03T16:37:40.839883 | 2018-01-10T13:49:57 | 2018-01-10T13:49:57 | 115,100,038 | 0 | 0 | null | 2017-12-22T09:29:28 | 2017-12-22T09:29:28 | null | UTF-8 | Java | false | false | 8,541 | java | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*/
package com.microsoft.embeddedsocial.ui.util;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Browser;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.Patterns;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.microsoft.embeddedsocial.autorest.models.ContentType;
import com.microsoft.embeddedsocial.account.AuthorizationCause;
import com.microsoft.embeddedsocial.account.UserAccount;
import com.microsoft.embeddedsocial.base.utils.debug.DebugLog;
import com.microsoft.embeddedsocial.data.Preferences;
import com.microsoft.embeddedsocial.data.storage.UserActionProxy;
import com.microsoft.embeddedsocial.image.ImageLoader;
import com.microsoft.embeddedsocial.image.ImageLocation;
import com.microsoft.embeddedsocial.image.ImageViewContentLoader;
import com.microsoft.embeddedsocial.pending.PendingLike;
import com.microsoft.embeddedsocial.pending.PendingPin;
import com.microsoft.embeddedsocial.sdk.R;
import com.microsoft.embeddedsocial.server.model.view.CommentView;
import com.microsoft.embeddedsocial.server.model.view.ReplyView;
import com.microsoft.embeddedsocial.server.model.view.TopicView;
import com.microsoft.embeddedsocial.service.IntentExtras;
import com.microsoft.embeddedsocial.ui.activity.ReportActivity;
import com.microsoft.embeddedsocial.ui.theme.ThemeAttributes;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Helper methods to update topics, comments and replies state.
*/
public final class ContentUpdateHelper {
private ContentUpdateHelper() {
}
public static void launchRemoveTopic(Context context, TopicView topic) {
new UserActionProxy(context).removeTopic(topic);
}
public static void launchRemoveComment(Context context, CommentView commentView) {
new UserActionProxy(context).removeComment(commentView);
}
public static void launchRemoveReply(Context context, ReplyView reply) {
new UserActionProxy(context).removeReply(reply);
}
public static void launchLike(Context context, String contentHandle, ContentType contentType, boolean liked) {
if (UserAccount.getInstance().checkAuthorization(AuthorizationCause.LIKE)) {
new UserActionProxy(context).setLikeStatus(contentHandle, contentType, liked);
} else {
Preferences.getInstance().setPendingAction(new PendingLike(contentHandle, contentType, liked));
}
}
public static void launchPin(Context context, String topicHandle, boolean pinned) {
if (UserAccount.getInstance().checkAuthorization(AuthorizationCause.PIN)) {
new UserActionProxy(context).setPinStatus(topicHandle, pinned);
} else {
Preferences.getInstance().setPendingAction(new PendingPin(topicHandle, pinned));
}
}
public static void startContentReport(Context context, String contentHandle, ContentType contentType) {
Intent intent = new Intent(context, ReportActivity.class);
intent.putExtra(IntentExtras.REPORT_CONTENT_HANDLE_EXTRA, contentHandle);
intent.putExtra(IntentExtras.REPORT_CONTENT_TYPE_EXTRA, contentType);
context.startActivity(intent);
}
public static void startUserReport(Context context, String userHandle, String userName) {
Intent intent = new Intent(context, ReportActivity.class);
intent.putExtra(IntentExtras.USER_HANDLE, userHandle);
intent.putExtra(IntentExtras.NAME, userName);
context.startActivity(intent);
}
public static void setProfileImage(Context context, @NonNull ImageViewContentLoader imageViewContentLoader, String photoUrl) {
int defaultDrawableId = ThemeAttributes.getResourceId(context, R.styleable.es_AppTheme_es_userNoPhotoIcon);
setProfileImage(imageViewContentLoader, photoUrl, defaultDrawableId);
}
public static void setProfileImage(@NonNull ImageViewContentLoader imageViewContentLoader, String photoUrl, @DrawableRes int defaultResId) {
ImageLocation profileImageLocation = ImageLocation.createUserPhotoImageLocation(photoUrl);
imageViewContentLoader.cancel();
if (profileImageLocation != null) {
final int profileImageWidth = imageViewContentLoader.getImageView().getResources().getDimensionPixelSize(R.dimen.es_user_icon_size);
imageViewContentLoader.load(profileImageLocation, profileImageWidth);
} else {
imageViewContentLoader.setImageResource(defaultResId);
}
}
public static void setProfileImage(@NonNull ImageViewContentLoader imageViewContentLoader, @DrawableRes int imageResId) {
imageViewContentLoader.setImageResource(imageResId);
}
private static final String SEARCH_SCHEME = "search://";
private static final String HTTP_SCHEME = "http://";
private static final String HTTPS_SCHEME = "https://";
private static final Pattern TAG_MATCHER = Pattern.compile("#+[A-Za-z0-9-_]+\\b");
public static void setTopicBody(Context context, @NonNull TextView topicBody, String topicText) {
if (TextUtils.isEmpty(topicText)) {
topicBody.setVisibility(View.GONE);
} else {
boolean hasLink = false;
Spannable spannable = new SpannableString(topicText);
Matcher matcher = TAG_MATCHER.matcher(spannable);
while (matcher.find()) {
hasLink = true;
final int start = matcher.start();
final int end = matcher.end();
spannable.setSpan(new URLSpanNoUnderline(SEARCH_SCHEME + spannable.subSequence(start + 1, end)), start, end, 0);
spannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.es_text_link_color)), start, end, 0);
}
Matcher urlMatcher = Patterns.WEB_URL.matcher(spannable);
while (urlMatcher.find()) {
hasLink = true;
final int start = urlMatcher.start();
final int end = urlMatcher.end();
String url = "" + spannable.subSequence(start, end);
if (!url.startsWith(HTTP_SCHEME) && ! url.startsWith(HTTPS_SCHEME)) {
url = HTTP_SCHEME + url;
}
spannable.setSpan(new URLSpan(url), start, end, 0);
}
if (hasLink) {
topicBody.setMovementMethod(LinkMovementMethod.getInstance());
}
topicBody.setText(spannable);
topicBody.setVisibility(View.VISIBLE);
}
}
public static void setTopicAppIcon(@NonNull ImageView postAppIcon, String appIconUrl) {
ImageLocation postAppIconLocation = ImageLocation.createUserPhotoImageLocation(appIconUrl);
ImageLoader.cancel(postAppIcon);
if (postAppIconLocation != null) {
final int postAppIconWidth = postAppIcon.getResources().getDimensionPixelSize(R.dimen.es_button_icon_size);
postAppIcon.setVisibility(View.VISIBLE);
ImageLoader.load(postAppIcon, postAppIconLocation.getUrl(postAppIconWidth));
} else {
postAppIcon.setVisibility(View.GONE);
}
}
public static void setTopicCoverImage(@NonNull ImageViewContentLoader imageViewContentLoader, ImageLocation coverImageLocation) {
imageViewContentLoader.cancel();
ImageView coverImage = imageViewContentLoader.getImageView();
if (coverImage == null) {
return;
}
if (coverImageLocation != null) {
final int coverImageWidth = coverImage.getResources().getDimensionPixelSize(R.dimen.es_card_cover_image_width);
coverImage.setVisibility(View.VISIBLE);
imageViewContentLoader.load(coverImageLocation, coverImageWidth);
} else {
coverImage.setVisibility(View.GONE);
}
}
private static class URLSpanNoUnderline extends URLSpan {
public URLSpanNoUnderline(String url) {
super(url);
}
@Override
public void updateDrawState(@NonNull TextPaint textPaint) {
super.updateDrawState(textPaint);
textPaint.setUnderlineText(false);
}
@Override
public void onClick(@NonNull View widget) {
Uri uri = Uri.parse(getURL());
Context context = widget.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
String packageName = context.getPackageName();
intent.putExtra(Browser.EXTRA_APPLICATION_ID, packageName);
intent.setPackage(packageName);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
DebugLog.w("Activity was not found for intent, " + intent.toString());
}
}
}
}
| [
"[email protected]"
] | |
647a69e04ef95e5e3d5a04ce7c3be9a19b7abc46 | 5c10830b0562073e580071e79b7ce64ecd764afc | /art/.svn/pristine/f1/f113d0f16f58750f66149575b7ddc777ba624c8c.svn-base | 740dac94943955394e6a43d40a0f455d8d4392ab | [] | no_license | DeeFromChina/art | 80f696d2425cbb8ff8f4c50736efe54225d93503 | 22b185ad02f912d945abaac4fd32a1dfd1b1e474 | refs/heads/master | 2021-06-23T08:23:41.066863 | 2017-06-25T13:47:04 | 2017-06-25T13:47:04 | 77,287,780 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,573 | package com.golead.art.works.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* This is an object that contains data related to the art_works_network table.
*/
@Entity
@Table(name="art_works_network")
public class ArtWorksNetwork implements Serializable {
private static final long serialVersionUID = 1L;
// primary key
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id", nullable = false)
private java.lang.Integer id; //
// properties
@Column(name = "network_id")
private java.lang.Integer networkId; // 网媒ID
@Column(name = "network_desc")
private java.lang.String networkDesc; // 描述
@Column(name = "works_id")
private java.lang.Integer worksId; // 作品id
// Constructors
public ArtWorksNetwork() {
}
public java.lang.Integer getId() {
return this.id;
}
public void setId(java.lang.Integer id) {
this.id = id;
}
public java.lang.Integer getNetworkId() {
return this.networkId;
}
public void setNetworkId(java.lang.Integer networkId) {
this.networkId = networkId;
}
public java.lang.String getNetworkDesc() {
return this.networkDesc;
}
public void setNetworkDesc(java.lang.String networkDesc) {
this.networkDesc = networkDesc;
}
public java.lang.Integer getWorksId() {
return this.worksId;
}
public void setWorksId(java.lang.Integer worksId) {
this.worksId = worksId;
}
public static String REF_CLASS = "ArtWorksNetwork";
public static String PROP_ID = "id";
public static String PROP_NETWORK_ID = "networkId";
public static String PROP_NETWORK_DESC = "networkDesc";
public static String PROP_WORKS_ID = "worksId";
public static String REF_TABLE = "art_works_network";
public static String COL_ID = "id";
public static String COL_NETWORK_ID = "network_id";
public static String COL_NETWORK_DESC = "network_desc";
public static String COL_WORKS_ID = "works_id";
public boolean equals(Object obj) {
if (null == obj) return false;
if (!(obj instanceof com.golead.art.works.model.ArtWorksNetwork)) return false;
else {
com.golead.art.works.model.ArtWorksNetwork o = (com.golead.art.works.model.ArtWorksNetwork) obj;
if (null == this.getId() || null == o.getId()) return false;
else return (this.getId().equals(o.getId()));
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[ArtWorksNetwork:");
buffer.append(" id:").append(id);
buffer.append(" networkId:").append(dealNull(networkId));
buffer.append(" networkDesc:").append(dealNull(networkDesc));
buffer.append(" worksId:").append(dealNull(worksId));
buffer.append("]");
return buffer.toString();
}
public String toJson() {
StringBuffer buffer = new StringBuffer();
buffer.append("{");
buffer.append("\"id\":\"").append(id).append("\"");
buffer.append(",\"networkId\":\"").append(dealNull(networkId)).append("\"");
buffer.append(",\"networkDesc\":\"").append(dealNull(networkDesc)).append("\"");
buffer.append(",\"worksId\":\"").append(dealNull(worksId)).append("\"");
buffer.append("}");
return buffer.toString();
}
private String dealNull(Object str) {
if(str==null) return ""; else return str.toString();
}
}
| [
"[email protected]"
] | ||
5058ff5ee1e21469e08fd3a90422faa6e4f565e0 | a0808470d18d9ca7fec0e4c94a9e6feb77f095a3 | /src/test/java/com/yuditsky/classroom/ClassroomApplicationTests.java | b1743fd239cac38911982ea7da2acfde5999b83a | [] | no_license | VladislavYuditsky/Classroom-Server | 97ed5e94663af59504a8f1687d673aac46550f39 | e95b3d6692a09fbb0882949374baba4aaa64669e | refs/heads/master | 2022-12-20T18:28:10.331822 | 2020-10-15T15:30:22 | 2020-10-15T15:30:22 | 298,307,172 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 217 | java | package com.yuditsky.classroom;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ClassroomApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
8449273427f2fce29a87c15440cc5c1046ab664f | a68f2098f94de13924727abb8387864ad06b7044 | /ProjectJava/AppiumDemo/src/appiumdemo/TestDataAppium.java | 369f513ddc2a2bc8bd35f4b921d800c9384c702b | [] | no_license | thuyduongnt/java-project | cc9e6597b1a4b874b16bdcbb1003bf3b75a5b3d4 | 6d4342a3f36018c2c299afc02cc076c91288a231 | refs/heads/master | 2021-08-29T21:49:43.489777 | 2017-12-15T04:20:31 | 2017-12-15T04:20:31 | 114,326,444 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,763 | java | package appiumdemo;
import java.lang.reflect.Method;
import org.testng.annotations.DataProvider;
public class TestDataAppium {
@DataProvider(name = "data")
public Object[][] GetData(Method name) {
Object[][] obj = new Object[1][1];
if (name.getName().equals("testFullName")) {
obj = new Object[2][2];
obj[0][0] = "";
obj[0][1] = "Mục này còn thiếu";
obj[1][0] = "duongntt";
obj[1][1] = "";
}
else if (name.getName().equals("validateEmail")) {
obj = new Object[7][2];
obj[0][0] = "";
obj[0][1] = "Mục này còn thiếu";
obj[1][0] = "thuyduonghp@";
obj[1][1] = "Vui lòng nhập một email hợp lệ";
obj[2][0] = "thuyduonghp@hotmail";
obj[2][1] = "Vui lòng nhập một email hợp lệ";
obj[3][0] = "thuyduonghp@hotmail.";
obj[3][1] = "Vui lòng nhập một email hợp lệ";
obj[4][0] = "[email protected]";
obj[4][1] = "Vui lòng nhập một email hợp lệ";
obj[5][0] = "thuyduonghphotmail.com";
obj[5][1] = "Vui lòng nhập một email hợp lệ";
obj[6][0] = "[email protected]";
obj[6][1] = "";
}
else if (name.getName().equals("validatePassword")) {
obj = new Object[6][2];
obj[0][0] = "";
obj[0][1] = "Mục này còn thiếu";
obj[1][0] = "123";
obj[1][1] = "Mật khẩu phải chứa ít nhất 6 ký tự";
obj[2][0] = "abc abc";
obj[2][1] = "Mật khẩu phải chứa ít nhất một chữ và số.";
obj[3][0] = "123 123";
obj[3][1] = "Mật khẩu phải chứa ít nhất một chữ và số.";
obj[4][0] = "123ab";
obj[4][1] = "Mật khẩu phải chứa ít nhất 6 ký tự";
obj[5][0] = "abc123 ";
obj[5][1] = "";
}
//else if()
return obj;
}
}
| [
"[email protected]"
] | |
37463d5be9d38433bfc26294590faaf5287644bd | 1b190151c2a2ed1b04fba5d836c6bee2a45201ab | /app/src/test/java/com/example/taichi/myapplication/ExampleUnitTest.java | 41aded5ef3766fb18c058c8aeca48aa71df2789d | [] | no_license | taichi-jp/HelloAndroidApp | b18fbad9a0464fda0d44cea88a7e6ba2932dd9a9 | ffe3acfb31a9073f689add1da575f5d7282d953e | refs/heads/master | 2021-08-19T07:40:23.311769 | 2017-11-25T07:47:42 | 2017-11-25T07:47:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 410 | java | package com.example.taichi.myapplication;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.