hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923620637c17455eea2a2941b7284f0a11d47384 | 1,279 | java | Java | shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/fixture/YamlRuleConfigurationFixture.java | aniketh-varma/shardingsphere | 6ebef5296b4e726beb06d2947bbc46b27942e425 | [
"Apache-2.0"
] | 5,788 | 2020-04-17T14:09:07.000Z | 2022-03-31T08:12:53.000Z | shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/fixture/YamlRuleConfigurationFixture.java | aniketh-varma/shardingsphere | 6ebef5296b4e726beb06d2947bbc46b27942e425 | [
"Apache-2.0"
] | 6,488 | 2020-04-17T14:21:54.000Z | 2022-03-31T21:36:33.000Z | shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/coordinator/fixture/YamlRuleConfigurationFixture.java | aniketh-varma/shardingsphere | 6ebef5296b4e726beb06d2947bbc46b27942e425 | [
"Apache-2.0"
] | 2,504 | 2020-04-17T14:09:46.000Z | 2022-03-31T12:21:31.000Z | 36.542857 | 82 | 0.769351 | 997,556 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.mode.manager.cluster.coordinator.fixture;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.infra.yaml.config.pojo.YamlRuleConfiguration;
@Getter
@Setter
public final class YamlRuleConfigurationFixture implements YamlRuleConfiguration {
private String name;
@Override
public Class<RuleConfigurationFixture> getRuleConfigurationType() {
return RuleConfigurationFixture.class;
}
}
|
923620b7600e84f213e60379b77bd88b1aa28001 | 314 | java | Java | src/main/java/com/exemplo/simples/SimplesApplication.java | marco-aurelioo/TestePdf | 0da5649cd892dc065425c0e97a141733327b8788 | [
"MIT"
] | null | null | null | src/main/java/com/exemplo/simples/SimplesApplication.java | marco-aurelioo/TestePdf | 0da5649cd892dc065425c0e97a141733327b8788 | [
"MIT"
] | null | null | null | src/main/java/com/exemplo/simples/SimplesApplication.java | marco-aurelioo/TestePdf | 0da5649cd892dc065425c0e97a141733327b8788 | [
"MIT"
] | null | null | null | 22.428571 | 68 | 0.821656 | 997,557 | package com.exemplo.simples;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SimplesApplication {
public static void main(String[] args) {
SpringApplication.run(SimplesApplication.class, args);
}
}
|
923621060b24b058addfbad5f8c14fc3e3382b88 | 7,427 | java | Java | ruoyi-pay/src/main/java/com/ruoyi/pay/utils/WeixinMessageUtil.java | HaiRonin/hospital-xuwen | 43399598991f6007b0dbaf18513dd4ea5e0919af | [
"MIT"
] | 1 | 2021-11-17T03:19:22.000Z | 2021-11-17T03:19:22.000Z | ruoyi-pay/src/main/java/com/ruoyi/pay/utils/WeixinMessageUtil.java | HaiRonin/hospital-xuwen | 43399598991f6007b0dbaf18513dd4ea5e0919af | [
"MIT"
] | 2 | 2020-09-14T15:00:15.000Z | 2020-09-14T15:03:15.000Z | ruoyi-pay/src/main/java/com/ruoyi/pay/utils/WeixinMessageUtil.java | HaiRonin/hospital-xuwen | 43399598991f6007b0dbaf18513dd4ea5e0919af | [
"MIT"
] | 3 | 2020-08-09T09:01:34.000Z | 2021-11-17T03:19:24.000Z | 34.868545 | 136 | 0.604686 | 997,558 | package com.ruoyi.pay.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pay.config.WechatConfig;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description : 微信消息工具
* @Author : yuanhualiang
* @Date: 2020-09-05 00:33
*/
public class WeixinMessageUtil {
private static final Logger LOG = LoggerFactory.getLogger(WeixinMessageUtil.class);
private static final String CACHE_ACCESS_TOKEN = "CACHE_ACCESS_TOKEN";
private static final String CACHE_JSAPI_TICKET = "WX_SHARE_JSAPI_TICKET";
/**
* 获取TOKEN
*
* @return
*/
public static String getAccessToken(RedisUtil redisUtil) {
Object accessTokenCache = redisUtil.get(CACHE_ACCESS_TOKEN);
LOG.info(">>>>>>>>>>>>>>>>>>>缓存获取accessToken=" + accessTokenCache);
if (null != accessTokenCache) {
return (String) accessTokenCache;
}
AccessToken accessToken = null;
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=#APPID#&secret=#APPSECRET#";
String requestUrl = accessTokenUrl.replace(
"#APPID#", WechatConfig.appId).replace(
"#APPSECRET#", WechatConfig.appsecret);
JSONObject jsonObject = httpRequestForSSL(requestUrl, "GET", null);
LOG.info(">>>>>>>>>>>>>>>>>获取accessToken结果:" + JSON.toJSONString(jsonObject));
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
} catch (JSONException e) {
accessToken = null;
// 获取token失败
LOG.error("获取token失败 errcode:{} errmsg:{}",
jsonObject.getIntValue("errcode"),
jsonObject.getString("errmsg"));
}
}
String accessTokenStr = "";
if (null != accessToken) {
accessTokenStr = accessToken.getToken();
if (StringUtils.isNotEmpty(accessTokenStr) && !"null".equals(accessTokenStr)) {
redisUtil.set(CACHE_ACCESS_TOKEN, accessTokenStr,
3600);
}
}
return accessTokenStr;
}
/**
* 解析XML请求
*
* @param request
* @return
* @throws Exception
*/
public static Map<String, String> parseXml(HttpServletRequest request)
throws Exception {
// 将解析结果存储在HashMap中
Map<String, String> map = new HashMap<String, String>();
// 从request中取得输入流
InputStream inputStream = request.getInputStream();
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
// 遍历所有子节点
for (Element e : elementList)
map.put(e.getName(), e.getText());
// 释放资源
inputStream.close();
inputStream = null;
return map;
}
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequestForSSL(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
LOG.error("Weixin server connection timed out.");
} catch (Exception e) {
LOG.error("https request error:{}", e);
}
return jsonObject;
}
/**
* 获取公众号ticket
*
* @param accessToken
* @return
* @throws Exception
*/
public static String getJsapiTicket(String accessToken, RedisUtil redisUtil) {
Object ticketObj = redisUtil.get(CACHE_JSAPI_TICKET);
LOG.info(">>>>>>>>>>>>>>>>>>>缓存获取ticket=" + ticketObj);
if (null != ticketObj) {
return (String) ticketObj;
} else {
String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
+ accessToken + "&type=jsapi";
JSONObject jsonObject = httpRequestForSSL(ticketUrl, "GET",
null);
LOG.info(">>>>>>>>>>>>>>>>>获取ticket结果:" + JSON.toJSONString(jsonObject));
String ticket = jsonObject.getString("ticket");
if (StringUtils.isNotEmpty(ticket) && !"null".equals(ticket)) {
redisUtil.set(CACHE_JSAPI_TICKET, ticket,
3600);
}
return ticket;
}
}
}
|
923621d5d44d1b175cc415bdb663db451d4e6759 | 2,318 | java | Java | src/main/java/com/isentropy/accumulo/collections/io/JavaSerializationSerde.java | isentropy/accumulo-collections | 77ee96a5e81a57644659d61b9b08e3eeeb7f66ac | [
"Apache-2.0"
] | 7 | 2016-04-26T21:01:38.000Z | 2016-08-12T19:17:13.000Z | src/main/java/com/isentropy/accumulo/collections/io/JavaSerializationSerde.java | isentropy/accumulo-collections | 77ee96a5e81a57644659d61b9b08e3eeeb7f66ac | [
"Apache-2.0"
] | null | null | null | src/main/java/com/isentropy/accumulo/collections/io/JavaSerializationSerde.java | isentropy/accumulo-collections | 77ee96a5e81a57644659d61b9b08e3eeeb7f66ac | [
"Apache-2.0"
] | null | null | null | 29.0125 | 82 | 0.762602 | 997,559 | /*
Accumulo Collections
Copyright 2016 Isentropy LLC
Written by Jonathan Wolff <kenaa@example.com>
Isentropy specializes in big data and quantitative programming consulting,
with particular expertise in Accumulo development and installation.
More info at http://isentropy.com.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.isentropy.accumulo.collections.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.isentropy.accumulo.collections.AccumuloSortedMap;
import com.isentropy.accumulo.util.Util;
public class JavaSerializationSerde implements SerDe{
public static Logger log = LoggerFactory.getLogger(JavaSerializationSerde.class);
public static byte[] javaSerialize(Object o){
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
ObjectOutputStream out;
try {
out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
} catch (IOException e) {
log.error(e.getMessage());
return null;
}
byte[] rslt= bos.toByteArray();
//log.debug("serialize: "+o+" = "+rslt.length+" "+Util.bytesToHex(rslt));
return rslt;
}
public static Object javaDeserialize(byte[] b){
return javaDeserialize(b,0,b.length);
}
public static Object javaDeserialize(byte[] b, int offset, int len){
ByteArrayInputStream bis = new ByteArrayInputStream(b,offset,len);
try{
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
catch(Exception e){
log.error(e.getMessage());
return null;
}
}
@Override
public byte[] serialize(Object o){
return javaSerialize(o);
}
@Override
public Object deserialize(byte[] b){
return javaDeserialize(b);
}
}
|
923622738b83a4666634bf199cd5742fa52aa433 | 12,577 | java | Java | src/org/blojsom/blog/FileBackedBlogCategory.java | apple-opensource-mirror/blojsom | 88e836eff56f33f840d37db7303bfbf3e972309f | [
"Unlicense"
] | null | null | null | src/org/blojsom/blog/FileBackedBlogCategory.java | apple-opensource-mirror/blojsom | 88e836eff56f33f840d37db7303bfbf3e972309f | [
"Unlicense"
] | null | null | null | src/org/blojsom/blog/FileBackedBlogCategory.java | apple-opensource-mirror/blojsom | 88e836eff56f33f840d37db7303bfbf3e972309f | [
"Unlicense"
] | 1 | 2021-06-10T15:19:37.000Z | 2021-06-10T15:19:37.000Z | 37.320475 | 148 | 0.650314 | 997,560 | /**
* Copyright (c) 2003-2005 , David A. Czarnecki
* All rights reserved.
*
* Portions Copyright (c) 2003-2005 by Mark Lussier
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the "David A. Czarnecki" and "blojsom" nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Products derived from this software may not be called "blojsom",
* nor may "blojsom" appear in their name, without prior written permission of
* David A. Czarnecki.
*
* 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
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER 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.
*/
package org.blojsom.blog;
import org.blojsom.util.BlojsomUtils;
import org.blojsom.util.BlojsomProperties;
import org.blojsom.util.BlojsomConstants;
import org.blojsom.BlojsomException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.List;
import java.util.ArrayList;
/**
* FileBackedBlogCategory
*
* @author David Czarnecki
* @version $Id: FileBackedBlogCategory.java,v 1.2.2.1 2005/07/21 14:11:02 johnan Exp $
*/
public class FileBackedBlogCategory extends BlogCategory {
private Log _logger = LogFactory.getLog(FileBackedBlogCategory.class);
protected BlogUser _blogUser;
/**
* Create a new FileBackedBlogCategory.
*/
public FileBackedBlogCategory() {
super();
}
/**
* Create a new FileBackedBlogCategory.
*
* @param category Category name
* @param categoryURL Category URL
*/
public FileBackedBlogCategory(String category, String categoryURL) {
super(category, categoryURL);
}
/**
* Load the meta data for the category
*
* @param blogHome Directory where blog entries are stored
* @param propertiesExtensions List of file extensions to use when looking for category properties
*/
protected void loadMetaData(String blogHome, String[] propertiesExtensions) {
File blog = new File(blogHome + BlojsomUtils.removeInitialSlash(_category));
// Load properties file for category (if present)
File[] categoryPropertyFiles = blog.listFiles(BlojsomUtils.getExtensionsFilter(propertiesExtensions));
if ((categoryPropertyFiles != null) && (categoryPropertyFiles.length > 0)) {
Properties dirProps = new BlojsomProperties();
for (int i = 0; i < categoryPropertyFiles.length; i++) {
try {
FileInputStream _fis = new FileInputStream(categoryPropertyFiles[i]);
dirProps.load(_fis);
_fis.close();
} catch (IOException ex) {
_logger.warn("Failed loading properties from: " + categoryPropertyFiles[i].toString());
continue;
}
}
setMetaData(dirProps);
}
}
/**
* Load a blog category.
*
* @param blog {@link Blog}
* @throws BlojsomException If there is an error loading the category
* @since blojsom 1.9.1
* @deprecated
*/
public void load(Blog blog) throws BlojsomException {
}
/**
* Save the blog category.
*
* @param blog {@link Blog}
* @throws BlojsomException If there is an error saving the category
* @since blojsom 1.9.1
* @deprecated
*/
public void save(Blog blog) throws BlojsomException {
}
/**
* Delete the blog category.
*
* @param blog {@link Blog}
* @throws BlojsomException If there is an error deleting the category
* @since blojsom 1.9.1
* @deprecated
*/
public void delete(Blog blog) throws BlojsomException {
}
/**
* Load a blog category. Currently only loads the blog meta-data from disk.
*
* @param blogUser {@link BlogUser}
* @throws BlojsomException If there is an error loading the category
* @since blojsom 2.22
*/
public void load(BlogUser blogUser) throws BlojsomException {
_blogUser = blogUser;
Blog blog = blogUser.getBlog();
loadMetaData(blog.getBlogHome(), blog.getBlogPropertiesExtensions());
}
/**
* Save the blog category.
*
* @param blogUser {@link BlogUser}
* @throws BlojsomException If there is an error saving the category
* @since blojsom 2.22
*/
public void save(BlogUser blogUser) throws BlojsomException {
_blogUser = blogUser;
Blog blog = blogUser.getBlog();
File blogCategory = new File(blog.getBlogHome() + BlojsomUtils.removeInitialSlash(_category));
// If the category does not exist, try and create it
if (!blogCategory.exists()) {
if (!blogCategory.mkdirs()) {
_logger.error("Could not create new blog category at: " + blogCategory.toString());
return;
}
}
// We know the category exists so try and save its meta-data
String propertiesExtension = blog.getBlogPropertiesExtensions()[0];
File categoryMetaDataFile = new File(blogCategory, "blojsom" + propertiesExtension);
Properties categoryMetaData = BlojsomUtils.mapToProperties(_metadata, BlojsomConstants.UTF8);
try {
FileOutputStream fos = new FileOutputStream(categoryMetaDataFile);
categoryMetaData.store(fos, null);
fos.close();
} catch (IOException e) {
_logger.error(e);
throw new BlojsomException("Unable to save blog category", e);
}
_logger.debug("Saved blog category: " + blogCategory.toString());
}
/**
* Delete the blog category.
*
* @param blogUser {@link BlogUser}
* @throws BlojsomException If there is an error deleting the category
* @since blojsom 2.22
*/
public void delete(BlogUser blogUser) throws BlojsomException {
_blogUser = blogUser;
Blog blog = blogUser.getBlog();
File blogCategory = new File(blog.getBlogHome() + BlojsomUtils.removeInitialSlash(_category));
if (blogCategory.equals(blog.getBlogHome())) {
if (!BlojsomUtils.deleteDirectory(blogCategory, false)) {
throw new BlojsomException("Unable to delete blog category directory: " + _category);
}
} else {
if (!BlojsomUtils.deleteDirectory(blogCategory)) {
throw new BlojsomException("Unable to delete blog category directory: " + _category);
}
}
_logger.debug("Deleted blog category: " + blogCategory.toString());
}
/**
* Recursively count the blog entries in a blog directory
*
* @param blog {@link Blog}
* @param recursive Set to <code>true</code> if entries in sub-categories should be counted
* @param rootDirectory
* @return
*/
protected int recursiveBlogEntriesCounter(Blog blog, boolean recursive, String rootDirectory) {
File blogDirectory = new File(rootDirectory);
File[] directories;
int totalEntries = 0;
if (blog.getBlogDirectoryFilter() == null) {
directories = blogDirectory.listFiles(BlojsomUtils.getDirectoryFilter());
} else {
directories = blogDirectory.listFiles(BlojsomUtils.getDirectoryFilter(blog.getBlogDirectoryFilter()));
}
File[] entries = blogDirectory.listFiles(BlojsomUtils.getRegularExpressionFilter(blog.getBlogFileExtensions()));
if (entries == null) {
totalEntries = 0;
} else {
totalEntries = entries.length;
}
if (directories != null && recursive) {
for (int i = 0; i < directories.length; i++) {
File directory = directories[i];
return totalEntries + recursiveBlogEntriesCounter(blog, recursive, directory.toString());
}
}
return totalEntries;
}
/**
* Count the number of blog entries in this category. If <code>recursive</code> is true, the method
* will also count entries in all sub-categories.
*
* @param blog {@link Blog}
* @param recursive Set to <code>true</code> if entries in sub-categories should be counted
* @return Number of blog entries in this category
* @since blojsom 2.22
*/
public int countBlogEntries(Blog blog, boolean recursive) {
int totalEntries = recursiveBlogEntriesCounter(blog, recursive, blog.getBlogHome() + _category);
return totalEntries;
}
/**
* Build a list of blog categories recursively
*
* @param blogUser {@link BlogUser}
* @param blogDepth Depth at which the current iteration is running
* @param blogDirectoryDepth Depth to which the fetcher should stop looking for categories
* @param blogDirectory Directory in which the current iteration is running
* @param categoryList Dynamic list of categories that gets added to as it explores directories
*/
protected void recursiveCategoryBuilder(BlogUser blogUser, int blogDepth, int blogDirectoryDepth, String blogDirectory, List categoryList) {
Blog blog = blogUser.getBlog();
blogDepth++;
if (blogDirectoryDepth != BlojsomConstants.INFINITE_BLOG_DEPTH) {
if (blogDepth == blogDirectoryDepth) {
return;
}
}
File blogDir = new File(blogDirectory);
File[] directories;
if (blog.getBlogDirectoryFilter() == null) {
directories = blogDir.listFiles(BlojsomUtils.getDirectoryFilter());
} else {
directories = blogDir.listFiles(BlojsomUtils.getDirectoryFilter(blog.getBlogDirectoryFilter()));
}
String categoryKey = BlojsomUtils.getBlogCategory(blog.getBlogHome(), blogDirectory);
if (!categoryKey.endsWith("/")) {
categoryKey += "/";
}
BlogCategory blogCategory = new FileBackedBlogCategory();
blogCategory.setParentCategory(this);
blogCategory.setCategory(categoryKey);
blogCategory.setCategoryURL(blog.getBlogURL() + BlojsomUtils.removeInitialSlash(categoryKey));
try {
blogCategory.load(blogUser);
} catch (BlojsomException e) {
_logger.error(e);
}
if (blogDepth != 0) {
categoryList.add(blogCategory);
}
if (directories == null) {
return;
} else {
for (int i = 0; i < directories.length; i++) {
File directory = directories[i];
recursiveCategoryBuilder(blogUser, blogDepth, blogDirectoryDepth, directory.toString(), categoryList);
}
}
}
/**
* Return a list of sub-categories under the current category
*
* @return {@link java.util.List} of sub-categories as {@link BlogCategory} objects
* @since blojsom 2.22
*/
public List getSubcategories() {
_subcategories = new ArrayList();
recursiveCategoryBuilder(_blogUser, -1, -1, _blogUser.getBlog().getBlogHome() + BlojsomUtils.removeInitialSlash(_category), _subcategories);
return _subcategories;
}
}
|
923622c7d667f23f2f1d6fd681d0030659da75a3 | 501 | java | Java | mark-product/src/main/java/com/lzy/mark/markproduct/dao/AttrDao.java | 859450408/Mark-lzy | 64f683b3e19055b4e1d331d004dc5043749da4b9 | [
"Apache-2.0"
] | null | null | null | mark-product/src/main/java/com/lzy/mark/markproduct/dao/AttrDao.java | 859450408/Mark-lzy | 64f683b3e19055b4e1d331d004dc5043749da4b9 | [
"Apache-2.0"
] | null | null | null | mark-product/src/main/java/com/lzy/mark/markproduct/dao/AttrDao.java | 859450408/Mark-lzy | 64f683b3e19055b4e1d331d004dc5043749da4b9 | [
"Apache-2.0"
] | null | null | null | 23.857143 | 73 | 0.764471 | 997,561 | package com.lzy.mark.markproduct.dao;
import com.lzy.mark.markproduct.entity.AttrEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 商品属性
*
* @author Liangzhanyi
* @email anpch@example.com
* @date 2021-11-27 07:12:10
*/
@Mapper
public interface AttrDao extends BaseMapper<AttrEntity> {
List<Long> selectSearchAttrIds(@Param("attrIds") List<Long> attrIds);
}
|
923622c8040f0e75c298aa13922536caadcdecad | 1,196 | java | Java | java/com/google/collide/dto/LogFatalRecord.java | codyopel/collide | f90d968bbe7da0c2c995aaee4d332fc49c51c2b6 | [
"Apache-2.0"
] | 90 | 2015-01-29T11:16:53.000Z | 2021-11-17T11:46:12.000Z | java/com/google/collide/dto/LogFatalRecord.java | codyopel/collide | f90d968bbe7da0c2c995aaee4d332fc49c51c2b6 | [
"Apache-2.0"
] | 4 | 2016-09-01T14:24:16.000Z | 2018-07-29T12:55:15.000Z | java/com/google/collide/dto/LogFatalRecord.java | codyopel/collide | f90d968bbe7da0c2c995aaee4d332fc49c51c2b6 | [
"Apache-2.0"
] | 47 | 2015-02-16T09:47:34.000Z | 2021-06-17T18:31:08.000Z | 33.222222 | 80 | 0.768395 | 997,562 | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.collide.dto;
import com.google.collide.dtogen.shared.ClientToServerDto;
import com.google.collide.dtogen.shared.RoutingType;
import com.google.collide.json.shared.JsonArray;
/**
* Fatal log messages are annotated with the window location, permutation, and a
* serialized throwable.
*/
@RoutingType(type = RoutingTypes.LOGFATALRECORD)
public interface LogFatalRecord extends ClientToServerDto {
String getMessage();
String getWindowLocation();
JsonArray<String> getRecentHistory();
String getPermutationStrongName();
ThrowableDto getThrowable();
}
|
9236247f1e5c77c5ceaf869b7a9d7fc698c95a82 | 14,490 | java | Java | public/java/src/org/broadinstitute/sting/gatk/walkers/variantutils/VariantValidationAssessor.java | ssadedin/gatk | c85374f5f9e06d6764e8ef4d0334ffe4f3cf8603 | [
"MIT"
] | null | null | null | public/java/src/org/broadinstitute/sting/gatk/walkers/variantutils/VariantValidationAssessor.java | ssadedin/gatk | c85374f5f9e06d6764e8ef4d0334ffe4f3cf8603 | [
"MIT"
] | null | null | null | public/java/src/org/broadinstitute/sting/gatk/walkers/variantutils/VariantValidationAssessor.java | ssadedin/gatk | c85374f5f9e06d6764e8ef4d0334ffe4f3cf8603 | [
"MIT"
] | null | null | null | 48.139535 | 174 | 0.690338 | 997,563 | /*
* Copyright (c) 2010.
*
* 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 org.broadinstitute.sting.gatk.walkers.variantutils;
import org.broadinstitute.sting.commandline.*;
import org.broadinstitute.sting.gatk.CommandLineGATK;
import org.broadinstitute.sting.gatk.arguments.StandardVariantContextInputArgumentCollection;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.walkers.*;
import org.broadinstitute.sting.utils.QualityUtils;
import org.broadinstitute.sting.utils.SampleUtils;
import org.broadinstitute.sting.utils.codecs.vcf.*;
import org.broadinstitute.sting.utils.help.DocumentedGATKFeature;
import org.broadinstitute.sting.utils.variantcontext.writer.VariantContextWriter;
import org.broadinstitute.sting.utils.variantcontext.Allele;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;
import org.broadinstitute.sting.utils.variantcontext.VariantContextBuilder;
import org.broadinstitute.sting.utils.variantcontext.VariantContextUtils;
import java.util.*;
/**
* Annotates a validation (from Sequenom for example) VCF with QC metrics (HW-equilibrium, % failed probes)
*
* <p>
* The Variant Validation Assessor is a tool for vetting/assessing validation data (containing genotypes).
* The tool produces a VCF that is annotated with information pertaining to plate quality control and by
* default is soft-filtered by high no-call rate or low Hardy-Weinberg probability.
* If you have .ped files, please first convert them to VCF format.
*
* <h2>Input</h2>
* <p>
* A validation VCF to annotate.
* </p>
*
* <h2>Output</h2>
* <p>
* An annotated VCF. Additionally, a table like the following will be output:
* <pre>
* Total number of samples assayed: 185
* Total number of records processed: 152
* Number of Hardy-Weinberg violations: 34 (22%)
* Number of no-call violations: 12 (7%)
* Number of homozygous variant violations: 0 (0%)
* Number of records passing all filters: 106 (69%)
* Number of passing records that are polymorphic: 98 (92%)
* </pre>
* </p>
*
* <h2>Examples</h2>
* <pre>
* java -Xmx2g -jar GenomeAnalysisTK.jar \
* -R ref.fasta \
* -T VariantValidationAssessor \
* --variant input.vcf \
* -o output.vcf
* </pre>
*
*/
@DocumentedGATKFeature( groupName = "Validation Utilities", extraDocs = {CommandLineGATK.class} )
@Reference(window=@Window(start=0,stop=40))
public class VariantValidationAssessor extends RodWalker<VariantContext,Integer> {
@ArgumentCollection
protected StandardVariantContextInputArgumentCollection variantCollection = new StandardVariantContextInputArgumentCollection();
@Output(doc="File to which variants should be written",required=true)
protected VariantContextWriter vcfwriter = null;
@Argument(fullName="maxHardy", doc="Maximum phred-scaled Hardy-Weinberg violation pvalue to consider an assay valid", required=false)
protected double maxHardy = 20.0;
/**
* To disable, set to a value greater than 1.
*/
@Argument(fullName="maxNoCall", doc="Maximum no-call rate (as a fraction) to consider an assay valid", required=false)
protected double maxNoCall = 0.05;
/**
* To disable, set to a value greater than 1.
*/
@Argument(fullName="maxHomVar", doc="Maximum homozygous variant rate (as a fraction) to consider an assay valid", required=false)
protected double maxHomNonref = 1.1;
//@Argument(fullName="populationFile", shortName="populations", doc="A tab-delimited file relating individuals to populations,"+
// "used for smart Hardy-Weinberg annotation",required = false)
//private File popFile = null;
// sample names
private TreeSet<String> sampleNames = null;
// variant context records
private ArrayList<VariantContext> records = new ArrayList<VariantContext>();
// statistics
private int numRecords = 0;
private int numHWViolations = 0;
private int numNoCallViolations = 0;
private int numHomVarViolations = 0;
private int numTrueVariants = 0;
//private HashMap<String,String> samplesToPopulation;
public void initialize() {
//if ( popFile != null ) {
// samplesToPopulation = parsePopulationFile(popFile);
//}
}
public Integer reduceInit() {
return 0;
}
public VariantContext map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
if ( tracker == null )
return null;
VariantContext vc = tracker.getFirstValue(variantCollection.variants, ref.getLocus());
// ignore places where we don't have a variant
if ( vc == null )
return null;
if ( sampleNames == null )
sampleNames = new TreeSet<String>(vc.getSampleNames());
return addVariantInformationToCall(vc);
}
public Integer reduce(VariantContext call, Integer numVariants) {
if ( call != null ) {
numVariants++;
records.add(call);
}
return numVariants;
}
public void onTraversalDone(Integer finalReduce) {
final List<String> inputNames = Arrays.asList(variantCollection.variants.getName());
// setup the header fields
Set<VCFHeaderLine> hInfo = new HashSet<VCFHeaderLine>();
hInfo.addAll(VCFUtils.getHeaderFields(getToolkit(), inputNames));
// set up the info and filter headers
hInfo.add(new VCFInfoHeaderLine("NoCallPct", 1, VCFHeaderLineType.Float, "Percent of no-calls"));
hInfo.add(new VCFInfoHeaderLine("HomRefPct", 1, VCFHeaderLineType.Float, "Percent of homozygous reference genotypes"));
hInfo.add(new VCFInfoHeaderLine("HetPct", 1, VCFHeaderLineType.Float, "Percent of heterozygous genotypes"));
hInfo.add(new VCFInfoHeaderLine("HomVarPct", 1, VCFHeaderLineType.Float, "Percent homozygous variant genotypes"));
hInfo.add(new VCFInfoHeaderLine("HW", 1, VCFHeaderLineType.Float, "Phred-scaled Hardy-Weinberg violation p-value"));
hInfo.add(VCFStandardHeaderLines.getInfoLine(VCFConstants.ALLELE_COUNT_KEY));
hInfo.add(VCFStandardHeaderLines.getInfoLine(VCFConstants.ALLELE_NUMBER_KEY));
hInfo.add(new VCFFilterHeaderLine("HardyWeinbergViolation", "The validation is in Hardy-Weinberg violation"));
hInfo.add(new VCFFilterHeaderLine("HighNoCallRate", "The validation no-call rate is too high"));
hInfo.add(new VCFFilterHeaderLine("TooManyHomVars", "The validation homozygous variant rate is too high"));
// print out (and add to headers) the validation metrics
System.out.println(String.format("Total number of samples assayed:\t\t\t%d", sampleNames.size()));
hInfo.add(new VCFHeaderLine("ValidationMetrics_SamplesAssayed", String.format("%d", sampleNames.size())));
System.out.println(String.format("Total number of records processed:\t\t\t%d", numRecords));
hInfo.add(new VCFHeaderLine("ValidationMetrics_RecordsProcessed", String.format("%d", numRecords)));
if ( numRecords > 0 ) {
System.out.println(String.format("Number of Hardy-Weinberg violations:\t\t\t%d (%d%%)", numHWViolations, 100*numHWViolations/numRecords));
hInfo.add(new VCFHeaderLine("ValidationMetrics_HardyWeinbergViolations", String.format("\"%d (%d%%)\"", numHWViolations, 100*numHWViolations/numRecords)));
System.out.println(String.format("Number of no-call violations:\t\t\t\t%d (%d%%)", numNoCallViolations, 100*numNoCallViolations/numRecords));
hInfo.add(new VCFHeaderLine("ValidationMetrics_NoCallViolations", String.format("\"%d (%d%%)\"", numNoCallViolations, 100*numNoCallViolations/numRecords)));
System.out.println(String.format("Number of homozygous variant violations:\t\t%d (%d%%)", numHomVarViolations, 100*numHomVarViolations/numRecords));
hInfo.add(new VCFHeaderLine("ValidationMetrics_HomVarViolations", String.format("\"%d (%d%%)\"", numHomVarViolations, 100*numHomVarViolations/numRecords)));
int goodRecords = numRecords - numHWViolations - numNoCallViolations - numHomVarViolations;
System.out.println(String.format("Number of records passing all filters:\t\t\t%d (%d%%)", goodRecords, 100*goodRecords/numRecords));
hInfo.add(new VCFHeaderLine("ValidationMetrics_RecordsPassingFilters", String.format("\"%d (%d%%)\"", goodRecords, 100*goodRecords/numRecords)));
if ( goodRecords > 0 ) {
System.out.println(String.format("Number of passing records that are polymorphic:\t\t%d (%d%%)", numTrueVariants, 100*numTrueVariants/goodRecords));
hInfo.add(new VCFHeaderLine("ValidationMetrics_PolymorphicPassingRecords", String.format("\"%d (%d%%)\"", numTrueVariants, 100*numTrueVariants/goodRecords)));
}
}
vcfwriter.writeHeader(new VCFHeader(hInfo, SampleUtils.getUniqueSamplesFromRods(getToolkit(), inputNames)));
for ( VariantContext record : records )
vcfwriter.add(record);
}
private VariantContext addVariantInformationToCall(VariantContext vContext) {
// check possible filters
double hwPvalue = hardyWeinbergCalculation(vContext);
double hwScore = Math.abs(QualityUtils.phredScaleErrorRate(hwPvalue));
double noCallProp = (double)vContext.getNoCallCount() / (double)vContext.getNSamples();
double homRefProp = (double)vContext.getHomRefCount() / (double)vContext.getNSamples();
double hetProp = (double)vContext.getHetCount() / (double)vContext.getNSamples();
double homVarProp = (double)vContext.getHomVarCount() / (double)vContext.getNSamples();
boolean isViolation = false;
Set<String> filters = new HashSet<String>();
if ( noCallProp > maxNoCall ) {
filters.add("HighNoCallRate");
numNoCallViolations++;
isViolation = true;
} else if ( hwScore > maxHardy ) {
filters.add("HardyWeinbergViolation");
numHWViolations++;
isViolation = true;
} else if ( homVarProp > maxHomNonref) {
filters.add("TooManyHomVars");
numHomVarViolations++;
isViolation = true;
}
VariantContextBuilder builder = new VariantContextBuilder(vContext).filters(filters);
numRecords++;
// add the info fields
builder.attribute("NoCallPct", String.format("%.1f", 100.0 * noCallProp));
builder.attribute("HomRefPct", String.format("%.1f", 100.0 * homRefProp));
builder.attribute("HomVarPct", String.format("%.1f", 100.0 * homVarProp));
builder.attribute("HetPct", String.format("%.1f", 100.0 * hetProp));
builder.attribute("HW", String.format("%.2f", hwScore));
Collection<Allele> altAlleles = vContext.getAlternateAlleles();
int altAlleleCount = altAlleles.size() == 0 ? 0 : vContext.getCalledChrCount(altAlleles.iterator().next());
if ( !isViolation && altAlleleCount > 0 )
numTrueVariants++;
builder.attribute(VCFConstants.ALLELE_COUNT_KEY, String.format("%d", altAlleleCount));
builder.attribute(VCFConstants.ALLELE_NUMBER_KEY, String.format("%d", vContext.getCalledChrCount()));
return builder.make();
}
private double hardyWeinbergCalculation(VariantContext vc) {
//if ( popFile != null ) {
// throw new StingException("We still need to implement this!");
//} else {
return VariantContextUtils.computeHardyWeinbergPvalue(vc);
//}
}
// TODO -- REWRITE THIS TO WORK WITH VARIANT CONTEXT
/******
private String smartHardy(ReferenceContext ref, VCFRecord rec) {
HashMap<String,ArrayList<Genotype>> genotypesByPopulation = new HashMap<String,ArrayList<Genotype>>(10);
HashMap<String,String> hardyWeinbergByPopulation = new HashMap<String,String>(10);
for ( String population : samplesToPopulation.values() ) {
genotypesByPopulation.put(population,new ArrayList<Genotype>());
}
//for ( String name : sampleNames ) {
// String pop = samplesToPopulation.get(name);
// if ( rec.getGenotype(name) != null ) {
// genotypesByPopulation.get(pop).add(rec.getGenotype(name));
// }
//}
for ( String population : samplesToPopulation.values() ) {
VCFVariationCall v = new VCFVariationCall(ref.getBase(),ref.getLocus(),VCFVariationCall.VARIANT_TYPE.SNP);
v.setGenotypeCalls(genotypesByPopulation.get(population));
hardyWeinbergByPopulation.put(population,HWCalc.annotate(null,ref,null,v));
}
return smartHardyString(hardyWeinbergByPopulation);
}
private String smartHardyString(HashMap<String,String> hwByPop) {
// for now just return the maximum:
int maxH = -100;
for ( String pop : samplesToPopulation.values() ) {
maxH = Integer.parseInt(hwByPop.get(pop)) > maxH ? Integer.parseInt(hwByPop.get(pop)) : maxH;
}
return String.format("%s",maxH);
}
*********/
}
|
923626230431ac0aef4c7abec52b456c376f2e73 | 1,141 | java | Java | projects/batfish/src/main/java/org/batfish/vendor/check_point_management/parsing/parboiled/BooleanExprAstNodeVisitor.java | ton31337/batfish | f8591e0c4578b655632648fb8e26bc814844d05c | [
"Apache-2.0"
] | 763 | 2017-02-21T20:35:50.000Z | 2022-03-29T09:27:14.000Z | projects/batfish/src/main/java/org/batfish/vendor/check_point_management/parsing/parboiled/BooleanExprAstNodeVisitor.java | ton31337/batfish | f8591e0c4578b655632648fb8e26bc814844d05c | [
"Apache-2.0"
] | 7,675 | 2017-01-18T08:04:59.000Z | 2022-03-31T21:29:36.000Z | projects/batfish/src/main/java/org/batfish/vendor/check_point_management/parsing/parboiled/BooleanExprAstNodeVisitor.java | ton31337/batfish | f8591e0c4578b655632648fb8e26bc814844d05c | [
"Apache-2.0"
] | 194 | 2017-05-03T14:58:10.000Z | 2022-03-30T20:56:44.000Z | 30.026316 | 94 | 0.804557 | 997,564 | package org.batfish.vendor.check_point_management.parsing.parboiled;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* A visitor of {@link BooleanExprAstNode} that takes a generic argument and returns a generic
* value.
*/
@ParametersAreNonnullByDefault
public interface BooleanExprAstNodeVisitor<T, U> {
default T visit(BooleanExprAstNode booleanExprAstNode, U arg) {
return booleanExprAstNode.accept(this, arg);
}
T visitConjunctionAstNode(ConjunctionAstNode conjunctionAstNode, U arg);
T visitDisjunctionAstNode(DisjunctionAstNode disjunctionAstNode, U arg);
T visitDportAstNode(DportAstNode dportAstNode, U arg);
T visitEmptyAstNode(EmptyAstNode emptyAstNode, U arg);
T visitErrorAstNode(ErrorAstNode errorAstNode, U arg);
T visitIncomingAstNode(IncomingAstNode incomingAstNode, U arg);
T visitOutgoingAstNode(OutgoingAstNode outgoingAstNode, U arg);
T visitTcpAstNode(TcpAstNode tcpAstNode, U arg);
T visitUdpAstNode(UdpAstNode udpAstNode, U arg);
T visitUhDportAstNode(UhDportAstNode uhDportAstNode, U arg);
T visitUnhandledAstNode(UnhandledAstNode unhandledAstNode, U arg);
}
|
923626506f61ef69e90ef4b1dcd796565d76b61a | 10,468 | java | Java | concordium-sdk/src/test/java/com/concordium/sdk/transactions/TransferWithMemoTransactionTest.java | Concordium/concordium-java-sdk | 4de276479acb99ef1fb5ccea615921acd7ae25a0 | [
"Apache-2.0"
] | 3 | 2021-09-18T07:53:42.000Z | 2022-01-25T02:23:15.000Z | concordium-sdk/src/test/java/com/concordium/sdk/transactions/TransferWithMemoTransactionTest.java | Concordium/concordium-java-sdk | 4de276479acb99ef1fb5ccea615921acd7ae25a0 | [
"Apache-2.0"
] | null | null | null | concordium-sdk/src/test/java/com/concordium/sdk/transactions/TransferWithMemoTransactionTest.java | Concordium/concordium-java-sdk | 4de276479acb99ef1fb5ccea615921acd7ae25a0 | [
"Apache-2.0"
] | null | null | null | 44.842975 | 157 | 0.589845 | 997,565 | package com.concordium.sdk.transactions;
import com.concordium.sdk.crypto.ed25519.ED25519ResultCode;
import com.concordium.sdk.crypto.ed25519.ED25519SecretKey;
import com.concordium.sdk.exceptions.ED25519Exception;
import com.concordium.sdk.exceptions.TransactionCreationException;
import lombok.val;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.*;
public class TransferWithMemoTransactionTest {
@Test
public void testCreateTransferWithMemo() {
try {
val transaction = TransferWithMemoTransaction
.builder()
.memo(Memo.from(new byte[]{1, 2, 3, 4, 5}))
.sender(AccountAddress.from("kgfhvu9qnh3mr6eel97y6fq2hezzol8z"))
.receiver(AccountAddress.from("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(TransactionSigner.from(
SignerEntry.from(Index.from(0), Index.from(0),
ED25519SecretKey.from("7100071c835a0a35e86dccba7ee9d10b89e36d1e596771cdc8ee36a17f7abbf2")),
SignerEntry.from(Index.from(0), Index.from(1),
ED25519SecretKey.from("vqbpgud2ghvjgm1n5hdgjnn5818fzsf2"))
))
.build();
assertEquals("ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b", transaction.getHash().asHex());
assertArrayEquals(TestUtils.EXPECTED_BLOCK_ITEM_TRANSFER_WITH_MEMO_VERSIONED_BYTES, TestUtils.signedByteArrayToUnsigned(transaction.getBytes()));
} catch (TransactionCreationException e) {
fail("Unexpected error: " + e.getMessage());
}
}
@Test
public void testCreateTransferWithMemoTransactionWithoutMemoFails() {
try {
TransferWithMemoTransaction
.builder()
.sender(AccountAddress.from("kgfhvu9qnh3mr6eel97y6fq2hezzol8z"))
.receiver(AccountAddress.from("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Memo cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferWithMemoTransactionWithoutSenderFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.receiver(AccountAddress.from("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Sender cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutReceiverFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("kgfhvu9qnh3mr6eel97y6fq2hezzol8z"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Receiver cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutAmountFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("kgfhvu9qnh3mr6eel97y6fq2hezzol8z"))
.receiver(AccountAddress.from("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Amount cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutNonceFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("kgfhvu9qnh3mr6eel97y6fq2hezzol8z"))
.receiver(AccountAddress.from("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"))
.amount(CCDAmount.fromMicro(17))
.expiry(Expiry.from(123456))
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. AccountNonce cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutExpiryFails() {
try {
AccountAddress sender = AccountAddress.from("kgfhvu9qnh3mr6eel97y6fq2hezzol8z");
AccountAddress receiver = AccountAddress.from("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7");
CCDAmount amount = CCDAmount.fromMicro(17);
AccountNonce accountNonce = AccountNonce.from(78910);
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(sender)
.receiver(receiver)
.amount(amount)
.nonce(accountNonce)
.signer(getValidSigner())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Expiry cannot be null")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithoutSignerShouldFail() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("kgfhvu9qnh3mr6eel97y6fq2hezzol8z"))
.receiver(AccountAddress.from("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
if (!e.getMessage().equals("The creation of the Transaction failed. Signer cannot be null or empty")) {
fail("Unexpected error: " + e);
}
}
}
@Test
public void testCreateTransferTransactionWithInvalidSignerFails() {
try {
TransferWithMemoTransaction
.builder()
.memo(Memo.from("Hello, World!".getBytes(StandardCharsets.UTF_8)))
.sender(AccountAddress.from("kgfhvu9qnh3mr6eel97y6fq2hezzol8z"))
.receiver(AccountAddress.from("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"))
.amount(CCDAmount.fromMicro(17))
.nonce(AccountNonce.from(78910))
.expiry(Expiry.from(123456))
.signer(getSignerWithMalformedSecretKey())
.build();
fail("Expected TransferWithMemo to fail");
} catch (TransactionCreationException e) {
val inner = (ED25519Exception) e.getInner();
if (!inner.getCode().equals(ED25519ResultCode.MALFORMED_SECRET_KEY))
fail("Unexpected error: " + e.getMessage());
}
}
private TransactionSigner getValidSigner() {
ED25519SecretKey firstSecretKey = ED25519SecretKey.from("7100071c835a0a35e86dccba7ee9d10b89e36d1e596771cdc8ee36a17f7abbf2");
ED25519SecretKey secondSecretKey = ED25519SecretKey.from("vqbpgud2ghvjgm1n5hdgjnn5818fzsf2");
return TransactionSigner.from(
SignerEntry.from(Index.from(0), Index.from(0),
firstSecretKey),
SignerEntry.from(Index.from(0), Index.from(1),
secondSecretKey));
}
private TransactionSigner getSignerWithMalformedSecretKey() {
return new TransactionSigner() {
@Override
public TransactionSigner put(Index credentialIndex, Index keyIndex, Signer signer) {
return this;
}
@Override
public TransactionSignature sign(byte[] message) throws ED25519Exception {
throw ED25519Exception.from(ED25519ResultCode.MALFORMED_SECRET_KEY);
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
};
}
}
|
9236265f1037f65ffefdc593b897438e4c4f5bf0 | 1,822 | java | Java | htb/fatty-10.10.10.174/fatty-client/org/springframework/beans/factory/xml/XmlBeanFactory.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | null | null | null | htb/fatty-10.10.10.174/fatty-client/org/springframework/beans/factory/xml/XmlBeanFactory.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | 1 | 2022-03-31T22:44:36.000Z | 2022-03-31T22:44:36.000Z | htb/fatty-10.10.10.174/fatty-client/org/springframework/beans/factory/xml/XmlBeanFactory.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | null | null | null | 20.942529 | 144 | 0.455543 | 997,566 | /* */ package org.springframework.beans.factory.xml;
/* */
/* */ import org.springframework.beans.BeansException;
/* */ import org.springframework.beans.factory.BeanFactory;
/* */ import org.springframework.beans.factory.support.BeanDefinitionRegistry;
/* */ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
/* */ import org.springframework.core.io.Resource;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Deprecated
/* */ public class XmlBeanFactory
/* */ extends DefaultListableBeanFactory
/* */ {
/* 57 */ private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry)this);
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public XmlBeanFactory(Resource resource) throws BeansException {
/* 67 */ this(resource, null);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
/* 78 */ super(parentBeanFactory);
/* 79 */ this.reader.loadBeanDefinitions(resource);
/* */ }
/* */ }
/* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/beans/factory/xml/XmlBeanFactory.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
923626eef0331c5d188202ebdb20f4bbd7539c9a | 2,920 | java | Java | google-ads/src/main/java/com/google/ads/googleads/v2/services/ClickConversionResultOrBuilder.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | 3 | 2020-12-20T18:56:52.000Z | 2021-07-29T12:12:02.000Z | google-ads/src/main/java/com/google/ads/googleads/v2/services/ClickConversionResultOrBuilder.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | null | null | null | google-ads/src/main/java/com/google/ads/googleads/v2/services/ClickConversionResultOrBuilder.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | null | null | null | 31.06383 | 105 | 0.674658 | 997,567 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v2/services/conversion_upload_service.proto
package com.google.ads.googleads.v2.services;
public interface ClickConversionResultOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v2.services.ClickConversionResult)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The Google Click ID (gclid) associated with this conversion.
* </pre>
*
* <code>.google.protobuf.StringValue gclid = 1;</code>
* @return Whether the gclid field is set.
*/
boolean hasGclid();
/**
* <pre>
* The Google Click ID (gclid) associated with this conversion.
* </pre>
*
* <code>.google.protobuf.StringValue gclid = 1;</code>
* @return The gclid.
*/
com.google.protobuf.StringValue getGclid();
/**
* <pre>
* The Google Click ID (gclid) associated with this conversion.
* </pre>
*
* <code>.google.protobuf.StringValue gclid = 1;</code>
*/
com.google.protobuf.StringValueOrBuilder getGclidOrBuilder();
/**
* <pre>
* Resource name of the conversion action associated with this conversion.
* </pre>
*
* <code>.google.protobuf.StringValue conversion_action = 2;</code>
* @return Whether the conversionAction field is set.
*/
boolean hasConversionAction();
/**
* <pre>
* Resource name of the conversion action associated with this conversion.
* </pre>
*
* <code>.google.protobuf.StringValue conversion_action = 2;</code>
* @return The conversionAction.
*/
com.google.protobuf.StringValue getConversionAction();
/**
* <pre>
* Resource name of the conversion action associated with this conversion.
* </pre>
*
* <code>.google.protobuf.StringValue conversion_action = 2;</code>
*/
com.google.protobuf.StringValueOrBuilder getConversionActionOrBuilder();
/**
* <pre>
* The date time at which the conversion occurred. The format is
* "yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g. “2019-01-01 12:32:45-08:00”.
* </pre>
*
* <code>.google.protobuf.StringValue conversion_date_time = 3;</code>
* @return Whether the conversionDateTime field is set.
*/
boolean hasConversionDateTime();
/**
* <pre>
* The date time at which the conversion occurred. The format is
* "yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g. “2019-01-01 12:32:45-08:00”.
* </pre>
*
* <code>.google.protobuf.StringValue conversion_date_time = 3;</code>
* @return The conversionDateTime.
*/
com.google.protobuf.StringValue getConversionDateTime();
/**
* <pre>
* The date time at which the conversion occurred. The format is
* "yyyy-mm-dd hh:mm:ss+|-hh:mm", e.g. “2019-01-01 12:32:45-08:00”.
* </pre>
*
* <code>.google.protobuf.StringValue conversion_date_time = 3;</code>
*/
com.google.protobuf.StringValueOrBuilder getConversionDateTimeOrBuilder();
}
|
923626f5f76e98e03e7fc851238fab63e60c668b | 986 | java | Java | core/src/main/java/laurencewarne/secondspace/common/system/PhysicsSystem.java | LaurenceWarne/second-space | c52dbde2ca2f4c8f81d04340753ff05df86478e9 | [
"MIT"
] | 2 | 2019-07-12T19:09:17.000Z | 2019-08-18T10:12:47.000Z | core/src/main/java/laurencewarne/secondspace/common/system/PhysicsSystem.java | LaurenceWarne/second-space | c52dbde2ca2f4c8f81d04340753ff05df86478e9 | [
"MIT"
] | null | null | null | core/src/main/java/laurencewarne/secondspace/common/system/PhysicsSystem.java | LaurenceWarne/second-space | c52dbde2ca2f4c8f81d04340753ff05df86478e9 | [
"MIT"
] | null | null | null | 24.04878 | 94 | 0.735294 | 997,568 | package laurencewarne.secondspace.common.system;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.annotations.Wire;
import com.artemis.systems.IntervalIteratingSystem;
import com.badlogic.gdx.physics.box2d.World;
import laurencewarne.secondspace.common.component.Physics;
/**
* Responsible for upating the physics of the world. Essentially just updates the box2D world.
*/
public class PhysicsSystem extends IntervalIteratingSystem {
// odb injects dependencies automatically
private ComponentMapper<Physics> mPhysics;
@Wire
private World box2DWorld;
public PhysicsSystem(float interval) {
super(Aspect.all(Physics.class), interval);
}
@Override
public void begin() {
box2DWorld.step(1/40f, 6, 2);
}
@Override
public void removed(int id) {
// Remove from box2d world
box2DWorld.destroyBody(mPhysics.get(id).getBody());
}
@Override
protected void process(int arg0) {
}
}
|
9236275274b5aefb01ebaede1ee4507024a0bfff | 2,768 | java | Java | jel-server/src/main/java/se/liquidbytes/jel/system/adapter/AbstractAdapter.java | trycoon/JEL | 8da266dd3e4324c123411186f9abe9b423c73cdd | [
"Apache-2.0"
] | 1 | 2018-04-14T08:10:26.000Z | 2018-04-14T08:10:26.000Z | jel-server/src/main/java/se/liquidbytes/jel/system/adapter/AbstractAdapter.java | trycoon/JEL | 8da266dd3e4324c123411186f9abe9b423c73cdd | [
"Apache-2.0"
] | null | null | null | jel-server/src/main/java/se/liquidbytes/jel/system/adapter/AbstractAdapter.java | trycoon/JEL | 8da266dd3e4324c123411186f9abe9b423c73cdd | [
"Apache-2.0"
] | null | null | null | 26.873786 | 154 | 0.697977 | 997,569 | /*
* Copyright 2015 Henrik Östman.
*
* 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 se.liquidbytes.jel.system.adapter;
import io.vertx.core.AbstractVerticle;
import se.liquidbytes.jel.system.plugin.Plugin;
/**
* Base class extended by all adapters
*
* @author Henrik Östman
*/
public abstract class AbstractAdapter extends AbstractVerticle implements Plugin {
/**
* Id for adapter.
*/
private String id;
public AbstractAdapter() {
}
/**
* Get id for adapter.
*
* @return adapter id
*/
public String getId() {
return id;
}
/**
* Set id for adapter.
*
* @param id id to assign adapter.
*/
protected void setId(String id) {
this.id = id;
}
/**
* Get a more informative description of the adapter, Optional.
*
* @return Long description
*/
public String getDescription() {
return "";
}
/**
* If adapter is capable of automatically detecting connected devices. If not, then devices has to manually be bound and unbound to adapter.
*
* @return Has support for autodetection
*/
public abstract boolean isDevicesAutodetected();
/**
* Method will be invoked when plugin is installed into the system.
*/
@Override
public void pluginInstall() {
// By default we do nothing, but derived classes may use this during installation for setting up needed files and directories.
}
/**
* Method will be invoked when plugin is uninstalled from the system.
*/
@Override
public void pluginUninstall() {
// By default we do nothing, but derived classes may use this during uninstallation for removing previous installed and created files and directories.
}
/**
* Method will be invoked when plugin is started by plugin manager.
*/
@Override
public void pluginStart() {
// By default we do nothing, but derived classes may use this if something need to be run at plugin startup and before this verticle has started.
}
/**
* Method will be invoked when plugin is stopped by plugin manager.
*/
@Override
public void pluginStop() {
// By default we do nothing, but derived classes may use this if something need to be run at plugin shutdown and after this verticle has been stopped.
}
}
|
9236282a17faba556c9998a0e12b54236f3e2179 | 1,617 | java | Java | modules/tasks/tasks/src/main/java/org/motechproject/tasks/dto/TaskEventInformationDto.java | pgesek/motech | 92d3969ca00ae71d8c545652655285987074f632 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 17 | 2015-08-11T07:39:39.000Z | 2021-08-30T04:24:51.000Z | modules/tasks/tasks/src/main/java/org/motechproject/tasks/dto/TaskEventInformationDto.java | pgesek/motech | 92d3969ca00ae71d8c545652655285987074f632 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 474 | 2015-08-11T08:15:03.000Z | 2018-03-29T16:11:11.000Z | modules/tasks/tasks/src/main/java/org/motechproject/tasks/dto/TaskEventInformationDto.java | pgesek/motech | 92d3969ca00ae71d8c545652655285987074f632 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 71 | 2015-09-03T15:09:11.000Z | 2018-07-24T04:34:30.000Z | 23.434783 | 146 | 0.658009 | 997,570 | package org.motechproject.tasks.dto;
public abstract class TaskEventInformationDto {
private String name;
private String displayName;
private String channelName;
private String moduleName;
private String moduleVersion;
private String subject;
public TaskEventInformationDto(String name, String displayName, String channelName, String moduleName, String moduleVersion, String subject) {
this.name = name;
this.displayName = displayName;
this.channelName = channelName;
this.moduleName = moduleName;
this.moduleVersion = moduleVersion;
this.subject = subject;
}
public String getName() {
return name;
}
public String getDisplayName() {
return displayName;
}
public String getChannelName() {
return channelName;
}
public String getModuleName() {
return moduleName;
}
public String getModuleVersion() {
return moduleVersion;
}
public String getSubject() {
return subject;
}
public void setName(String name) {
this.name = name;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public void setModuleVersion(String moduleVersion) {
this.moduleVersion = moduleVersion;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
|
9236287cc528ea868e65a033bb4e2620863b13de | 22,653 | java | Java | backend/de.metas.printing/de.metas.printing.base/src/main/java-gen/de/metas/printing/model/I_C_Order_MFGWarehouse_Report_PrintInfo_v.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.printing/de.metas.printing.base/src/main/java-gen/de/metas/printing/model/I_C_Order_MFGWarehouse_Report_PrintInfo_v.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.printing/de.metas.printing.base/src/main/java-gen/de/metas/printing/model/I_C_Order_MFGWarehouse_Report_PrintInfo_v.java | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z | 35.450704 | 457 | 0.760606 | 997,571 | package de.metas.printing.model;
/** Generated Interface for C_Order_MFGWarehouse_Report_PrintInfo_v
* @author metasfresh (generated)
*/
@SuppressWarnings("javadoc")
public interface I_C_Order_MFGWarehouse_Report_PrintInfo_v
{
/** TableName=C_Order_MFGWarehouse_Report_PrintInfo_v */
public static final String Table_Name = "C_Order_MFGWarehouse_Report_PrintInfo_v";
/** AD_Table_ID=541001 */
// public static final int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name);
/**
* Set Archiv.
* Archiv für Belege und Berichte
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setAD_Archive_ID (int AD_Archive_ID);
/**
* Get Archiv.
* Archiv für Belege und Berichte
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getAD_Archive_ID();
public org.compiere.model.I_AD_Archive getAD_Archive();
public void setAD_Archive(org.compiere.model.I_AD_Archive AD_Archive);
/** Column definition for AD_Archive_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, org.compiere.model.I_AD_Archive> COLUMN_AD_Archive_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, org.compiere.model.I_AD_Archive>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "AD_Archive_ID", org.compiere.model.I_AD_Archive.class);
/** Column name AD_Archive_ID */
public static final String COLUMNNAME_AD_Archive_ID = "AD_Archive_ID";
/**
* Get Client.
* Client/Tenant for this installation.
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getAD_Client_ID();
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/**
* Set Organisation.
* Organisational entity within client
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setAD_Org_ID (int AD_Org_ID);
/**
* Get Organisation.
* Organisational entity within client
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getAD_Org_ID();
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/**
* Set Hardware-Drucker.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setAD_PrinterHW_ID (int AD_PrinterHW_ID);
/**
* Get Hardware-Drucker.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getAD_PrinterHW_ID();
public de.metas.printing.model.I_AD_PrinterHW getAD_PrinterHW();
public void setAD_PrinterHW(de.metas.printing.model.I_AD_PrinterHW AD_PrinterHW);
/** Column definition for AD_PrinterHW_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_AD_PrinterHW> COLUMN_AD_PrinterHW_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_AD_PrinterHW>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "AD_PrinterHW_ID", de.metas.printing.model.I_AD_PrinterHW.class);
/** Column name AD_PrinterHW_ID */
public static final String COLUMNNAME_AD_PrinterHW_ID = "AD_PrinterHW_ID";
/**
* Set Hardware-Schacht.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setAD_PrinterHW_MediaTray_ID (int AD_PrinterHW_MediaTray_ID);
/**
* Get Hardware-Schacht.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getAD_PrinterHW_MediaTray_ID();
public de.metas.printing.model.I_AD_PrinterHW_MediaTray getAD_PrinterHW_MediaTray();
public void setAD_PrinterHW_MediaTray(de.metas.printing.model.I_AD_PrinterHW_MediaTray AD_PrinterHW_MediaTray);
/** Column definition for AD_PrinterHW_MediaTray_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_AD_PrinterHW_MediaTray> COLUMN_AD_PrinterHW_MediaTray_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_AD_PrinterHW_MediaTray>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "AD_PrinterHW_MediaTray_ID", de.metas.printing.model.I_AD_PrinterHW_MediaTray.class);
/** Column name AD_PrinterHW_MediaTray_ID */
public static final String COLUMNNAME_AD_PrinterHW_MediaTray_ID = "AD_PrinterHW_MediaTray_ID";
/**
* Set ad_session_printpackage_id.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setAD_Session_Printpackage_ID (int AD_Session_Printpackage_ID);
/**
* Get ad_session_printpackage_id.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getAD_Session_Printpackage_ID();
public org.compiere.model.I_AD_Session getAD_Session_Printpackage();
public void setAD_Session_Printpackage(org.compiere.model.I_AD_Session AD_Session_Printpackage);
/** Column definition for AD_Session_Printpackage_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, org.compiere.model.I_AD_Session> COLUMN_AD_Session_Printpackage_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, org.compiere.model.I_AD_Session>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "AD_Session_Printpackage_ID", org.compiere.model.I_AD_Session.class);
/** Column name AD_Session_Printpackage_ID */
public static final String COLUMNNAME_AD_Session_Printpackage_ID = "AD_Session_Printpackage_ID";
/**
* Set Verantwortlicher Benutzer.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setAD_User_Responsible_ID (int AD_User_Responsible_ID);
/**
* Get Verantwortlicher Benutzer.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getAD_User_Responsible_ID();
/** Column name AD_User_Responsible_ID */
public static final String COLUMNNAME_AD_User_Responsible_ID = "AD_User_Responsible_ID";
/**
* Set Sales order.
* Order
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setC_Order_ID (int C_Order_ID);
/**
* Get Sales order.
* Order
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getC_Order_ID();
public org.compiere.model.I_C_Order getC_Order();
public void setC_Order(org.compiere.model.I_C_Order C_Order);
/** Column definition for C_Order_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, org.compiere.model.I_C_Order> COLUMN_C_Order_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, org.compiere.model.I_C_Order>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "C_Order_ID", org.compiere.model.I_C_Order.class);
/** Column name C_Order_ID */
public static final String COLUMNNAME_C_Order_ID = "C_Order_ID";
/**
* Set Order / MFG Warehouse report.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setC_Order_MFGWarehouse_Report_ID (int C_Order_MFGWarehouse_Report_ID);
/**
* Get Order / MFG Warehouse report.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getC_Order_MFGWarehouse_Report_ID();
/** Column definition for C_Order_MFGWarehouse_Report_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_C_Order_MFGWarehouse_Report_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "C_Order_MFGWarehouse_Report_ID", null);
/** Column name C_Order_MFGWarehouse_Report_ID */
public static final String COLUMNNAME_C_Order_MFGWarehouse_Report_ID = "C_Order_MFGWarehouse_Report_ID";
/**
* Set Druck-Warteschlangendatensatz.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setC_Printing_Queue_ID (int C_Printing_Queue_ID);
/**
* Get Druck-Warteschlangendatensatz.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getC_Printing_Queue_ID();
public de.metas.printing.model.I_C_Printing_Queue getC_Printing_Queue();
public void setC_Printing_Queue(de.metas.printing.model.I_C_Printing_Queue C_Printing_Queue);
/** Column definition for C_Printing_Queue_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_C_Printing_Queue> COLUMN_C_Printing_Queue_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_C_Printing_Queue>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "C_Printing_Queue_ID", de.metas.printing.model.I_C_Printing_Queue.class);
/** Column name C_Printing_Queue_ID */
public static final String COLUMNNAME_C_Printing_Queue_ID = "C_Printing_Queue_ID";
/**
* Set Druck-Job Anweisung.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setC_Print_Job_Instructions_ID (int C_Print_Job_Instructions_ID);
/**
* Get Druck-Job Anweisung.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getC_Print_Job_Instructions_ID();
public de.metas.printing.model.I_C_Print_Job_Instructions getC_Print_Job_Instructions();
public void setC_Print_Job_Instructions(de.metas.printing.model.I_C_Print_Job_Instructions C_Print_Job_Instructions);
/** Column definition for C_Print_Job_Instructions_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_C_Print_Job_Instructions> COLUMN_C_Print_Job_Instructions_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_C_Print_Job_Instructions>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "C_Print_Job_Instructions_ID", de.metas.printing.model.I_C_Print_Job_Instructions.class);
/** Column name C_Print_Job_Instructions_ID */
public static final String COLUMNNAME_C_Print_Job_Instructions_ID = "C_Print_Job_Instructions_ID";
/**
* Set Druckpaket.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setC_Print_Package_ID (int C_Print_Package_ID);
/**
* Get Druckpaket.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getC_Print_Package_ID();
public de.metas.printing.model.I_C_Print_Package getC_Print_Package();
public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package);
/** Column definition for C_Print_Package_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_C_Print_Package> COLUMN_C_Print_Package_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_C_Print_Package>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "C_Print_Package_ID", de.metas.printing.model.I_C_Print_Package.class);
/** Column name C_Print_Package_ID */
public static final String COLUMNNAME_C_Print_Package_ID = "C_Print_Package_ID";
/**
* Set Druckpaket-Info.
* Contains details for the print package, like printer, tray, pages from/to and print service name.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setC_Print_PackageInfo_ID (int C_Print_PackageInfo_ID);
/**
* Get Druckpaket-Info.
* Contains details for the print package, like printer, tray, pages from/to and print service name.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getC_Print_PackageInfo_ID();
public de.metas.printing.model.I_C_Print_PackageInfo getC_Print_PackageInfo();
public void setC_Print_PackageInfo(de.metas.printing.model.I_C_Print_PackageInfo C_Print_PackageInfo);
/** Column definition for C_Print_PackageInfo_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_C_Print_PackageInfo> COLUMN_C_Print_PackageInfo_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, de.metas.printing.model.I_C_Print_PackageInfo>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "C_Print_PackageInfo_ID", de.metas.printing.model.I_C_Print_PackageInfo.class);
/** Column name C_Print_PackageInfo_ID */
public static final String COLUMNNAME_C_Print_PackageInfo_ID = "C_Print_PackageInfo_ID";
/**
* Set Element Queue.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setC_Queue_Element_ID (int C_Queue_Element_ID);
/**
* Get Element Queue.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getC_Queue_Element_ID();
/** Column definition for C_Queue_Element_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_C_Queue_Element_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "C_Queue_Element_ID", null);
/** Column name C_Queue_Element_ID */
public static final String COLUMNNAME_C_Queue_Element_ID = "C_Queue_Element_ID";
/**
* Set WorkPackage Queue.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setC_Queue_WorkPackage_ID (int C_Queue_WorkPackage_ID);
/**
* Get WorkPackage Queue.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getC_Queue_WorkPackage_ID();
/** Column definition for C_Queue_WorkPackage_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_C_Queue_WorkPackage_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "C_Queue_WorkPackage_ID", null);
/** Column name C_Queue_WorkPackage_ID */
public static final String COLUMNNAME_C_Queue_WorkPackage_ID = "C_Queue_WorkPackage_ID";
/**
* Get Created.
* Date this record was created
*
* <br>Type: DateTime
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.sql.Timestamp getCreated();
/** Column definition for Created */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_Created = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "Created", null);
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/**
* Get Created By.
* User who created this records
*
* <br>Type: Table
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getCreatedBy();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/**
* Set Warehouse.
* Storage Warehouse and Service Point
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setM_Warehouse_ID (int M_Warehouse_ID);
/**
* Get Warehouse.
* Storage Warehouse and Service Point
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getM_Warehouse_ID();
/** Column name M_Warehouse_ID */
public static final String COLUMNNAME_M_Warehouse_ID = "M_Warehouse_ID";
/**
* Set Print service name.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setPrintServiceName (java.lang.String PrintServiceName);
/**
* Get Print service name.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.lang.String getPrintServiceName();
/** Column definition for PrintServiceName */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_PrintServiceName = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "PrintServiceName", null);
/** Column name PrintServiceName */
public static final String COLUMNNAME_PrintServiceName = "PrintServiceName";
/**
* Set printservicetray.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setPrintServiceTray (java.lang.String PrintServiceTray);
/**
* Get printservicetray.
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.lang.String getPrintServiceTray();
/** Column definition for PrintServiceTray */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_PrintServiceTray = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "PrintServiceTray", null);
/** Column name PrintServiceTray */
public static final String COLUMNNAME_PrintServiceTray = "PrintServiceTray";
/**
* Set Ressource.
* Ressource
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setS_Resource_ID (int S_Resource_ID);
/**
* Get Ressource.
* Ressource
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getS_Resource_ID();
public org.compiere.model.I_S_Resource getS_Resource();
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource);
/** Column definition for S_Resource_ID */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, org.compiere.model.I_S_Resource> COLUMN_S_Resource_ID = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, org.compiere.model.I_S_Resource>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "S_Resource_ID", org.compiere.model.I_S_Resource.class);
/** Column name S_Resource_ID */
public static final String COLUMNNAME_S_Resource_ID = "S_Resource_ID";
/**
* Set status_print_job_instructions.
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions);
/**
* Get status_print_job_instructions.
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isStatus_Print_Job_Instructions();
/** Column definition for Status_Print_Job_Instructions */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_Status_Print_Job_Instructions = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "Status_Print_Job_Instructions", null);
/** Column name Status_Print_Job_Instructions */
public static final String COLUMNNAME_Status_Print_Job_Instructions = "Status_Print_Job_Instructions";
/**
* Set Schachtnummer.
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setTrayNumber (int TrayNumber);
/**
* Get Schachtnummer.
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getTrayNumber();
/** Column definition for TrayNumber */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_TrayNumber = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "TrayNumber", null);
/** Column name TrayNumber */
public static final String COLUMNNAME_TrayNumber = "TrayNumber";
/**
* Get Updated.
* Date this record was updated
*
* <br>Type: DateTime
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public java.sql.Timestamp getUpdated();
/** Column definition for Updated */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_Updated = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "Updated", null);
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/**
* Get Updated By.
* User who updated this records
*
* <br>Type: Table
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getUpdatedBy();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/**
* Set wp_iserror.
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setWP_IsError (boolean WP_IsError);
/**
* Get wp_iserror.
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isWP_IsError();
/** Column definition for WP_IsError */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_WP_IsError = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "WP_IsError", null);
/** Column name WP_IsError */
public static final String COLUMNNAME_WP_IsError = "WP_IsError";
/**
* Set wp_isprocessed.
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setWP_IsProcessed (boolean WP_IsProcessed);
/**
* Get wp_isprocessed.
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isWP_IsProcessed();
/** Column definition for WP_IsProcessed */
public static final org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object> COLUMN_WP_IsProcessed = new org.adempiere.model.ModelColumn<I_C_Order_MFGWarehouse_Report_PrintInfo_v, Object>(I_C_Order_MFGWarehouse_Report_PrintInfo_v.class, "WP_IsProcessed", null);
/** Column name WP_IsProcessed */
public static final String COLUMNNAME_WP_IsProcessed = "WP_IsProcessed";
}
|
9236289b2ff043ed604d174abc743e3246f03186 | 4,091 | java | Java | instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/servlet/AppServerBridge.java | lmolkova/opentelemetry-java-instrumentation | 2f47e8a3d3603dfb30811621edadc0ef648e6010 | [
"MIT",
"ECL-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 683 | 2020-05-30T19:20:06.000Z | 2022-03-30T22:08:23.000Z | instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/servlet/AppServerBridge.java | lmolkova/opentelemetry-java-instrumentation | 2f47e8a3d3603dfb30811621edadc0ef648e6010 | [
"MIT",
"ECL-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 2,736 | 2020-05-30T20:21:17.000Z | 2022-03-31T18:26:35.000Z | instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/servlet/AppServerBridge.java | lmolkova/opentelemetry-java-instrumentation | 2f47e8a3d3603dfb30811621edadc0ef648e6010 | [
"MIT",
"ECL-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 350 | 2020-05-30T09:34:34.000Z | 2022-03-31T14:34:28.000Z | 36.20354 | 100 | 0.746028 | 997,572 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.api.servlet;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.ContextKey;
import javax.annotation.Nullable;
/**
* Helper container for Context attributes for transferring certain information between servlet
* integration and app-server server handler integrations.
*/
public class AppServerBridge {
private static final ContextKey<AppServerBridge> CONTEXT_KEY =
ContextKey.named("opentelemetry-servlet-app-server-bridge");
/**
* Attach AppServerBridge to context.
*
* @param ctx server context
* @return new context with AppServerBridge attached.
*/
public static Context init(Context ctx) {
return init(ctx, /* shouldRecordException= */ true);
}
/**
* Attach AppServerBridge to context.
*
* @param ctx server context
* @param shouldRecordException whether servlet integration should record exception thrown during
* servlet invocation in server span. Use <code>false</code> on servers where exceptions
* thrown during servlet invocation are propagated to the method where server span is closed
* and can be added to server span there and <code>true</code> otherwise.
* @return new context with AppServerBridge attached.
*/
public static Context init(Context ctx, boolean shouldRecordException) {
return ctx.with(AppServerBridge.CONTEXT_KEY, new AppServerBridge(shouldRecordException));
}
private final boolean servletShouldRecordException;
private Throwable exception;
private AppServerBridge(boolean shouldRecordException) {
servletShouldRecordException = shouldRecordException;
}
/**
* Returns true, if servlet integration should record exception thrown during servlet invocation
* in server span. This method should return <code>false</code> on servers where exceptions thrown
* during servlet invocation are propagated to the method where server span is closed and can be
* added to server span there and <code>true</code> otherwise.
*
* @param context server context
* @return <code>true</code>, if servlet integration should record exception thrown during servlet
* invocation in server span, or <code>false</code> otherwise.
*/
public static boolean shouldRecordException(Context context) {
AppServerBridge appServerBridge = context.get(AppServerBridge.CONTEXT_KEY);
if (appServerBridge != null) {
return appServerBridge.servletShouldRecordException;
}
return true;
}
/**
* Record exception that happened during servlet invocation so that app server instrumentation can
* add it to server span.
*
* @param context server context
* @param exception exception that happened during servlet invocation
*/
public static void recordException(Context context, Throwable exception) {
AppServerBridge appServerBridge = context.get(AppServerBridge.CONTEXT_KEY);
if (appServerBridge != null && appServerBridge.servletShouldRecordException) {
appServerBridge.exception = exception;
}
}
/**
* Get exception that happened during servlet invocation.
*
* @param context server context
* @return exception that happened during servlet invocation
*/
@Nullable
public static Throwable getException(Context context) {
AppServerBridge appServerBridge = context.get(AppServerBridge.CONTEXT_KEY);
if (appServerBridge != null) {
return appServerBridge.exception;
}
return null;
}
/**
* Class used as key in CallDepthThreadLocalMap for counting servlet invocation depth in
* Servlet3Advice and Servlet2Advice. We can not use helper classes like Servlet3Advice and
* Servlet2Advice for determining call depth of server invocation because they can be injected
* into multiple class loaders.
*
* @return class used as a key in CallDepthThreadLocalMap for counting servlet invocation depth
*/
public static Class<?> getCallDepthKey() {
class Key {}
return Key.class;
}
}
|
92362a5aadc40a2440c1ab48c2ea6cf1a495b9dd | 8,013 | java | Java | qe/ql/src/java/org/apache/hadoop/hive/ql/parse/ParseContext.java | tonycody/tencent-tdw | 92357724319bbc24f3f0d5563d68d299d237a17f | [
"Apache-1.1"
] | 3 | 2019-11-08T12:47:19.000Z | 2021-06-10T19:46:01.000Z | qe/ql/src/java/org/apache/hadoop/hive/ql/parse/ParseContext.java | tonycody/tencent-tdw | 92357724319bbc24f3f0d5563d68d299d237a17f | [
"Apache-1.1"
] | null | null | null | qe/ql/src/java/org/apache/hadoop/hive/ql/parse/ParseContext.java | tonycody/tencent-tdw | 92357724319bbc24f3f0d5563d68d299d237a17f | [
"Apache-1.1"
] | 8 | 2020-03-12T13:42:59.000Z | 2021-05-27T06:34:33.000Z | 29.788104 | 90 | 0.745913 | 997,573 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.parse;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.hive.ql.exec.JoinOperator;
import org.apache.hadoop.hive.ql.exec.MapJoinOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.plan.exprNodeDesc;
import org.apache.hadoop.hive.ql.plan.loadFileDesc;
import org.apache.hadoop.hive.ql.plan.loadTableDesc;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.metadata.TablePartition;
import org.apache.hadoop.hive.ql.optimizer.unionproc.UnionProcContext;
public class ParseContext {
private QB qb;
private ASTNode ast;
private HashMap<String, ASTPartitionPruner> aliasToPruner;
private HashMap<TableScanOperator, exprNodeDesc> opToPartPruner;
private HashMap<String, SamplePruner> aliasToSamplePruner;
private LinkedHashMap<String, Operator<? extends Serializable>> topOps;
private HashMap<String, Operator<? extends Serializable>> topSelOps;
private LinkedHashMap<Operator<? extends Serializable>, OpParseContext> opParseCtx;
private Map<JoinOperator, QBJoinTree> joinContext;
private Map<MapJoinOperator, QBJoinTree> mapJoinContext;
private HashMap<TableScanOperator, TablePartition> topToTable;
private List<loadTableDesc> loadTableWork;
private List<loadFileDesc> loadFileWork;
private Context ctx;
private HiveConf conf;
private HashMap<String, String> idToTableNameMap;
private int destTableId;
private UnionProcContext uCtx;
private List<MapJoinOperator> listMapJoinOpsNoReducer;
private boolean hasNonPartCols;
public ParseContext() {
}
public ParseContext(
HiveConf conf,
QB qb,
ASTNode ast,
HashMap<String, ASTPartitionPruner> aliasToPruner,
HashMap<TableScanOperator, exprNodeDesc> opToPartPruner,
HashMap<String, SamplePruner> aliasToSamplePruner,
LinkedHashMap<String, Operator<? extends Serializable>> topOps,
HashMap<String, Operator<? extends Serializable>> topSelOps,
LinkedHashMap<Operator<? extends Serializable>, OpParseContext> opParseCtx,
Map<JoinOperator, QBJoinTree> joinContext,
HashMap<TableScanOperator, TablePartition> topToTable,
List<loadTableDesc> loadTableWork, List<loadFileDesc> loadFileWork,
Context ctx, HashMap<String, String> idToTableNameMap, int destTableId,
UnionProcContext uCtx, List<MapJoinOperator> listMapJoinOpsNoReducer) {
this.conf = conf;
this.qb = qb;
this.ast = ast;
this.aliasToPruner = aliasToPruner;
this.opToPartPruner = opToPartPruner;
this.aliasToSamplePruner = aliasToSamplePruner;
this.joinContext = joinContext;
this.topToTable = topToTable;
this.loadFileWork = loadFileWork;
this.loadTableWork = loadTableWork;
this.opParseCtx = opParseCtx;
this.topOps = topOps;
this.topSelOps = topSelOps;
this.ctx = ctx;
this.idToTableNameMap = idToTableNameMap;
this.destTableId = destTableId;
this.uCtx = uCtx;
this.listMapJoinOpsNoReducer = listMapJoinOpsNoReducer;
this.hasNonPartCols = false;
}
public QB getQB() {
return qb;
}
public void setQB(QB qb) {
this.qb = qb;
}
public Context getContext() {
return ctx;
}
public void setContext(Context ctx) {
this.ctx = ctx;
}
public HiveConf getConf() {
return conf;
}
public void setConf(HiveConf conf) {
this.conf = conf;
}
public ASTNode getParseTree() {
return ast;
}
public void setParseTree(ASTNode ast) {
this.ast = ast;
}
public HashMap<String, ASTPartitionPruner> getAliasToPruner() {
return aliasToPruner;
}
public void setAliasToPruner(HashMap<String, ASTPartitionPruner> aliasToPruner) {
this.aliasToPruner = aliasToPruner;
}
public HashMap<TableScanOperator, exprNodeDesc> getOpToPartPruner() {
return opToPartPruner;
}
public void setOpToPartPruner(
HashMap<TableScanOperator, exprNodeDesc> opToPartPruner) {
this.opToPartPruner = opToPartPruner;
}
public HashMap<TableScanOperator, TablePartition> getTopToTable() {
return topToTable;
}
public void setTopToTable(
HashMap<TableScanOperator, TablePartition> topToTable) {
this.topToTable = topToTable;
}
public HashMap<String, SamplePruner> getAliasToSamplePruner() {
return aliasToSamplePruner;
}
public void setAliasToSamplePruner(
HashMap<String, SamplePruner> aliasToSamplePruner) {
this.aliasToSamplePruner = aliasToSamplePruner;
}
public LinkedHashMap<String, Operator<? extends Serializable>> getTopOps() {
return topOps;
}
public void setTopOps(
LinkedHashMap<String, Operator<? extends Serializable>> topOps) {
this.topOps = topOps;
}
public HashMap<String, Operator<? extends Serializable>> getTopSelOps() {
return topSelOps;
}
public void setTopSelOps(
HashMap<String, Operator<? extends Serializable>> topSelOps) {
this.topSelOps = topSelOps;
}
public LinkedHashMap<Operator<? extends Serializable>, OpParseContext> getOpParseCtx() {
return opParseCtx;
}
public void setOpParseCtx(
LinkedHashMap<Operator<? extends Serializable>, OpParseContext> opParseCtx) {
this.opParseCtx = opParseCtx;
}
public List<loadTableDesc> getLoadTableWork() {
return loadTableWork;
}
public void setLoadTableWork(List<loadTableDesc> loadTableWork) {
this.loadTableWork = loadTableWork;
}
public List<loadFileDesc> getLoadFileWork() {
return loadFileWork;
}
public void setLoadFileWork(List<loadFileDesc> loadFileWork) {
this.loadFileWork = loadFileWork;
}
public HashMap<String, String> getIdToTableNameMap() {
return idToTableNameMap;
}
public void setIdToTableNameMap(HashMap<String, String> idToTableNameMap) {
this.idToTableNameMap = idToTableNameMap;
}
public int getDestTableId() {
return destTableId;
}
public void setDestTableId(int destTableId) {
this.destTableId = destTableId;
}
public UnionProcContext getUCtx() {
return uCtx;
}
public void setUCtx(UnionProcContext uCtx) {
this.uCtx = uCtx;
}
public Map<JoinOperator, QBJoinTree> getJoinContext() {
return joinContext;
}
public void setJoinContext(Map<JoinOperator, QBJoinTree> joinContext) {
this.joinContext = joinContext;
}
public List<MapJoinOperator> getListMapJoinOpsNoReducer() {
return listMapJoinOpsNoReducer;
}
public void setListMapJoinOpsNoReducer(
List<MapJoinOperator> listMapJoinOpsNoReducer) {
this.listMapJoinOpsNoReducer = listMapJoinOpsNoReducer;
}
public void setHasNonPartCols(boolean val) {
this.hasNonPartCols = val;
}
public boolean getHasNonPartCols() {
return this.hasNonPartCols;
}
public Map<MapJoinOperator, QBJoinTree> getMapJoinContext() {
return mapJoinContext;
}
public void setMapJoinContext(Map<MapJoinOperator, QBJoinTree> mapJoinContext) {
this.mapJoinContext = mapJoinContext;
}
}
|
92362a8a13d2908a599e111fcbb27c55f2873f50 | 1,289 | java | Java | src/main/java/com/mingcai/edu/modules/oa/service/wx/OaWxUsersService.java | KevinXYJ/mingcai-oa | 5ff7f2e69d2b5bac803000bc3965bbbf3692088c | [
"Apache-2.0"
] | 1 | 2019-05-09T00:12:50.000Z | 2019-05-09T00:12:50.000Z | src/main/java/com/mingcai/edu/modules/oa/service/wx/OaWxUsersService.java | KevinXYJ/mingcai-oa | 5ff7f2e69d2b5bac803000bc3965bbbf3692088c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mingcai/edu/modules/oa/service/wx/OaWxUsersService.java | KevinXYJ/mingcai-oa | 5ff7f2e69d2b5bac803000bc3965bbbf3692088c | [
"Apache-2.0"
] | 1 | 2020-02-18T06:58:14.000Z | 2020-02-18T06:58:14.000Z | 26.306122 | 108 | 0.762607 | 997,574 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.mingcai.edu.modules.oa.service.wx;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mingcai.edu.common.persistence.Page;
import com.mingcai.edu.common.service.CrudService;
import com.mingcai.edu.modules.oa.entity.wx.OaWxUsers;
import com.mingcai.edu.modules.oa.dao.wx.OaWxUsersDao;
/**
* 微信用户Service
* @author kun
* @version 2019-03-05
*/
@Service
@Transactional(readOnly = true)
public class OaWxUsersService extends CrudService<OaWxUsersDao, OaWxUsers> {
public OaWxUsers get(String id) {
return super.get(id);
}
public List<OaWxUsers> findList(OaWxUsers oaWxUsers) {
return super.findList(oaWxUsers);
}
public List<OaWxUsers> findListAll(OaWxUsers oaWxUsers) {
return dao.findAllList(oaWxUsers);
}
public Page<OaWxUsers> findPage(Page<OaWxUsers> page, OaWxUsers oaWxUsers) {
return super.findPage(page, oaWxUsers);
}
@Transactional(readOnly = false)
public void save(OaWxUsers oaWxUsers) {
super.save(oaWxUsers);
}
@Transactional(readOnly = false)
public void delete(OaWxUsers oaWxUsers) {
super.delete(oaWxUsers);
}
} |
92362b38f43afe800186ed77125fe5f51dd6403d | 705 | java | Java | codebase/projects/test-report/src/java/edu/duke/cabig/catrip/test/report/data/TestSuite.java | NCIP/catrip | 1615ab2598cf5ce060e98d69052ae0e52eaf9148 | [
"BSD-3-Clause"
] | null | null | null | codebase/projects/test-report/src/java/edu/duke/cabig/catrip/test/report/data/TestSuite.java | NCIP/catrip | 1615ab2598cf5ce060e98d69052ae0e52eaf9148 | [
"BSD-3-Clause"
] | 1 | 2019-04-30T06:37:01.000Z | 2019-04-30T06:37:01.000Z | codebase/projects/test-report/src/java/edu/duke/cabig/catrip/test/report/data/TestSuite.java | NCIP/catrip | 1615ab2598cf5ce060e98d69052ae0e52eaf9148 | [
"BSD-3-Clause"
] | null | null | null | 22.741935 | 66 | 0.747518 | 997,575 | /*L
* Copyright Duke Comprehensive Cancer Center
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catrip/LICENSE.txt for details.
*/
/*
* Created on Jul 18, 2006
*/
package edu.duke.cabig.catrip.test.report.data;
import java.util.ArrayList;
import java.util.Properties;
public class TestSuite
{
public int errors;
public int failures;
public String name;
public int tests;
public double time;
public Properties props = new Properties();
public ArrayList<TestCase> testCases = new ArrayList<TestCase>();
public ArrayList<TestStep> testSteps = new ArrayList<TestStep>();
public String docText;
public Properties docTags = new Properties();
}
|
92362c65c1fa570d17e5e52719fb91815024aae5 | 1,460 | java | Java | model-auth-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/EmissionAllowanceProductType2Code.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 40 | 2020-10-13T13:44:59.000Z | 2022-03-30T13:58:32.000Z | model-auth-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/EmissionAllowanceProductType2Code.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 25 | 2020-10-04T23:46:22.000Z | 2022-03-30T12:31:03.000Z | model-auth-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/EmissionAllowanceProductType2Code.java | luongnvUIT/prowide-iso20022 | 59210a4b67cd38759df2d0dd82ad19acf93ffe75 | [
"Apache-2.0"
] | 22 | 2020-12-22T14:50:22.000Z | 2022-03-30T13:19:10.000Z | 23.174603 | 96 | 0.656849 | 997,576 |
package com.prowidesoftware.swift.model.mx.dic;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for EmissionAllowanceProductType2Code.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="EmissionAllowanceProductType2Code">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="CERE"/>
* <enumeration value="ERUE"/>
* <enumeration value="EUAE"/>
* <enumeration value="EUAA"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "EmissionAllowanceProductType2Code")
@XmlEnum
public enum EmissionAllowanceProductType2Code {
/**
* Commodity attribute of type emissions allowance CER (Certified Emission Reduction).
*
*/
CERE,
/**
* Commodity attribute of type emissions allowance ERU (European Reduction Unit).
*
*/
ERUE,
/**
* Commodity attribute of type emissions allowance EUA (European Union Allowance).
*
*/
EUAE,
/**
* Commodity attribute of type emissions allowance EUAA (European Union Aviation Allowance).
*
*/
EUAA;
public String value() {
return name();
}
public static EmissionAllowanceProductType2Code fromValue(String v) {
return valueOf(v);
}
}
|
92362ca5090753fde5d5ef995696fc462a76d8a2 | 4,449 | java | Java | src/main/java/net/jkernelmachines/util/generators/MultiClassGaussianGenerator.java | davidpicard/jkernelmachines | 9bfe30d82e8071b966b631d9906df2b7800bf2c3 | [
"BSD-3-Clause"
] | 18 | 2015-01-03T01:46:31.000Z | 2021-08-04T08:21:00.000Z | src/main/java/net/jkernelmachines/util/generators/MultiClassGaussianGenerator.java | raamana/jkernelmachines | 9bfe30d82e8071b966b631d9906df2b7800bf2c3 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/net/jkernelmachines/util/generators/MultiClassGaussianGenerator.java | raamana/jkernelmachines | 9bfe30d82e8071b966b631d9906df2b7800bf2c3 | [
"BSD-3-Clause"
] | 8 | 2015-10-19T14:22:09.000Z | 2021-08-04T08:21:01.000Z | 27.63354 | 83 | 0.674534 | 997,577 | /*******************************************************************************
* Copyright (c) 2016, David Picard.
* All rights reserved.
*
* 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 copyright holder 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.
*******************************************************************************/
package net.jkernelmachines.util.generators;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import net.jkernelmachines.type.TrainingSample;
/**
* <p>
* Class for generating toys subject to multi-class classification tasks, using
* Gaussian distributions.
* </p>
*
* <p>
* Toys are sampled from as many Gaussian distributions as the number of
* classes, in a space with the dimension of the number of classes. Each
* Gaussian has a mean of 1 on the component of the class and 0 otherwise. Thee
* spacing p and the standard deviation of the Gaussian can be adjusted.
* Generated lists are shuffled.
* </p>
*
* @author picard
*
*/
public class MultiClassGaussianGenerator {
float p = 2.0f;
double sigma = 1.0;
int nbclasses = 5;
Random ran = new Random();
/**
* Default constructor, with p=2, sigma = 1, nbclasses = 5;
*/
public MultiClassGaussianGenerator() {
}
/**
* Constructor specifying the number of classes
*
* @param nbclasses
* the number of classes
*/
public MultiClassGaussianGenerator(int nbclasses) {
this.nbclasses = nbclasses;
}
/**
* Generates a list of Toys with specified number of samples per class
*
* @param samplesPerClass
* the number of samples for each class
* @return the list of samples
*/
public List<TrainingSample<double[]>> generateList(int samplesPerClass) {
List<TrainingSample<double[]>> list = new ArrayList<TrainingSample<double[]>>();
for (int c = 0; c < nbclasses; c++) {
for (int i = 0; i < samplesPerClass; i++) {
double[] d = new double[nbclasses];
for (int x = 0; x < nbclasses; x++) {
if (c == x)
d[x] = p + ran.nextGaussian()*sigma;
else
d[x] = ran.nextGaussian()*sigma;
}
list.add(new TrainingSample<double[]>(d, c));
}
}
// shuffle the list before returning
Collections.shuffle(list, ran);
return list;
}
/**
* Tells the distance between classes
* @return the p
*/
public float getP() {
return p;
}
/**
* Sets the distance between classes
* @param p the p to set
*/
public void setP(float p) {
this.p = p;
}
/**
* Tells the standard deviation
* @return the sigma
*/
public double getSigma() {
return sigma;
}
/**
* Sets the standard deviation
* @param sigma the sigma to set
*/
public void setSigma(double sigma) {
this.sigma = sigma;
}
/**
* Tells the number of classes
* @return the nbclasses
*/
public int getNbclasses() {
return nbclasses;
}
/**
* Sets the number of classes
* @param nbclasses the nbclasses to set
*/
public void setNbclasses(int nbclasses) {
this.nbclasses = nbclasses;
}
}
|
92362d6907c09424fb2b74345d2298acb08a25e4 | 21,405 | java | Java | powerauth-admin/src/main/java/io/getlime/security/app/admin/controller/ApplicationController.java | wultra/powerauth-admin | 8a1dd92e9e82b0866e6745ddaadfe25ead2c6b3a | [
"Apache-2.0"
] | 3 | 2019-12-24T13:37:10.000Z | 2021-04-08T05:13:10.000Z | powerauth-admin/src/main/java/io/getlime/security/app/admin/controller/ApplicationController.java | wultra/powerauth-admin | 8a1dd92e9e82b0866e6745ddaadfe25ead2c6b3a | [
"Apache-2.0"
] | 85 | 2018-07-19T12:45:48.000Z | 2022-02-12T18:00:51.000Z | powerauth-admin/src/main/java/io/getlime/security/app/admin/controller/ApplicationController.java | wultra/powerauth-admin | 8a1dd92e9e82b0866e6745ddaadfe25ead2c6b3a | [
"Apache-2.0"
] | 3 | 2019-01-27T12:03:03.000Z | 2021-12-15T00:30:20.000Z | 43.773006 | 243 | 0.631581 | 997,578 | /*
* Copyright 2017 Wultra s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.security.app.admin.controller;
import com.google.common.collect.Lists;
import com.wultra.security.powerauth.client.PowerAuthClient;
import com.wultra.security.powerauth.client.model.enumeration.CallbackUrlType;
import com.wultra.security.powerauth.client.model.error.PowerAuthClientException;
import com.wultra.security.powerauth.client.v3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
/**
* Controller related to application and application version management.
*
* @author Petr Dvorak
*/
@Controller
public class ApplicationController {
private static final Logger logger = LoggerFactory.getLogger(ApplicationController.class);
private final List<String> CALLBACK_ATTRIBUTES_OPTIONAL = Arrays.asList("attr_userId", "attr_activationName", "attr_deviceInfo", "attr_platform", "attr_activationFlags", "attr_activationStatus", "attr_blockedReason", "attr_applicationId");
private final PowerAuthClient client;
@Autowired
public ApplicationController(PowerAuthClient client) {
this.client = client;
}
/**
* Redirect '/' URL to the list of application.
*
* @return Redirect view to list of applications.
*/
@RequestMapping(value = "/")
public String homePage() {
try {
List<GetApplicationListResponse.Applications> applicationList = client.getApplicationList();
if (applicationList.isEmpty()) {
return "redirect:/application/list";
} else {
return "redirect:/activation/list";
}
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Show list of applications.
*
* @param model Model with passed parameters.
* @return "applications" view.
*/
@RequestMapping(value = "/application/list")
public String applicationList(Map<String, Object> model) {
try {
List<GetApplicationListResponse.Applications> applicationList = client.getApplicationList();
model.put("applications", applicationList);
return "applications";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Show application detail.
*
* @param id Application ID.
* @param model Model with passed parameters.
* @return "applicationDetail" view.
*/
@RequestMapping(value = "/application/detail/{applicationId}")
public String applicationDetail(@PathVariable(value = "applicationId") Long id, Map<String, Object> model) {
try {
GetApplicationDetailResponse applicationDetails = client.getApplicationDetail(id);
GetRecoveryConfigResponse recoveryConfig = client.getRecoveryConfig(id);
List<GetCallbackUrlListResponse.CallbackUrlList> callbackUrlList = client.getCallbackUrlList(id);
model.put("id", applicationDetails.getApplicationId());
model.put("name", applicationDetails.getApplicationName());
model.put("masterPublicKey", applicationDetails.getMasterPublicKey());
model.put("activationRecoveryEnabled", recoveryConfig.isActivationRecoveryEnabled());
model.put("recoveryPostcardEnabled", recoveryConfig.isRecoveryPostcardEnabled());
model.put("allowMultipleRecoveryCodes", recoveryConfig.isAllowMultipleRecoveryCodes());
model.put("postcardPublicKey", recoveryConfig.getPostcardPublicKey());
model.put("remotePostcardPublicKey", recoveryConfig.getRemotePostcardPublicKey());
model.put("versions", Lists.reverse(applicationDetails.getVersions()));
model.put("roles", applicationDetails.getApplicationRoles());
model.put("callbacks", callbackUrlList);
return "applicationDetail";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Create a new application.
*
* @return "applicationCreate" view.
*/
@RequestMapping(value = "/application/create")
public String applicationCreate() {
return "applicationCreate";
}
/**
* Create a new application version.
*
* @param id Application ID
* @param model Model with passed parameters.
* @return "applicationVersionCreate" view.
*/
@RequestMapping(value = "/application/detail/{applicationId}/version/create")
public String applicationVersionCreate(@PathVariable(value = "applicationId") Long id, Map<String, Object> model) {
model.put("applicationId", id);
return "applicationVersionCreate";
}
/**
* Show application callback create form.
*
* @param id Application ID.
* @param model Model with passed parameters.
* @return "callbackCreate" view.
*/
@RequestMapping(value = "/application/detail/{applicationId}/callback/create")
public String applicationCreateCallback(@PathVariable(value = "applicationId") Long id, Map<String, Object> model) {
model.put("applicationId", id);
return "callbackCreate";
}
/**
* Show application callback update form.
*
* @param applicationId Application ID.
* @param callbackId Callback ID.
* @param model Model with passed parameters.
* @return "callbackUpdate" view.
*/
@RequestMapping(value = "/application/detail/{applicationId}/callback/update")
public String applicationUpdateCallback(@PathVariable(value = "applicationId") Long applicationId,
@RequestParam String callbackId,
Map<String, Object> model) {
if (callbackId == null) {
logger.warn("Missing callback ID");
return "error";
}
try {
List<GetCallbackUrlListResponse.CallbackUrlList> callbacks = client.getCallbackUrlList(applicationId);
for (GetCallbackUrlListResponse.CallbackUrlList callback: callbacks) {
if (callback.getId().equals(callbackId)) {
model.put("callbackId", callbackId);
model.put("applicationId", applicationId);
model.put("name", callback.getName());
model.put("callbackUrl", callback.getCallbackUrl());
for (String attribute: callback.getAttributes()) {
model.put("attr_" + attribute, true);
}
return "callbackUpdate";
}
}
logger.warn("Callback not found, application ID: {}, callback ID: {}", applicationId, callbackId);
return "error";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Show application role create form.
*
* @param id Application ID.
* @param model Model with passed parameters.
* @return "roleCreate" view.
*/
@RequestMapping(value = "/application/detail/{applicationId}/role/create")
public String applicationCreateRole(@PathVariable(value = "applicationId") Long id, Map<String, Object> model) {
model.put("applicationId", id);
return "roleCreate";
}
/**
* Execute the application create action by calling the SOAP service.
*
* @param name Application name.
* @param redirectAttributes Redirect attributes.
* @return Redirect to the new application details.
*/
@RequestMapping(value = "/application/create/do.submit", method = RequestMethod.POST)
public String applicationCreateAction(@RequestParam String name, RedirectAttributes redirectAttributes) {
try {
if (name == null || name.trim().isEmpty()) {
redirectAttributes.addFlashAttribute("error", "Application name must not be empty.");
return "redirect:/application/create";
}
CreateApplicationResponse application = client.createApplication(name);
return "redirect:/application/detail/" + application.getApplicationId();
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Execute the application version create action by calling the SOAP service.
*
* @param applicationId Application ID.
* @param name Version name.
* @param redirectAttributes Redirect attributes.
* @return Redirect to application detail (application versions are visible there).
*/
@RequestMapping(value = "/application/detail/{applicationId}/version/create/do.submit", method = RequestMethod.POST)
public String applicationVersionCreateAction(@PathVariable Long applicationId, @RequestParam String name, RedirectAttributes redirectAttributes) {
try {
if (name == null || name.trim().isEmpty()) {
redirectAttributes.addFlashAttribute("error", "Application version name must not be empty.");
return "redirect:/application/detail/" + applicationId + "/version/create";
}
client.createApplicationVersion(applicationId, name);
return "redirect:/application/detail/" + applicationId;
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Execute the action that marks application version supported / unsupported.
*
* @param version Application version.
* @param enabled True for supported, False for unsupported
* @param id Application ID (path variable), for the redirect purposes
* @return Redirect to application detail (application versions are visible there).
*/
@RequestMapping(value = "/application/detail/{applicationId}/version/update/do.submit", method = RequestMethod.POST)
public String applicationUpdateAction(
@RequestParam(value = "version", required = false) Long version,
@RequestParam(value = "enabled") Boolean enabled,
@PathVariable(value = "applicationId") Long id) {
try {
if (enabled) {
client.supportApplicationVersion(version);
} else {
client.unsupportApplicationVersion(version);
}
return "redirect:/application/detail/" + id;
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Execute the action that creates a new callback on given application.
*
* @param allParams All request parameters.
* @param applicationId Application ID.
* @param redirectAttributes Redirect attributes.
* @return Redirect to application detail, callbacks tab.
*/
@RequestMapping(value = "/application/detail/{applicationId}/callback/create/do.submit")
public String applicationCreateCallbackAction(
@RequestParam Map<String, String> allParams,
@PathVariable(value = "applicationId") Long applicationId, RedirectAttributes redirectAttributes) {
try {
String name = allParams.get("name");
String callbackUrl = allParams.get("callbackUrl");
String error = null;
if (name == null || name.trim().isEmpty()) {
error = "Callback name must not be empty.";
} else if (callbackUrl == null || callbackUrl.trim().isEmpty()) {
error = "Callback URL must not be empty.";
} else {
try {
new URL(callbackUrl);
} catch (MalformedURLException e) {
error = "Callback URL is not in a valid format";
}
}
if (error != null) {
for (String attribute: CALLBACK_ATTRIBUTES_OPTIONAL) {
if (allParams.get(attribute) != null) {
redirectAttributes.addFlashAttribute(attribute, true);
}
}
redirectAttributes.addFlashAttribute("error", error);
redirectAttributes.addFlashAttribute("name", name);
redirectAttributes.addFlashAttribute("callbackUrl", callbackUrl);
return "redirect:/application/detail/" + applicationId + "/callback/create";
}
List<String> attributes = new ArrayList<>();
attributes.add("activationId");
for (String attribute: CALLBACK_ATTRIBUTES_OPTIONAL) {
if (allParams.get(attribute) != null) {
attributes.add(attribute.replace("attr_", ""));
}
}
client.createCallbackUrl(applicationId, name, CallbackUrlType.ACTIVATION_STATUS_CHANGE, callbackUrl, attributes);
return "redirect:/application/detail/" + applicationId + "#callbacks";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Execute the action that creates a new callback on given application.
*
* @param allParams All request parameters.
* @param applicationId Application ID.
* @param redirectAttributes Redirect attributes.
* @return Redirect to application detail, callbacks tab.
*/
@RequestMapping(value = "/application/detail/{applicationId}/callback/update/do.submit")
public String applicationUpdateCallbackAction(
@RequestParam Map<String, String> allParams,
@PathVariable(value = "applicationId") Long applicationId,
RedirectAttributes redirectAttributes) {
try {
String name = allParams.get("name");
String callbackUrl = allParams.get("callbackUrl");
String callbackId = allParams.get("callbackId");
String error = null;
if (name == null || name.trim().isEmpty()) {
error = "Callback name must not be empty.";
} else if (callbackUrl == null || callbackUrl.trim().isEmpty()) {
error = "Callback URL must not be empty.";
} else {
try {
new URL(callbackUrl);
} catch (MalformedURLException e) {
error = "Callback URL is not in a valid format";
}
}
if (error != null) {
redirectAttributes.addAttribute("callbackId", callbackId);
redirectAttributes.addFlashAttribute("error", error);
redirectAttributes.addFlashAttribute("name", name);
redirectAttributes.addFlashAttribute("callbackUrl", callbackUrl);
return "redirect:/application/detail/" + applicationId + "/callback/update";
}
List<String> attributes = new ArrayList<>();
attributes.add("activationId");
for (String attribute: CALLBACK_ATTRIBUTES_OPTIONAL) {
if (allParams.get(attribute) != null) {
attributes.add(attribute.replace("attr_", ""));
}
}
client.updateCallbackUrl(callbackId, applicationId, name, callbackUrl, attributes);
return "redirect:/application/detail/" + applicationId + "#callbacks";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Execute the action that removes a callback with given ID.
*
* @param id Application ID.
* @param callbackId Callback ID.
* @return Redirect to application detail, callbacks tab.
*/
@RequestMapping(value = "/application/detail/{applicationId}/callback/remove/do.submit")
public String applicationRemoveCallbackAction(
@RequestParam(value = "callbackId") String callbackId,
@PathVariable(value = "applicationId") Long id) {
try {
client.removeCallbackUrl(callbackId);
return "redirect:/application/detail/" + id + "#callbacks";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Execute the action that creates a new role assigned to given application.
*
* @param id Application ID.
* @param name Role name.
* @param redirectAttributes Redirect attributes.
* @return Redirect to application detail, roles tab.
*/
@RequestMapping(value = "/application/detail/{applicationId}/role/create/do.submit")
public String applicationCreateRoleAction(
@RequestParam(value = "name") String name,
@PathVariable(value = "applicationId") Long id, RedirectAttributes redirectAttributes) {
try {
String error = null;
if (name == null || name.trim().isEmpty()) {
error = "Role name must not be empty.";
}
if (error != null) {
redirectAttributes.addFlashAttribute("error", error);
redirectAttributes.addFlashAttribute("name", name);
return "redirect:/application/detail/" + id + "/role/create";
}
client.addApplicationRoles(id, Collections.singletonList(name));
return "redirect:/application/detail/" + id + "#roles";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Execute the action that removes a callback with given ID.
*
* @param id Application ID.
* @param name Role name.
* @return Redirect to application detail, roles tab.
*/
@RequestMapping(value = "/application/detail/{applicationId}/role/remove/do.submit")
public String applicationRemoveRoleAction(
@RequestParam(value = "name") String name,
@PathVariable(value = "applicationId") Long id) {
try {
client.removeApplicationRoles(id, Collections.singletonList(name));
return "redirect:/application/detail/" + id + "#roles";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
/**
* Update recovery configuration.
* @param activationRecoveryEnabled Whether activation recovery is enabled.
* @param recoveryPostcardEnabled Whether recovery postcard is enabled.
* @param allowMultipleRecoveryCodes Whether multiple recovery codes are allowed per user.
* @param remotePostcardPublicKey Base64 encoded printing center public key.
* @param id Application ID.
* @return Redirect to application detail, recovery tab.
*/
@RequestMapping(value = "/application/detail/{applicationId}/recovery/update/do.submit")
public String applicationUpdateRecoveryConfigAction(
@RequestParam(value = "activationRecoveryEnabled", required = false) boolean activationRecoveryEnabled,
@RequestParam(value = "recoveryPostcardEnabled", required = false) boolean recoveryPostcardEnabled,
@RequestParam(value = "allowMultipleRecoveryCodes", required = false) boolean allowMultipleRecoveryCodes,
@RequestParam(value = "remotePostcardPublicKey", required = false) String remotePostcardPublicKey,
@PathVariable(value = "applicationId") Long id) {
try {
if (!activationRecoveryEnabled && recoveryPostcardEnabled) {
// Turn off recovery postcard in case activation recovery is disabled
recoveryPostcardEnabled = false;
}
client.updateRecoveryConfig(id, activationRecoveryEnabled, recoveryPostcardEnabled, allowMultipleRecoveryCodes, remotePostcardPublicKey);
return "redirect:/application/detail/" + id + "#recovery";
} catch (PowerAuthClientException ex) {
logger.warn(ex.getMessage(), ex);
return "error";
}
}
}
|
92362f43fd785a06f7599c652735317d41105f96 | 165 | java | Java | stratego.build.spoofax2.benchmark/src/main/java/benchmark/chocopy/compilation/Exp.java | toinehartman/stratego | 771ccce8a2a83d81aa78a1e0f6613ee3fda04178 | [
"Apache-2.0"
] | null | null | null | stratego.build.spoofax2.benchmark/src/main/java/benchmark/chocopy/compilation/Exp.java | toinehartman/stratego | 771ccce8a2a83d81aa78a1e0f6613ee3fda04178 | [
"Apache-2.0"
] | null | null | null | stratego.build.spoofax2.benchmark/src/main/java/benchmark/chocopy/compilation/Exp.java | toinehartman/stratego | 771ccce8a2a83d81aa78a1e0f6613ee3fda04178 | [
"Apache-2.0"
] | null | null | null | 27.5 | 78 | 0.854545 | 997,579 | package benchmark.chocopy.compilation;
import benchmark.chocopy.problem.ExpProblem;
public class Exp extends ChocoPyCompilationBenchmark implements ExpProblem { }
|
923630dea80d1c61993e0dc5b6f46f9b470180da | 2,361 | java | Java | server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/impl/TopicDao.java | MiddlewareICS/kaa | 65c02e847d6019e4afb20fbfb03c3416e0972908 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-08-27T10:45:57.000Z | 2019-08-30T06:21:04.000Z | server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/impl/TopicDao.java | MiddlewareICS/kaa | 65c02e847d6019e4afb20fbfb03c3416e0972908 | [
"ECL-2.0",
"Apache-2.0"
] | 8 | 2020-01-31T18:26:22.000Z | 2022-01-21T23:34:19.000Z | server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/impl/TopicDao.java | MiddlewareICS/kaa | 65c02e847d6019e4afb20fbfb03c3416e0972908 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-11-24T07:01:26.000Z | 2019-11-24T07:01:26.000Z | 26.233333 | 96 | 0.691233 | 997,580 | /*
* Copyright 2014-2016 CyberVision, Inc.
*
* 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.kaaproject.kaa.server.common.dao.impl;
import org.kaaproject.kaa.common.dto.TopicTypeDto;
import org.kaaproject.kaa.server.common.dao.model.sql.Topic;
import java.util.List;
/**
* The Interface TopicDao.
*
* @param <T> the generic type
*/
public interface TopicDao<T> extends SqlDao<T> {
/**
* Find topics by application id.
*
* @param appId the application id
* @return the list of topics
*/
List<T> findTopicsByAppId(String appId);
/**
* Find topics by application id and type.
*
* @param appId the application id
* @param type the topic type
* @return the list of topics
*/
List<T> findTopicsByAppIdAndType(String appId, TopicTypeDto type);
/**
* Find topic by application id and name.
*
* @param appId the application id
* @param topicName the topic name
* @return topic by application
*/
T findTopicByAppIdAndName(String appId, String topicName);
/**
* Find topics by ids.
*
* @param ids the ids
* @return the list of topics
*/
List<T> findTopicsByIds(List<String> ids);
/**
* Removes the topics by application id.
*
* @param appId the application id
*/
void removeTopicsByAppId(String appId);
/**
* Gets the next sequence number of topic.
*
* @param topicId the topic id
* @return the topic with next sequence number
*/
T getNextSeqNumber(String topicId);
/**
* Find vacant topics for endpoint groups.
* This method have to return topics which not yet attached to endpoint group with specific id
*
* @param appId the application id
* @param groupId the group id
* @return the list of vacant topics
*/
List<Topic> findVacantTopicsByGroupId(String appId, String groupId);
}
|
92363246483f5ea3a21f8744e9f1d27ea36fc71b | 1,420 | java | Java | src/test/java/io/dwpbank/movewp3/kafka/compoundkey/CompoundKeyTest.java | knieschraube/kafka-compoundkey-serde | ad01ad96060b16b802146336045f840ec4dd643a | [
"Apache-2.0"
] | 5 | 2020-05-26T09:40:50.000Z | 2021-09-22T20:42:42.000Z | src/test/java/io/dwpbank/movewp3/kafka/compoundkey/CompoundKeyTest.java | knieschraube/kafka-compoundkey-serde | ad01ad96060b16b802146336045f840ec4dd643a | [
"Apache-2.0"
] | 3 | 2020-05-25T16:16:51.000Z | 2020-06-12T15:14:01.000Z | src/test/java/io/dwpbank/movewp3/kafka/compoundkey/CompoundKeyTest.java | knieschraube/kafka-compoundkey-serde | ad01ad96060b16b802146336045f840ec4dd643a | [
"Apache-2.0"
] | 2 | 2020-06-10T09:48:17.000Z | 2022-01-27T07:10:41.000Z | 33.023256 | 117 | 0.662676 | 997,581 | package io.dwpbank.movewp3.kafka.compoundkey;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class CompoundKeyTest {
@Test
public void nullIsRenderedCorrectly() {
assertThat(CompoundKey.of(() -> Arrays.asList(new Object[]{null})).toString()).isEqualTo("N");
assertThat(CompoundKey.of(() -> Arrays.asList(new Object[]{42, null})).toString()).isEqualTo("2:42-N");
assertThat(CompoundKey.of(() -> Arrays.asList(new Object[]{42, null, 23})).toString()).isEqualTo("2:42-N-2:23");
}
@Test
public void multipleStrings() {
assertThat(
CompoundKey.of(() -> List.of("Gallia est omnis divisa in partes tres.", "Quarum unum incolunt Belgae, ..."))
.toString()).isEqualTo("39:Gallia est omnis divisa in partes tres.-32:Quarum unum incolunt Belgae, ...");
}
@Test
public void emptyString() {
assertThat(CompoundKey.of(() -> List.of("")).toString()).isEqualTo("0:");
}
@Test
public void boxedSimpleTypes() {
assertThat(
CompoundKey.of(() -> Arrays.asList(23, 42L, -1, true, false, 3.14))
.toString()).isEqualTo("2:23-2:42-2:-1-4:true-5:false-4:3.14");
}
@Test
public void bigDecimal() {
assertThat(CompoundKey.of(() -> List.of(BigDecimal.ONE, BigDecimal.ZERO)).toString()).isEqualTo("1:1-1:0");
}
}
|
923632ee9608cb7751b7752ede8329a59ef3c905 | 15,733 | java | Java | src/test/java/bsh/TestBshScriptEngine.java | saravanan-murugs/beanshell | 05a1d649dffc14f1fa654bc5a4a1e6233eac5eed | [
"Apache-2.0"
] | 640 | 2015-09-29T03:28:02.000Z | 2022-03-27T06:57:31.000Z | src/test/java/bsh/TestBshScriptEngine.java | saravanan-murugs/beanshell | 05a1d649dffc14f1fa654bc5a4a1e6233eac5eed | [
"Apache-2.0"
] | 409 | 2015-09-23T18:22:07.000Z | 2022-02-23T23:20:05.000Z | src/test/java/bsh/TestBshScriptEngine.java | saravanan-murugs/beanshell | 05a1d649dffc14f1fa654bc5a4a1e6233eac5eed | [
"Apache-2.0"
] | 180 | 2015-10-01T21:19:11.000Z | 2022-03-28T02:19:17.000Z | 41.402632 | 120 | 0.663955 | 997,582 | package bsh;
import static javax.script.ScriptContext.ENGINE_SCOPE;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import bsh.engine.BshScriptEngine;
import bsh.engine.BshScriptEngineFactory;
public class TestBshScriptEngine {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void test_bsh_script_engine( ) throws Throwable {
ScriptEngineManager manager =
new ScriptEngineManager( bsh.Interpreter.class.getClassLoader() );
ScriptEngine engine = manager.getEngineByName( "beanshell" );
assertNotNull( engine );
// basic eval
int i = (Integer)engine.eval("2*2");
assertEquals( 4, i );
// set a variable
engine.put( "foo", 42 );
assertEquals( 42, engine.get("foo") );
// bsh primitives stay primitive internally
engine.eval( "int fooInt=42" );
assertEquals( 42, engine.get("foo") );
assertSame( engine.eval("fooInt.getClass();"), Primitive.class );
assertThat( engine.getContext().getAttribute( "fooInt", ENGINE_SCOPE ),
instanceOf( Integer.class ) );
// Variables visible through bindings in both directions?
Bindings engineScope = engine.getBindings( ENGINE_SCOPE );
Bindings engineScope2 = engine.getContext().getBindings( ENGINE_SCOPE );
assertSame( engineScope, engineScope2 );
assertThat( engineScope.get("foo"), instanceOf( Integer.class ) );
engineScope.put("bar", "gee");
// get() and eval() for us should be equivalent in this case
assertEquals( "gee", engine.get("bar") );
assertEquals( "gee", engine.eval("bar") );
// install and invoke a method
engine.eval("foo() { return foo+1; }");
// invoke a method
Invocable invocable = (Invocable) engine;
assertEquals( 43, invocable.invokeFunction( "foo" ) );
// get interface
engine.eval("flag=false; run() { flag=true; }");
assertFalse( (Boolean) engine.get("flag") );
assertNull( engine.get("flag_nonexistent") );
Runnable runnable = (Runnable) invocable.getInterface( Runnable.class );
runnable.run();
assertTrue( (Boolean) engine.get("flag") );
// get interface from scripted object
engine.eval(
"flag2=false; myObj() { run() { flag2=true; } return this; }");
assertFalse( (Boolean) engine.get("flag2") );
Object scriptedObject = invocable.invokeFunction("myObj");
assertThat( scriptedObject, instanceOf( This.class ) );
runnable =
(Runnable) invocable.getInterface( scriptedObject, Runnable.class );
runnable.run();
assertTrue( (Boolean) engine.get("flag2") );
// Run with alternate bindings
assertTrue( (Boolean) engine.get("flag") );
assertEquals( 42, engine.get("foo") );
Bindings newEngineScope = engine.createBindings();
engine.eval( "flag=false; foo=33;", newEngineScope );
assertFalse( (Boolean) newEngineScope.get("flag") );
assertEquals(33, newEngineScope.get("foo") );
// These are unchanged in default context
assertTrue( (Boolean )engine.get("flag") );
assertEquals( 42, engine.get("foo") );
// Try redirecting output
String fname = "testBshScriptEngine.out";
String outString = "checkstyle-supressions.xml";
Writer fout = new FileWriter( fname );
engine.getContext().setWriter( fout );
engine.put( "outString", outString );
engine.eval(new StringReader("dir('src/conf');"));
BufferedReader bin = new BufferedReader( new FileReader( fname ) );
String line = bin.readLine();
assertNotNull(line);
assertThat(line, endsWith(outString));
new File(fname).delete();
bin.close();
fout.close();
// Add a new scope dynamically?
}
@Test
public void test_bsh_script_engine_compile() throws Throwable {
Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName( "beanshell" );
assertNotNull( engine );
CompiledScript script = engine.compile(new StringReader("return 42;"));
assertEquals(42, script.eval());
}
@Test
public void test_bsh_script_engine_compile_no_line_terminator() throws Throwable {
Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName( "beanshell" );
assertNotNull( engine );
CompiledScript script = engine.compile("37+5");
assertEquals(42, script.eval());
}
@Test
public void test_bsh_script_engine_compile_args() throws Throwable {
ScriptEngine engine = new ScriptEngineManager().getEngineByName( "beanshell" );
assertNotNull( engine );
CompiledScript square = ((Compilable) engine).compile("return x*x;");
ScriptContext ctx = engine.getContext();
ctx.setAttribute("x", 5, ENGINE_SCOPE);
assertEquals(25, square.eval(ctx));
}
@Test
public void test_bsh_script_engine_compile_return_this() throws Throwable {
class CompiledMethod {
Object bshThis;
Method invokeMethod;
CompiledMethod() throws Throwable {
Compilable engine = (Compilable) new ScriptEngineManager().getEngineByName( "beanshell" );
assertNotNull( engine );
CompiledScript script = engine.compile("square(x) { return x*x; } return this;");
bshThis = script.eval();
invokeMethod = bshThis.getClass().getMethod("invokeMethod", new Class[] {String.class, Object[].class});
}
int square(int x) throws Throwable {
return (int) invokeMethod.invoke(bshThis, new Object[] {"square", new Object[] {x}});
}
}
CompiledMethod cm = new CompiledMethod();
assertEquals(16, cm.square(4));
assertEquals(25, cm.square(5));
}
@Test
public void test_bsh_script_engine_compile_set_return_this() throws Throwable {
ScriptEngine engine = new ScriptEngineManager().getEngineByName( "beanshell" );
assertNotNull( engine );
CompiledScript script = ((Compilable) engine).compile("square(x) { return x*x; } return this;");
engine.getContext().setAttribute("script", script.eval(), ENGINE_SCOPE);
assertEquals(16, engine.eval("script.square(4);"));
assertEquals(25, engine.eval("script.square(5);"));
engine.eval("square(x) { return script.square(x); }");
assertEquals(16, engine.eval("square(4);"));
assertEquals(25, engine.eval("square(5);"));
}
@Test
public void check_BshScriptEngineFactory() throws Exception {
final String script = "a = null; return \"a=\" + a;\n";
final Interpreter bsh = new Interpreter();
final Object interpreterResult = bsh.eval(script);
final BshScriptEngine bse = new BshScriptEngine();
final ScriptEngineFactory bsef = bse.getFactory();
final Object scriptEngineResult = bsef.getScriptEngine().eval(script);
assertEquals(interpreterResult, scriptEngineResult);
assertSame(bsef, bse.getFactory());
}
@Test
public void test_script_engine_factory() throws Exception {
final ScriptEngineFactory bsef = new BshScriptEngine().getFactory();
assertEquals("BeanShell Engine", bsef.getParameter(ScriptEngine.ENGINE));
assertEquals("BeanShell Engine", bsef.getParameter(ScriptEngine.NAME));
assertEquals(Interpreter.VERSION, bsef.getParameter(ScriptEngine.ENGINE_VERSION));
assertEquals("BeanShell", bsef.getParameter(ScriptEngine.LANGUAGE));
assertEquals(Interpreter.VERSION, bsef.getParameter(ScriptEngine.LANGUAGE_VERSION));
assertEquals("MULTITHREADED", bsef.getParameter("THREADING"));
assertNull(bsef.getParameter("UNKNOWN"));
assertEquals("foo();", bsef.getMethodCallSyntax(null, "foo", new String[0]));
assertEquals("obj.toString();", bsef.getMethodCallSyntax("obj", "toString", new String[0]));
assertEquals("obj.someMethod(42, \"text\", false);",
bsef.getMethodCallSyntax("obj", "someMethod", new String[] {"42", "\"text\"", "false"} ));
assertEquals("print(\"out\");", bsef.getOutputStatement("out"));
assertEquals("a=0;\nb=a+1;\nreturn b;\n", bsef.getProgram("a=0","b=a+1","return b;"));
assertThat(bsef.getMimeTypes(), contains("application/x-beanshell", "application/x-bsh"));
assertThat(bsef.getExtensions(), contains("bsh"));
assertThat(bsef.getNames(), contains("beanshell", "bsh"));
}
@Test
public void test_eval_writer_unicode() throws Exception {
ScriptEngine engine = new BshScriptEngineFactory().getScriptEngine();
ScriptContext ctx = new SimpleScriptContext();
StringWriter sw = new StringWriter();
ctx.setWriter(sw);
engine.setContext(ctx);
engine.eval("print('\\u3456');");
assertEquals(new String("\u3456".getBytes(), "UTF-8").charAt(0),
new String(sw.toString().getBytes(), "UTF-8").charAt(0));
}
@Test
public void test_method_invocation() throws Exception {
ScriptEngine engine = new BshScriptEngineFactory().getScriptEngine();
ScriptContext ctx = new SimpleScriptContext();
StringWriter sw = new StringWriter();
ctx.setWriter(sw);
engine.setContext(ctx);
engine.eval(
"this.interpreter.print(new Object() {"
+ "public String toString() {"
+"return \"hello BeanShell\";"
+ "}"
+ "});"
);
assertEquals("hello BeanShell", sw.toString());
sw.close();
}
@Test
public void check_parse_exception_line_number() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Encountered: ;"));
final String script = "print(\"test\";";
new BshScriptEngineFactory().getScriptEngine().eval(script);
}
@Test
public void check_script_exception_eval_error() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Unknown class: Unknown"));
final String script = "new Unknown();";
new BshScriptEngineFactory().getScriptEngine().eval(script);
}
@Test
public void check_exception_thrown_in_script() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Caused by: java.lang.Exception: test exception"));
final String script = "throw new Exception('test exception');";
new BshScriptEngineFactory().getScriptEngine().eval(script);
}
@Test
public void check_script_exception_get_interface_null_this() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(containsString("Illegal object type: null"));
((Invocable) new BshScriptEngine()).getInterface(null, null);
}
@Test
public void check_script_exception_get_interface_illegal_this() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(containsString("Illegal object type: class java.lang.Object"));
((Invocable) new BshScriptEngine()).getInterface(new Object(), null);
}
@Test
public void check_script_exception_invoke_method_null_this() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Illegal object type: null"));
((Invocable) new BshScriptEngine()).invokeMethod(null, null);
}
@Test
public void check_script_exception_invoke_method_illegal_this() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Illegal object type: class java.lang.Object"));
((Invocable) new BshScriptEngine()).invokeMethod(new Object(), null);
}
@Test
public void check_script_exception_invoke_function_unknown() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Method unknown() not found in bsh scripted object"));
((Invocable) new BshScriptEngine()).invokeFunction("unknown");
}
@Test
public void check_script_exception_invoke_function_throws_exception() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Caused by: java.lang.Exception: test exception"));
ScriptEngine engine = new ScriptEngineManager().getEngineByName("beanshell");
engine.eval("foo() { throw new Exception('test exception'); }");
((Invocable) engine).invokeFunction("foo");
}
@Test
public void check_script_exception_compile_close_ioe() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Test Close IOE"));
Reader read = new BufferedReader( new StringReader("return 42;") ) {
public void close() throws IOException {
throw new IOException("Test Close IOE");
}
};
((Compilable) new ScriptEngineManager().getEngineByName("beanshell")).compile(read);
}
@Test
public void check_script_exception_compile_parse_exception() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Encountered: ;"));
final String script = "print(\"test\";";
((Compilable) new BshScriptEngineFactory().getScriptEngine()).compile(script);
}
@Test
public void check_script_exception_compile_eval_error() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Unknown class: Unknown"));
final String script = "new Unknown();";
((Compilable) new ScriptEngineManager().getEngineByName("beanshell")).compile(script).eval();
}
@Test
public void check_script_exception_compile_reader_ioe() throws Exception {
thrown.expect(ScriptException.class);
thrown.expectMessage(containsString("Test IOE"));
Reader read = new StringReader("") {
public int read(char cbuf[]) throws IOException {
throw new IOException("Test IOE");
}
};
((Compilable) new BshScriptEngineFactory().getScriptEngine()).compile(read);
}
}
|
9236349266cbd2af670f208acdfa62439eaae286 | 15,057 | java | Java | chrome/android/java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java | Cela-Inc/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3,282 | 2016-07-09T10:14:53.000Z | 2022-03-23T02:52:47.000Z | app/src/main/java/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java | hu670014125/AndroidChromium | b4d7e48b7c83d090e7601003cda625c19cb20867 | [
"Apache-2.0"
] | 77 | 2016-07-12T06:51:46.000Z | 2021-12-13T02:59:03.000Z | app/src/main/java/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java | hu670014125/AndroidChromium | b4d7e48b7c83d090e7601003cda625c19cb20867 | [
"Apache-2.0"
] | 873 | 2016-07-11T01:36:14.000Z | 2022-03-16T06:30:28.000Z | 39.007772 | 100 | 0.68958 | 997,583 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.media.router;
import android.content.Context;
import android.support.v7.media.MediaRouter;
import org.chromium.base.SysUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.chrome.browser.media.router.cast.CastMediaRouteProvider;
import org.chromium.chrome.browser.media.router.cast.MediaSink;
import org.chromium.chrome.browser.media.router.cast.MediaSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Implements the JNI interface called from the C++ Media Router implementation on Android.
* Owns a list of {@link MediaRouteProvider} implementations and dispatches native calls to them.
*/
@JNINamespace("media_router")
public class ChromeMediaRouter implements MediaRouteManager {
private static final String TAG = "MediaRouter";
private static MediaRouteProvider.Builder sRouteProviderBuilder =
new CastMediaRouteProvider.Builder();
// The pointer to the native object. Can be null only during tests.
private final long mNativeMediaRouterAndroid;
private final List<MediaRouteProvider> mRouteProviders = new ArrayList<MediaRouteProvider>();
private final Map<String, MediaRouteProvider> mRouteIdsToProviders =
new HashMap<String, MediaRouteProvider>();
private final Map<String, Map<MediaRouteProvider, List<MediaSink>>> mSinksPerSourcePerProvider =
new HashMap<String, Map<MediaRouteProvider, List<MediaSink>>>();
private final Map<String, List<MediaSink>> mSinksPerSource =
new HashMap<String, List<MediaSink>>();
@VisibleForTesting
public static void setRouteProviderBuilderForTest(MediaRouteProvider.Builder builder) {
sRouteProviderBuilder = builder;
}
@VisibleForTesting
protected List<MediaRouteProvider> getRouteProvidersForTest() {
return mRouteProviders;
}
@VisibleForTesting
protected Map<String, MediaRouteProvider> getRouteIdsToProvidersForTest() {
return mRouteIdsToProviders;
}
@VisibleForTesting
protected Map<String, Map<MediaRouteProvider, List<MediaSink>>>
getSinksPerSourcePerProviderForTest() {
return mSinksPerSourcePerProvider;
}
@VisibleForTesting
protected Map<String, List<MediaSink>> getSinksPerSourceForTest() {
return mSinksPerSource;
}
/**
* Obtains the {@link MediaRouter} instance given the application context.
* @param applicationContext The context to get the Android media router service for.
* @return Null if the media router API is not supported, the service instance otherwise.
*/
@Nullable
public static MediaRouter getAndroidMediaRouter(Context applicationContext) {
try {
// Pre-MR1 versions of JB do not have the complete MediaRouter APIs,
// so getting the MediaRouter instance will throw an exception.
return MediaRouter.getInstance(applicationContext);
} catch (NoSuchMethodError e) {
return null;
} catch (NoClassDefFoundError e) {
// TODO(mlamouri): happens with Robolectric.
return null;
}
}
@Override
public void onSinksReceived(
String sourceId, MediaRouteProvider provider, List<MediaSink> sinks) {
if (!mSinksPerSourcePerProvider.containsKey(sourceId)) {
mSinksPerSourcePerProvider.put(
sourceId, new HashMap<MediaRouteProvider, List<MediaSink>>());
}
// Replace the sinks found by this provider with the new list.
Map<MediaRouteProvider, List<MediaSink>> sinksPerProvider =
mSinksPerSourcePerProvider.get(sourceId);
sinksPerProvider.put(provider, sinks);
List<MediaSink> allSinksPerSource = new ArrayList<MediaSink>();
for (List<MediaSink> s : sinksPerProvider.values()) allSinksPerSource.addAll(s);
mSinksPerSource.put(sourceId, allSinksPerSource);
if (mNativeMediaRouterAndroid != 0) {
nativeOnSinksReceived(mNativeMediaRouterAndroid, sourceId, allSinksPerSource.size());
}
}
@Override
public void onRouteCreated(
String mediaRouteId, String mediaSinkId, int requestId, MediaRouteProvider provider,
boolean wasLaunched) {
mRouteIdsToProviders.put(mediaRouteId, provider);
if (mNativeMediaRouterAndroid != 0) {
nativeOnRouteCreated(mNativeMediaRouterAndroid, mediaRouteId, mediaSinkId, requestId,
wasLaunched);
}
}
@Override
public void onRouteRequestError(String errorText, int requestId) {
if (mNativeMediaRouterAndroid != 0) {
nativeOnRouteRequestError(mNativeMediaRouterAndroid, errorText, requestId);
}
}
@Override
public void onRouteClosed(String mediaRouteId) {
if (mNativeMediaRouterAndroid != 0) {
nativeOnRouteClosed(mNativeMediaRouterAndroid, mediaRouteId);
}
mRouteIdsToProviders.remove(mediaRouteId);
}
@Override
public void onRouteClosedWithError(String mediaRouteId, String message) {
if (mNativeMediaRouterAndroid != 0) {
nativeOnRouteClosedWithError(mNativeMediaRouterAndroid, mediaRouteId, message);
}
mRouteIdsToProviders.remove(mediaRouteId);
}
@Override
public void onMessageSentResult(boolean success, int callbackId) {
nativeOnMessageSentResult(mNativeMediaRouterAndroid, success, callbackId);
}
@Override
public void onMessage(String mediaRouteId, String message) {
nativeOnMessage(mNativeMediaRouterAndroid, mediaRouteId, message);
}
/**
* Initializes the media router and its providers.
* @param nativeMediaRouterAndroid the handler for the native counterpart of this instance
* @param applicationContext the application context to use to obtain system APIs
* @return an initialized {@link ChromeMediaRouter} instance
*/
@CalledByNative
public static ChromeMediaRouter create(long nativeMediaRouterAndroid,
Context applicationContext) {
ChromeMediaRouter router = new ChromeMediaRouter(nativeMediaRouterAndroid);
MediaRouteProvider provider = sRouteProviderBuilder.create(applicationContext, router);
if (provider != null) router.addMediaRouteProvider(provider);
return router;
}
/**
* Starts background monitoring for available media sinks compatible with the given
* |sourceUrn| if the device is in a state that allows it.
* @param sourceId a URL to use for filtering of the available media sinks
* @return whether the monitoring started (ie. was allowed).
*/
@CalledByNative
public boolean startObservingMediaSinks(String sourceId) {
if (SysUtils.isLowEndDevice()) return false;
for (MediaRouteProvider provider : mRouteProviders) {
provider.startObservingMediaSinks(sourceId);
}
return true;
}
/**
* Stops background monitoring for available media sinks compatible with the given
* |sourceUrn|
* @param sourceId a URL passed to {@link #startObservingMediaSinks(String)} before.
*/
@CalledByNative
public void stopObservingMediaSinks(String sourceId) {
for (MediaRouteProvider provider : mRouteProviders) {
provider.stopObservingMediaSinks(sourceId);
}
mSinksPerSource.remove(sourceId);
mSinksPerSourcePerProvider.remove(sourceId);
}
/**
* Returns the URN of the media sink corresponding to the given source URN
* and an index. Essentially a way to access the corresponding {@link MediaSink}'s
* list via JNI.
* @param sourceUrn The URN to get the sink for.
* @param index The index of the sink in the current sink array.
* @return the corresponding sink URN if found or null.
*/
@CalledByNative
public String getSinkUrn(String sourceUrn, int index) {
return getSink(sourceUrn, index).getUrn();
}
/**
* Returns the name of the media sink corresponding to the given source URN
* and an index. Essentially a way to access the corresponding {@link MediaSink}'s
* list via JNI.
* @param sourceUrn The URN to get the sink for.
* @param index The index of the sink in the current sink array.
* @return the corresponding sink name if found or null.
*/
@CalledByNative
public String getSinkName(String sourceUrn, int index) {
return getSink(sourceUrn, index).getName();
}
/**
* Initiates route creation with the given parameters. Notifies the native client of success
* and failure.
* @param sourceId the id of the {@link MediaSource} to route to the sink.
* @param sinkId the id of the {@link MediaSink} to route the source to.
* @param presentationId the id of the presentation to be used by the page.
* @param origin the origin of the frame requesting a new route.
* @param tabId the id of the tab the requesting frame belongs to.
* @param isIncognito whether the route is being requested from an Incognito profile.
* @param requestId the id of the route creation request tracked by the native side.
*/
@CalledByNative
public void createRoute(
String sourceId,
String sinkId,
String presentationId,
String origin,
int tabId,
boolean isIncognito,
int requestId) {
MediaRouteProvider provider = getProviderForSource(sourceId);
if (provider == null) {
onRouteRequestError("No provider supports createRoute with source: " + sourceId
+ " and sink: " + sinkId, requestId);
return;
}
provider.createRoute(
sourceId, sinkId, presentationId, origin, tabId, isIncognito, requestId);
}
/**
* Initiates route joining with the given parameters. Notifies the native client of success
* or failure.
* @param sourceId the id of the {@link MediaSource} to route to the sink.
* @param sinkId the id of the {@link MediaSink} to route the source to.
* @param presentationId the id of the presentation to be used by the page.
* @param origin the origin of the frame requesting a new route.
* @param tabId the id of the tab the requesting frame belongs to.
* @param requestId the id of the route creation request tracked by the native side.
*/
@CalledByNative
public void joinRoute(
String sourceId,
String presentationId,
String origin,
int tabId,
int requestId) {
MediaRouteProvider provider = getProviderForSource(sourceId);
if (provider == null) {
onRouteRequestError("Route not found.", requestId);
return;
}
provider.joinRoute(sourceId, presentationId, origin, tabId, requestId);
}
/**
* Closes the route specified by the id.
* @param routeId the id of the route to close.
*/
@CalledByNative
public void closeRoute(String routeId) {
MediaRouteProvider provider = mRouteIdsToProviders.get(routeId);
if (provider == null) return;
provider.closeRoute(routeId);
}
/**
* Notifies the specified route that it's not attached to the web page anymore.
* @param routeId the id of the route that was detached.
*/
@CalledByNative
public void detachRoute(String routeId) {
MediaRouteProvider provider = mRouteIdsToProviders.get(routeId);
if (provider == null) return;
provider.detachRoute(routeId);
mRouteIdsToProviders.remove(routeId);
}
/**
* Sends a string message to the specified route.
* @param routeId The id of the route to send the message to.
* @param message The message to send.
* @param callbackId The id of the result callback tracked by the native side.
*/
@CalledByNative
public void sendStringMessage(String routeId, String message, int callbackId) {
MediaRouteProvider provider = mRouteIdsToProviders.get(routeId);
if (provider == null) {
nativeOnMessageSentResult(mNativeMediaRouterAndroid, false, callbackId);
return;
}
provider.sendStringMessage(routeId, message, callbackId);
}
/**
* Sends a binary message to the specified route.
* @param routeId The id of the route to send the message to.
* @param data The binary message to send.
* @param callbackId The id of the result callback tracked by the native side.
*/
@CalledByNative
public void sendBinaryMessage(String routeId, byte[] data, int callbackId) {
MediaRouteProvider provider = mRouteIdsToProviders.get(routeId);
if (provider == null) {
nativeOnMessageSentResult(mNativeMediaRouterAndroid, false, callbackId);
return;
}
provider.sendBinaryMessage(routeId, data, callbackId);
}
@VisibleForTesting
protected ChromeMediaRouter(long nativeMediaRouter) {
mNativeMediaRouterAndroid = nativeMediaRouter;
}
@VisibleForTesting
protected void addMediaRouteProvider(MediaRouteProvider provider) {
mRouteProviders.add(provider);
}
private MediaSink getSink(String sourceId, int index) {
assert mSinksPerSource.containsKey(sourceId);
return mSinksPerSource.get(sourceId).get(index);
}
private MediaRouteProvider getProviderForSource(String sourceId) {
for (MediaRouteProvider provider : mRouteProviders) {
if (provider.supportsSource(sourceId)) return provider;
}
return null;
}
native void nativeOnSinksReceived(
long nativeMediaRouterAndroid, String sourceUrn, int count);
native void nativeOnRouteCreated(
long nativeMediaRouterAndroid,
String mediaRouteId,
String mediaSinkId,
int createRouteRequestId,
boolean wasLaunched);
native void nativeOnRouteRequestError(
long nativeMediaRouterAndroid, String errorText, int createRouteRequestId);
native void nativeOnRouteClosed(long nativeMediaRouterAndroid, String mediaRouteId);
native void nativeOnRouteClosedWithError(
long nativeMediaRouterAndroid, String mediaRouteId, String message);
native void nativeOnMessageSentResult(
long nativeMediaRouterAndroid, boolean success, int callbackId);
native void nativeOnMessage(long nativeMediaRouterAndroid, String mediaRouteId, String message);
}
|
923634d416417b3db0cadd4701fe4cffe8bd56e8 | 4,385 | java | Java | corpus/class/eclipse.jdt.core/3966.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 15 | 2018-07-10T09:38:31.000Z | 2021-11-29T08:28:07.000Z | corpus/class/eclipse.jdt.core/3966.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 3 | 2018-11-16T02:58:59.000Z | 2021-01-20T16:03:51.000Z | corpus/class/eclipse.jdt.core/3966.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 6 | 2018-06-27T20:19:00.000Z | 2022-02-19T02:29:53.000Z | 35.33871 | 117 | 0.651073 | 997,584 | /*******************************************************************************
* Copyright (c) 2005, 2007 BEA Systems, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* ychag@example.com - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.apt.core.internal;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.apt.core.internal.generatedfile.GeneratedFileManager;
import org.eclipse.jdt.apt.core.internal.generatedfile.GeneratedSourceFolderManager;
import org.eclipse.jdt.apt.core.internal.util.FileSystemUtil;
import org.eclipse.jdt.apt.core.util.AptPreferenceConstants;
import org.eclipse.jdt.core.IJavaProject;
/**
* Stores project-specific data for APT. Analagous to JavaProject
* @author jgarms
*
*/
public class AptProject {
private final IJavaProject _javaProject;
private final GeneratedFileManager _gfm;
private final GeneratedSourceFolderManager _gsfm;
public AptProject(final IJavaProject javaProject) {
_javaProject = javaProject;
_gsfm = new GeneratedSourceFolderManager(this);
_gfm = new GeneratedFileManager(this, _gsfm);
}
public IJavaProject getJavaProject() {
return _javaProject;
}
public GeneratedFileManager getGeneratedFileManager() {
return _gfm;
}
public GeneratedSourceFolderManager getGeneratedSourceFolderManager() {
return _gsfm;
}
/**
* This method should be called whenever compilation begins, to perform
* initialization and verify configuration.
*/
public void compilationStarted() {
_gfm.compilationStarted();
}
/**
* This method should be called whenever project preferences are
* changed by the user. This may cause the classpath and generated
* source folder to change, so this should <em>not</em> be called
* from a context where resources may be locked, e.g., within
* certain resource change listeners.
* @param key a preference key such as @see AptPreferenceConstants#APT_ENABLED
*/
public void preferenceChanged(String key) {
if (AptPreferenceConstants.APT_GENSRCDIR.equals(key)) {
_gsfm.folderNamePreferenceChanged();
} else if (AptPreferenceConstants.APT_ENABLED.equals(key)) {
_gsfm.enabledPreferenceChanged();
}
}
/**
* Invoked whenever a project is cleaned. This will remove any state kept about
* generated files for the given project. If the deleteFiles flag is specified,
* then the contents of the generated source folder will be deleted.
*
* @param deleteFiles true if the contents of the generated source folder are to be
* deleted, false otherwise.
*/
public void projectClean(boolean deleteFiles) {
_gfm.projectCleaned();
// which will force the next build to be a full build.
if (deleteFiles) {
IFolder f = _gsfm.getFolder();
if (f != null && f.exists()) {
try {
IResource[] members = f.members();
for (int i = 0; i < members.length; i++) {
FileSystemUtil.deleteDerivedResources(members[i]);
}
} catch (CoreException ce) {
AptPlugin.log(ce, "Could not delete generated files");
}
}
}
}
/**
* Invoked when a project is closed.
*/
public void projectClosed() {
_gfm.projectClosed();
}
/**
* Invoked when a project has been deleted, to clean up
* state associated with the project.
* This will not delete any of the project's generated files
* from disk, nor will it delete this object (which in turn
* owns the GeneratedFileManager for this project).
*/
public void projectDeleted() {
if (AptPlugin.DEBUG)
//$NON-NLS-1$
AptPlugin.trace("AptProject.projectDeleted cleaning state for project " + _javaProject.getElementName());
_gfm.projectDeleted();
}
}
|
9236355cd6d65b94db39eab9156052e2dce9f856 | 5,128 | java | Java | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/lottie/LottieAnimationViewPropertyManager.java | ahmadtech199/expo | b35f4713789b48c8ba72d7abe7089e5dfa031c41 | [
"Apache-2.0",
"MIT"
] | 16,461 | 2017-03-24T19:59:01.000Z | 2022-03-31T21:52:45.000Z | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/lottie/LottieAnimationViewPropertyManager.java | ahmadtech199/expo | b35f4713789b48c8ba72d7abe7089e5dfa031c41 | [
"Apache-2.0",
"MIT"
] | 13,016 | 2017-03-25T22:49:31.000Z | 2022-03-31T23:23:58.000Z | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/lottie/LottieAnimationViewPropertyManager.java | ahmadtech199/expo | b35f4713789b48c8ba72d7abe7089e5dfa031c41 | [
"Apache-2.0",
"MIT"
] | 3,945 | 2017-03-25T07:12:57.000Z | 2022-03-31T20:55:18.000Z | 30.52381 | 99 | 0.717434 | 997,585 | package abi42_0_0.host.exp.exponent.modules.api.components.lottie;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.widget.ImageView;
import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieDrawable;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.RenderMode;
import com.airbnb.lottie.SimpleColorFilter;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.value.LottieValueCallback;
import abi42_0_0.com.facebook.react.bridge.ReadableArray;
import abi42_0_0.com.facebook.react.bridge.ReadableMap;
import java.lang.ref.WeakReference;
import java.util.regex.Pattern;
/**
* Class responsible for applying the properties to the LottieView.
* The way react-native works makes it impossible to predict in which order properties will be set,
* also some of the properties of the LottieView needs to be set simultaneously.
*
* To solve this, instance of this class accumulates all changes to the view and applies them at
* the end of react transaction, so it could control how changes are applied.
*/
public class LottieAnimationViewPropertyManager {
private final WeakReference<LottieAnimationView> viewWeakReference;
private String animationJson;
private Float progress;
private Boolean loop;
private Float speed;
/**
* Should be set to true if one of the animationName related parameters has changed as a result
* of last reconciliation. We need to update the animation in this case.
*/
private boolean animationNameDirty;
private String animationName;
private ImageView.ScaleType scaleType;
private String imageAssetsFolder;
private Boolean enableMergePaths;
private ReadableArray colorFilters;
private RenderMode renderMode;
public LottieAnimationViewPropertyManager(LottieAnimationView view) {
this.viewWeakReference = new WeakReference<>(view);
}
public void setAnimationName(String animationName) {
this.animationName = animationName;
this.animationNameDirty = true;
}
public void setAnimationJson(String json) {
this.animationJson = json;
}
public void setProgress(Float progress) {
this.progress = progress;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public void setLoop(boolean loop) {
this.loop = loop;
}
public void setScaleType(ImageView.ScaleType scaleType) {
this.scaleType = scaleType;
}
public void setRenderMode(RenderMode renderMode) {
this.renderMode = renderMode;
}
public void setImageAssetsFolder(String imageAssetsFolder) {
this.imageAssetsFolder = imageAssetsFolder;
}
public void setEnableMergePaths(boolean enableMergePaths) {
this.enableMergePaths = enableMergePaths;
}
public void setColorFilters(ReadableArray colorFilters) {
this.colorFilters = colorFilters;
}
/**
* Updates the view with changed fields.
* Majority of the properties here are independent so they are has to be reset to null
* as soon as view is updated with the value.
*
* The only exception from this rule is the group of the properties for the animation.
* For now this is animationName and cacheStrategy. These two properties are should be set
* simultaneously if the dirty flag is set.
*/
public void commitChanges() {
LottieAnimationView view = viewWeakReference.get();
if (view == null) {
return;
}
if (animationJson != null) {
view.setAnimationFromJson(animationJson, Integer.toString(animationJson.hashCode()));
animationJson = null;
}
if (animationNameDirty) {
view.setAnimation(animationName);
animationNameDirty = false;
}
if (progress != null) {
view.setProgress(progress);
progress = null;
}
if (loop != null) {
view.setRepeatCount(loop ? LottieDrawable.INFINITE : 0);
loop = null;
}
if (speed != null) {
view.setSpeed(speed);
speed = null;
}
if (scaleType != null) {
view.setScaleType(scaleType);
scaleType = null;
}
if (renderMode != null) {
view.setRenderMode(renderMode);
renderMode = null;
}
if (imageAssetsFolder != null) {
view.setImageAssetsFolder(imageAssetsFolder);
imageAssetsFolder = null;
}
if (enableMergePaths != null) {
view.enableMergePathsForKitKatAndAbove(enableMergePaths);
enableMergePaths = null;
}
if (colorFilters != null && colorFilters.size() > 0) {
for (int i = 0 ; i < colorFilters.size() ; i++) {
ReadableMap current = colorFilters.getMap(i);
String color = current.getString("color");
String path = current.getString("keypath");
SimpleColorFilter colorFilter = new SimpleColorFilter(Color.parseColor(color));
String pathWithGlobstar = path +".**";
String[] keys = pathWithGlobstar.split(Pattern.quote("."));
KeyPath keyPath = new KeyPath(keys);
LottieValueCallback<ColorFilter> callback = new LottieValueCallback<>(colorFilter);
view.addValueCallback(keyPath, LottieProperty.COLOR_FILTER, callback);
}
}
}
}
|
923635c09a2b8c9fcf1b286a6164949e72f4a272 | 226 | java | Java | gmall-pms/src/main/java/com/atguigu/gmall/pms/feign/PmsToSms.java | lvym-web/gmall-2020 | 3d7c1eff913435aae32ee917afa2d2d150fca506 | [
"Apache-2.0"
] | null | null | null | gmall-pms/src/main/java/com/atguigu/gmall/pms/feign/PmsToSms.java | lvym-web/gmall-2020 | 3d7c1eff913435aae32ee917afa2d2d150fca506 | [
"Apache-2.0"
] | 2 | 2021-03-19T20:25:07.000Z | 2021-04-22T17:11:16.000Z | gmall-pms/src/main/java/com/atguigu/gmall/pms/feign/PmsToSms.java | lvym-web/gmall-2020 | 3d7c1eff913435aae32ee917afa2d2d150fca506 | [
"Apache-2.0"
] | null | null | null | 20.545455 | 55 | 0.814159 | 997,586 | package com.atguigu.gmall.pms.feign;
import com.atguigu.gmall.sms.api.PmsToSmsServer;
import org.springframework.cloud.openfeign.FeignClient;
@FeignClient("sms-server")
public interface PmsToSms extends PmsToSmsServer {
}
|
9236362759aee32b581fbca3d63ef320f7b4420c | 925 | java | Java | starter-core/src/main/java/by/gdev/settings/SettingsManager.java | robertmakrytski/desktop-starter | 78bc3938dce22e7b735e862d1c163b2ad433130b | [
"MIT"
] | null | null | null | starter-core/src/main/java/by/gdev/settings/SettingsManager.java | robertmakrytski/desktop-starter | 78bc3938dce22e7b735e862d1c163b2ad433130b | [
"MIT"
] | null | null | null | starter-core/src/main/java/by/gdev/settings/SettingsManager.java | robertmakrytski/desktop-starter | 78bc3938dce22e7b735e862d1c163b2ad433130b | [
"MIT"
] | null | null | null | 27.205882 | 103 | 0.717838 | 997,587 | package by.gdev.settings;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.Data;
import java.io.InputStream;
import java.io.InputStreamReader;
@Data
public class SettingsManager {
private static SettingsManager instance;
private String configUrl;
private int connectionTimeout;
public SettingsManager() {
//load settings.json
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classloader.getResourceAsStream("settings.json");
JsonObject json = JsonParser.parseReader(new InputStreamReader(inputStream)).getAsJsonObject();
//get values
configUrl = json.get("configUrl").getAsString();
connectionTimeout = json.get("connectionTimeout").getAsInt();
instance = this;
}
public static SettingsManager getInstance() {
return instance;
}
}
|
92363632830aee1010fd806d6f98ee5f8523e85e | 3,767 | java | Java | src/main/java/org/elasticsearch/plugin/ingest/library/LibraryClient.java | bLozanoUPM/ingest-library | fbc306e9727b0876960ce2bb236cc27d0792558e | [
"Apache-2.0"
] | null | null | null | src/main/java/org/elasticsearch/plugin/ingest/library/LibraryClient.java | bLozanoUPM/ingest-library | fbc306e9727b0876960ce2bb236cc27d0792558e | [
"Apache-2.0"
] | null | null | null | src/main/java/org/elasticsearch/plugin/ingest/library/LibraryClient.java | bLozanoUPM/ingest-library | fbc306e9727b0876960ce2bb236cc27d0792558e | [
"Apache-2.0"
] | null | null | null | 40.074468 | 120 | 0.597027 | 997,588 | /*
* Copyright [2018] [Borja Lozano Álvarez]
*
* 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.elasticsearch.plugin.ingest.library;
import org.elasticsearch.SpecialPermission;
import org.elasticsearch.common.SuppressForbidden;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
final class LibraryClient {
@SuppressForbidden(reason="Access PTM model hosted in remote server")
static JSONObject projectDoc(String model,String doc) throws IOException,PrivilegedActionException {
// check that its not unprivileged code like a script
SpecialPermission.check();
String endpoint = "http://librairy.linkeddata.es/"+model+"/inferences";
StringBuilder content = new StringBuilder();
JSONObject body = new JSONObject();
body.put("text",doc);
body.put("topics",true);
return AccessController.doPrivileged((PrivilegedExceptionAction<JSONObject>)
() -> {
try {
URL url = new URL(endpoint);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestProperty("Accept", "application/json");
DataOutputStream wr = new DataOutputStream(httpConnection.getOutputStream());
wr.write(body.toString().getBytes());
Integer responseCode = httpConnection.getResponseCode();
BufferedReader bufferedReader;
// Creates a reader buffer
if (responseCode > 199 && responseCode < 300) {
bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
} else {
bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream()));
}
// To receive the response
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line).append("\n");
}
bufferedReader.close();
return new JSONObject(content.toString());
}catch(Exception e){
Throwable cause = e.getCause();
if(cause instanceof PrivilegedActionException) {
throw (PrivilegedActionException) cause;
} else {
throw new AssertionError(cause);
}
}
}
);
}
}
|
923636ae001c845feb86d1c7ddce4cc548660d7f | 151 | java | Java | src/main/java/com/yusuf/bentenmod/client/Keybindings.java | vemerion/Ben-10-Mod | a7a067b53aa47b5986549ae6052610e72d1000bb | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/yusuf/bentenmod/client/Keybindings.java | vemerion/Ben-10-Mod | a7a067b53aa47b5986549ae6052610e72d1000bb | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/yusuf/bentenmod/client/Keybindings.java | vemerion/Ben-10-Mod | a7a067b53aa47b5986549ae6052610e72d1000bb | [
"BSD-3-Clause"
] | null | null | null | 16.777778 | 48 | 0.807947 | 997,589 | package com.yusuf.bentenmod.client;
import net.minecraft.client.settings.KeyBinding;
public class Keybindings {
public static KeyBinding RELOAD;
}
|
923637f0ae94fadf4dbd6b6964de20a799597e26 | 2,188 | java | Java | domino-ui/src/main/java/org/dominokit/domino/ui/forms/TextBox.java | hpehl/domino-ui | 79cad6ece414d03676ac0e1c288f0bd37201fea9 | [
"Apache-2.0"
] | null | null | null | domino-ui/src/main/java/org/dominokit/domino/ui/forms/TextBox.java | hpehl/domino-ui | 79cad6ece414d03676ac0e1c288f0bd37201fea9 | [
"Apache-2.0"
] | null | null | null | domino-ui/src/main/java/org/dominokit/domino/ui/forms/TextBox.java | hpehl/domino-ui | 79cad6ece414d03676ac0e1c288f0bd37201fea9 | [
"Apache-2.0"
] | null | null | null | 23.276596 | 82 | 0.625686 | 997,590 | package org.dominokit.domino.ui.forms;
import elemental2.dom.HTMLInputElement;
import org.dominokit.domino.ui.forms.validations.InputAutoValidator;
import org.jboss.elemento.Elements;
import static java.util.Objects.nonNull;
public class TextBox extends AbstractValueBox<TextBox, HTMLInputElement, String> {
private static final String TEXT = "text";
private boolean emptyAsNull;
public TextBox() {
this(TEXT, "");
}
public TextBox(String label) {
this(TEXT, label);
}
public TextBox(String type, String label) {
super(type, label);
}
public static TextBox create() {
return new TextBox();
}
public static TextBox create(String label) {
return new TextBox(label);
}
public static TextBox password(String label) {
return new TextBox("password", label);
}
public static TextBox password() {
return new TextBox("password", "");
}
@Override
protected HTMLInputElement createInputElement(String type) {
return Elements.input(type).element();
}
@Override
protected void clearValue() {
value("");
}
@Override
protected void doSetValue(String value) {
if (nonNull(value)) {
getInputElement().element().value = value;
} else {
getInputElement().element().value = "";
}
}
@Override
public String getValue() {
String value = getInputElement().element().value;
if (value.isEmpty() && isEmptyAsNull()) {
return null;
}
return value;
}
public TextBox setType(String type) {
getInputElement().element().type = type;
return this;
}
@Override
public String getStringValue() {
return getValue();
}
public TextBox setEmptyAsNull(boolean emptyAsNull) {
this.emptyAsNull = emptyAsNull;
return this;
}
public boolean isEmptyAsNull() {
return emptyAsNull;
}
@Override
protected AutoValidator createAutoValidator(AutoValidate autoValidate) {
return new InputAutoValidator<>(getInputElement(), autoValidate);
}
}
|
9236380e060d69ed200a07acd9cfacfffd13ee32 | 3,082 | java | Java | Android/java/doraemonkit/src/main/java/com/didichuxing/doraemonkit/aop/OkHttpHook.java | liushilong08/DoraemonKit | 727cd5b5328447565a7be4b2ae33128ebb9041ac | [
"Apache-2.0"
] | 27 | 2020-05-29T07:50:32.000Z | 2021-07-20T01:46:16.000Z | Android/java/doraemonkit/src/main/java/com/didichuxing/doraemonkit/aop/OkHttpHook.java | liushilong08/DoraemonKit | 727cd5b5328447565a7be4b2ae33128ebb9041ac | [
"Apache-2.0"
] | 1 | 2020-07-29T08:52:54.000Z | 2020-07-29T08:52:54.000Z | Android/java/doraemonkit/src/main/java/com/didichuxing/doraemonkit/aop/OkHttpHook.java | liushilong08/DoraemonKit | 727cd5b5328447565a7be4b2ae33128ebb9041ac | [
"Apache-2.0"
] | 9 | 2020-09-15T09:24:46.000Z | 2021-07-06T10:46:29.000Z | 30.82 | 106 | 0.645036 | 997,591 | package com.didichuxing.doraemonkit.aop;
import android.util.Log;
import com.blankj.utilcode.util.ReflectUtils;
import com.didichuxing.doraemonkit.kit.network.okhttp.interceptor.DoraemonInterceptor;
import com.didichuxing.doraemonkit.kit.network.okhttp.interceptor.DoraemonWeakNetworkInterceptor;
import com.didichuxing.doraemonkit.kit.network.okhttp.interceptor.LargePictureInterceptor;
import com.didichuxing.doraemonkit.kit.network.okhttp.interceptor.MockInterceptor;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-12-13-10:40
* 描 述:用来通过ASM在编译器进行hook
* 修订历史:
* ================================================
*/
public class OkHttpHook {
// 每个拦截器都有自己的相对优点。
// 应用拦截器
// 不需要担心中间响应,如重定向和重试。
// 总是调用一次,即使从缓存提供HTTP响应。
// 遵守应用程序的原始意图。
// 不注意OkHttp注入的头像If-None-Match。
// 允许短路和不通话Chain.proceed()。
// 允许重试并进行多次呼叫Chain.proceed()。
// 网络拦截器
// 能够对重定向和重试等中间响应进行操作。
// 不调用缓存的响应来短路网络。
// 观察数据,就像通过网络传输一样。
// 访问Connection该请求。
public static List<Interceptor> globalInterceptors = new ArrayList<>();
public static List<Interceptor> globalNetworkInterceptors = new ArrayList<>();
private static boolean IS_INSTALL = false;
public static void installInterceptor() {
if (IS_INSTALL) {
return;
}
try {
//可能存在用户没有引入okhttp的情况
globalInterceptors.add(new MockInterceptor());
globalInterceptors.add(new LargePictureInterceptor());
globalInterceptors.add(new DoraemonInterceptor());
globalNetworkInterceptors.add(new DoraemonWeakNetworkInterceptor());
IS_INSTALL = true;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param builder 真实的对象为okHttpClient.Builder
* @param okHttpClient 真实的对象为okHttpClient
*/
public static void performOkhttpOneParamBuilderInit(Object builder, Object okHttpClient) {
try {
if (builder instanceof OkHttpClient.Builder) {
OkHttpClient.Builder localBuild = (OkHttpClient.Builder) builder;
List<Interceptor> interceptors = removeDuplicate(localBuild.interceptors());
List<Interceptor> networkInterceptors = removeDuplicate(localBuild.networkInterceptors());
ReflectUtils.reflect(localBuild).field("interceptors", interceptors);
ReflectUtils.reflect(localBuild).field("networkInterceptors", networkInterceptors);
}
} catch (Exception e) {
Log.i("Doraemon", "" + e.getMessage());
}
}
/**
* 保证顺序并去重
*
* @param list
* @return
*/
private static List<Interceptor> removeDuplicate(List<Interceptor> list) {
//保证顺序并去重
LinkedHashSet h = new LinkedHashSet<Interceptor>(list);
list.clear();
list.addAll(h);
return list;
}
}
|
92363856bc97e4ff60295c6230cadc8130cf2532 | 113 | java | Java | src/main/java/com/derdiedas/authentication/package-info.java | dufernandes/derdiedas | 738d60d5ed333dfb139006d1bc5bf8e14013b721 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/derdiedas/authentication/package-info.java | dufernandes/derdiedas | 738d60d5ed333dfb139006d1bc5bf8e14013b721 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/derdiedas/authentication/package-info.java | dufernandes/derdiedas | 738d60d5ed333dfb139006d1bc5bf8e14013b721 | [
"Apache-2.0"
] | null | null | null | 18.833333 | 50 | 0.725664 | 997,592 | /**
* Holds authentication and authorication classes.
*
* @since 1.0
*/
package com.derdiedas.authentication; |
923638c23d6b2f846033d859c3c814b49f4cd726 | 701 | java | Java | shop-security/src/main/java/com/sunny/security/config/SecuritySessionUtils.java | tec-feng/saas-shop | a040a54169541481a03830edba7f91cf15931284 | [
"Apache-2.0"
] | 2 | 2020-06-03T05:39:08.000Z | 2020-06-30T00:38:03.000Z | shop-security/src/main/java/com/sunny/security/config/SecuritySessionUtils.java | tec-feng/saas-shop | a040a54169541481a03830edba7f91cf15931284 | [
"Apache-2.0"
] | 3 | 2020-04-30T16:49:04.000Z | 2021-06-04T22:09:55.000Z | shop-security/src/main/java/com/sunny/security/config/SecuritySessionUtils.java | tec-feng/saas-shop | a040a54169541481a03830edba7f91cf15931284 | [
"Apache-2.0"
] | 2 | 2020-10-16T05:46:33.000Z | 2022-01-09T04:10:06.000Z | 29.208333 | 84 | 0.766049 | 997,593 | package com.sunny.security.config;
import com.sunny.user.model.SecurityUserDetails;
import com.sunny.user.model.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* @author tec_feng
* @create 2020-05-21 18:43
*/
public class SecuritySessionUtils {
public static User getLoginUser(){
SecurityContext ctx = SecurityContextHolder.getContext();
Authentication auth = ctx.getAuthentication();
SecurityUserDetails userDetails = (SecurityUserDetails) auth.getPrincipal();
return userDetails.getUser();
}
}
|
9236395df05581d0bd0296c9dcc601d04bca38e7 | 7,979 | java | Java | src/com/t0ast/xdocroot/ui/SettingsPanel.java | T0astBread/XDocRoot | 152e3bb153a8842c6a7f49cf709ce86f517cd096 | [
"MIT"
] | null | null | null | src/com/t0ast/xdocroot/ui/SettingsPanel.java | T0astBread/XDocRoot | 152e3bb153a8842c6a7f49cf709ce86f517cd096 | [
"MIT"
] | null | null | null | src/com/t0ast/xdocroot/ui/SettingsPanel.java | T0astBread/XDocRoot | 152e3bb153a8842c6a7f49cf709ce86f517cd096 | [
"MIT"
] | null | null | null | 41.774869 | 170 | 0.655972 | 997,594 | /*
* For license information please see LICENSE.txt
*/
package com.t0ast.xdocroot.ui;
import com.t0ast.swingutils.DialogUtils;
import com.t0ast.swingutils.ui.LinkLabelAddon;
import com.t0ast.swingutils.ui.licensing.mit.MitLicenseInformationDialog;
import com.t0ast.xdocroot.config.Config;
import java.awt.Dialog;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
/**
*
* @author T0astBread
*/
public class SettingsPanel extends javax.swing.JPanel
{
private Config config;
private JFileChooser confFileChooser;
/**
* Creates new form Settings
*/
public SettingsPanel()
{
initComponents();
this.confFileChooser = new JFileChooser("C:/xampp/apache/conf/httpd.conf");
this.confFileChooser.setAcceptAllFileFilterUsed(false);
this.confFileChooser.addChoosableFileFilter(new FileFilter()
{
@Override
public boolean accept(File f)
{
return f.isDirectory() || f.getName().equals("httpd.conf");
}
@Override
public String getDescription()
{
return "Apache Module Configuration File (httpd.conf)";
}
});
this.btnConfigFileSelect.addActionListener(evt ->
{
if(this.confFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
this.txtConfigFilePath.setText(this.confFileChooser.getSelectedFile().getAbsolutePath());
});
this.btnSave.addActionListener(evt ->
{
config.configFilePath = this.txtConfigFilePath.getText();
btnCancel.getActionListeners()[0].actionPerformed(null);
});
this.btnCancel.addActionListener(evt -> SwingUtilities.getWindowAncestor(this).dispose());
LinkLabelAddon.applyTo(this.lblLicenseInfo, this::showLicenseInfoDialog);
}
private void showLicenseInfoDialog()
{
JDialog licenseDialog = new MitLicenseInformationDialog(SwingUtilities.getWindowAncestor(this));
licenseDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
licenseDialog.pack();
licenseDialog.setLocationRelativeTo(this);
licenseDialog.setVisible(true);
}
public JButton getBtnSave()
{
return btnSave;
}
public SettingsPanel setConfig(Config config)
{
this.config = config;
this.txtConfigFilePath.setText(config.configFilePath);
return this;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents()
{
lblHeader = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
btnConfigFileSelect = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
txtConfigFilePath = new javax.swing.JTextField();
btnCancel = new javax.swing.JButton();
btnSave = new javax.swing.JButton();
lblLicenseInfo = new javax.swing.JLabel();
lblHeader.setFont(new java.awt.Font("Dialog", 0, 36)); // NOI18N
lblHeader.setText("Settings");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Apache"));
btnConfigFileSelect.setText("Select");
jLabel2.setText("Config File:");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtConfigFilePath)
.addGap(4, 4, 4)
.addComponent(btnConfigFileSelect)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtConfigFilePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnConfigFileSelect))
.addContainerGap())
);
btnCancel.setText("Cancel");
btnSave.setText("Save");
lblLicenseInfo.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
lblLicenseInfo.setText("License Information");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblHeader)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(lblLicenseInfo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 150, Short.MAX_VALUE)
.addComponent(btnSave)
.addGap(0, 0, 0)
.addComponent(btnCancel)))
.addGap(12, 12, 12))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(lblHeader)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnCancel)
.addComponent(btnSave))
.addComponent(lblLicenseInfo, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(12, 12, 12))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnConfigFileSelect;
private javax.swing.JButton btnSave;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel lblHeader;
private javax.swing.JLabel lblLicenseInfo;
private javax.swing.JTextField txtConfigFilePath;
// End of variables declaration//GEN-END:variables
}
|
92363968f4cc7720757201b7905a273585627866 | 1,518 | java | Java | librarycalendar/src/main/java/com/joybar/librarycalendar/data/CalendarDate.java | myjoybar/android-calendar-view | eb8c30045cde59919bfa2bd4d043380eb161efd9 | [
"Apache-2.0"
] | 473 | 2016-09-14T05:17:52.000Z | 2022-01-18T09:05:10.000Z | librarycalendar/src/main/java/com/joybar/librarycalendar/data/CalendarDate.java | Bryce-Fitzgerald/android-calendar-view | eb8c30045cde59919bfa2bd4d043380eb161efd9 | [
"Apache-2.0"
] | 6 | 2016-09-29T04:32:51.000Z | 2020-07-23T14:05:32.000Z | librarycalendar/src/main/java/com/joybar/librarycalendar/data/CalendarDate.java | Bryce-Fitzgerald/android-calendar-view | eb8c30045cde59919bfa2bd4d043380eb161efd9 | [
"Apache-2.0"
] | 99 | 2016-09-19T09:25:51.000Z | 2022-01-22T02:12:35.000Z | 22.656716 | 109 | 0.632411 | 997,595 | package com.joybar.librarycalendar.data;
/**
* Created by joybar on 2/24/16.
*/
public class CalendarDate {
private Lunar lunar = new Lunar();//农历
private Solar solar = new Solar();//公历
private boolean isInThisMonth; //是否在当月
private boolean isSelect;//是否被选中
public CalendarDate(int year, int month, int day, boolean isInThisMonth, boolean isSelect, Lunar lunar) {
this.isInThisMonth = isInThisMonth;
this.isSelect = isSelect;
this.lunar = lunar;
}
public CalendarDate(boolean isInThisMonth, boolean isSelect, Solar solar, Lunar lunar) {
this.isInThisMonth = isInThisMonth;
this.isSelect = isSelect;
this.solar = solar;
this.lunar = lunar;
}
public boolean isInThisMonth() {
return isInThisMonth;
}
public void setIsInThisMonth(boolean isInThisMonth) {
this.isInThisMonth = isInThisMonth;
}
public boolean isSelect() {
return isSelect;
}
public void setIsSelect(boolean isSelect) {
this.isSelect = isSelect;
}
public Solar getSolar() {
return solar;
}
public void setSolar(Solar solar) {
this.solar = solar;
}
public void setInThisMonth(boolean inThisMonth) {
isInThisMonth = inThisMonth;
}
public void setSelect(boolean select) {
isSelect = select;
}
public Lunar getLunar() {
return lunar;
}
public void setLunar(Lunar lunar) {
this.lunar = lunar;
}
}
|
92363af0d08c1359128021c7b2aea2a4ea033c69 | 5,126 | java | Java | src/authoring/frontend/CreatePathPanel.java | eriis1024/Vooga-Salad | b0a9c3f7dd3422fad9ffded916da0a923e19bdd5 | [
"MIT"
] | null | null | null | src/authoring/frontend/CreatePathPanel.java | eriis1024/Vooga-Salad | b0a9c3f7dd3422fad9ffded916da0a923e19bdd5 | [
"MIT"
] | null | null | null | src/authoring/frontend/CreatePathPanel.java | eriis1024/Vooga-Salad | b0a9c3f7dd3422fad9ffded916da0a923e19bdd5 | [
"MIT"
] | null | null | null | 29.45977 | 211 | 0.730589 | 997,596 | package authoring.frontend;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
/**
* Class to create the righthand panel for the path authoring screen.
* @author Erik Riis
*
*/
public class CreatePathPanel extends PathPanel {
public static final int PANEL_PATH_SIZE = 90;
public static final int PANEL_WIDTH = 330;
public static final int PANEL_HEIGHT = 900;
public static final int TRASH_IMAGE_SIZE = 120;
public static final String TRASH_IMAGE = "file:images/trash.png";
public static final String DEFAULT_PATH_IMAGE = "file:images/cobblestone.png";
public static final String DEFAULT_START_IMAGE = "file:images/brick.png";
public static final String DEFAULT_END_IMAGE = "file:images/darkstone.png";
private VBox pathPanel;
private DraggableImage pathImage;
private DraggableImage startImage;
private DraggableImage endImage;
private Button applyButton;
private Button backButton;
private ImageView trashImage;
private boolean isTransparent;
public CreatePathPanel(AuthoringView view) {
super(view);
makeScreenWithoutStyling();
makePanel();
}
@Override
protected Button getApplyButton() {
return applyButton;
}
@Override
public Parent makeScreenWithoutStyling() {
pathPanel = new VBox();
pathPanel.setMaxSize(PANEL_WIDTH, PANEL_HEIGHT);
pathPanel.getStylesheets();
return pathPanel;
}
@Override
protected void makePanel() {
Label panelTitle = new Label("Drag and Drop Paths");
Label startLabel = new Label("Start:");
Label pathLabel = new Label("Path:");
Label endLabel = new Label("End:");
pathImage = new DraggableImage(new Image(DEFAULT_PATH_IMAGE));
pathImage.setCopyDraggable();
pathImage.getPathImage().setId(CreatePathGrid.PATH);
startImage = new DraggableImage(new Image(DEFAULT_START_IMAGE));
startImage.setCopyDraggable();
startImage.getPathImage().setId(CreatePathGrid.START);
endImage = new DraggableImage(new Image(DEFAULT_END_IMAGE));
endImage.setCopyDraggable();
endImage.getPathImage().setId(CreatePathGrid.END);
applyButton = getUIFactory().makeTextButton("", "Apply");
backButton = setupBackButton();
trashImage = new ImageView(new Image(TRASH_IMAGE, TRASH_IMAGE_SIZE, TRASH_IMAGE_SIZE, true, false));
ToggleGroup radioGroup = new ToggleGroup();
ToggleButton transparentToggle = new ToggleButton("Make Path Transparent");
transparentToggle.setToggleGroup(radioGroup);
radioGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>(){
public void changed(ObservableValue<? extends Toggle> ov,
Toggle toggle, Toggle new_toggle) {
if (new_toggle == null) {
isTransparent = false;
} else {
isTransparent = true;
}
}
});
pathPanel.getChildren().addAll(panelTitle, startLabel, startImage.getPathImage(), pathLabel, pathImage.getPathImage(), endLabel, endImage.getPathImage(), trashImage, transparentToggle, applyButton, backButton);
}
@Override
protected void setApplyButtonAction(EventHandler<ActionEvent> e) {
applyButton.setOnAction(
event -> {
setSaved();
e.handle(event);
});
}
@Override
protected Node getPanel() {
return pathPanel;
}
/**
* Creates the trash image in the panel that allows for dragging and dropping path blocks to delete them from the gridPane
* @return trashImage
*/
protected ImageView makeTrashImage() {
trashImage.setOnDragDropped(new EventHandler <DragEvent>() {
@Override
public void handle(DragEvent event) {
event.acceptTransferModes(TransferMode.ANY);
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasImage()) {
success = true;
}
event.setDropCompleted(success);
event.consume();
}
});
return trashImage;
}
/**
* gets a boolean that discerns if the user has toggled for the path blocks to be transparent in the Game Player
* @return isTransparent
*/
protected boolean getTransparent() {
return isTransparent;
}
/**
* Gets the DraggableImage that represents a path block
* @return pathImage
*/
protected DraggableImage getPanelPathImage() {
return pathImage;
}
/**
* Gets the DraggableImage that represents a start block
* @return startImage
*/
protected DraggableImage getPanelStartImage() {
return startImage;
}
/**
* Gets the DraggableImage that represents an end block
* @return endImage
*/
protected DraggableImage getPanelEndImage() {
return endImage;
}
}
|
92363b0806219868d041dc8434636af5cc8ce927 | 548 | java | Java | net/minecraft/scoreboard/ScoreCriteriaHealth.java | BantorSchwanzVor/plotscanner-leak | cbf130076159711d939affb4b0343c46c3466107 | [
"MIT"
] | null | null | null | net/minecraft/scoreboard/ScoreCriteriaHealth.java | BantorSchwanzVor/plotscanner-leak | cbf130076159711d939affb4b0343c46c3466107 | [
"MIT"
] | null | null | null | net/minecraft/scoreboard/ScoreCriteriaHealth.java | BantorSchwanzVor/plotscanner-leak | cbf130076159711d939affb4b0343c46c3466107 | [
"MIT"
] | null | null | null | 26.095238 | 147 | 0.717153 | 997,597 | package net.minecraft.scoreboard;
public class ScoreCriteriaHealth extends ScoreCriteria {
public ScoreCriteriaHealth(String name) {
super(name);
}
public boolean isReadOnly() {
return true;
}
public IScoreCriteria.EnumRenderType getRenderType() {
return IScoreCriteria.EnumRenderType.HEARTS;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\scoreboard\ScoreCriteriaHealth.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
92363bc252c16d06a5236f47397d5993946e1fab | 793 | java | Java | cooper-framework/cooper-framework-core/src/main/java/jdepend/framework/context/ClientContext.java | jdepend/cooper | baac23d8372a4ece5c103a815b2a573a55ee59cb | [
"Apache-2.0"
] | 9 | 2015-01-30T06:55:28.000Z | 2019-11-28T08:47:14.000Z | cooper-framework/cooper-framework-core/src/main/java/jdepend/framework/context/ClientContext.java | jdepend/cooper | baac23d8372a4ece5c103a815b2a573a55ee59cb | [
"Apache-2.0"
] | 3 | 2015-08-12T23:09:51.000Z | 2018-12-07T06:10:44.000Z | cooper-framework/cooper-framework-core/src/main/java/jdepend/framework/context/ClientContext.java | jdepend/cooper | baac23d8372a4ece5c103a815b2a573a55ee59cb | [
"Apache-2.0"
] | 7 | 2015-03-05T07:33:55.000Z | 2021-12-14T07:17:40.000Z | 21.432432 | 80 | 0.687264 | 997,598 | package jdepend.framework.context;
import java.net.InetAddress;
import java.net.UnknownHostException;
import jdepend.framework.context.Scope.SCOPE;
/**
* 客户端上下文
*
* @author wangdg
*
*/
public final class ClientContext {
private final static String CurrentUser = "CurrentUser";
public static String getUser() {
String user = (String) JDependContext.getInfo(SCOPE.APP_SCOPSE, CurrentUser);
if (user == null) {
try {
user = InetAddress.getLocalHost().getHostName();
JDependContext.setInfo(SCOPE.APP_SCOPSE, CurrentUser, user);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
return user;
}
public static void setUser(String user) {
JDependContext.setInfo(SCOPE.APP_SCOPSE, CurrentUser, user);
}
}
|
92363c1d149b6d7025171d872a229d0bec92ffea | 5,719 | java | Java | common-base/src/main/java/com/shuframework/commonbase/result/ResultUtil.java | shuframework/framework-common | 036cb612d52f06a89e9ee9b789fbb15cbbdce419 | [
"Apache-2.0"
] | null | null | null | common-base/src/main/java/com/shuframework/commonbase/result/ResultUtil.java | shuframework/framework-common | 036cb612d52f06a89e9ee9b789fbb15cbbdce419 | [
"Apache-2.0"
] | null | null | null | common-base/src/main/java/com/shuframework/commonbase/result/ResultUtil.java | shuframework/framework-common | 036cb612d52f06a89e9ee9b789fbb15cbbdce419 | [
"Apache-2.0"
] | null | null | null | 22.427451 | 84 | 0.592236 | 997,599 | package com.shuframework.commonbase.result;
import com.shuframework.commonbase.enums.FailureEnum;
import com.shuframework.commonbase.util.SystemUtil;
/**
* 返回结果的工具类,包含了错误码
*
* @author shuheng
*/
public class ResultUtil {
public static final int SUCCESS_CODE = 20000;
public static boolean SUCCESS_BOOL = true;
public static boolean FAILURE_BOOL = false;
// public static final String QUERY_OK = "QueryOk";
// public static final String ADD_OK = "AddOk";
// public static final String UPDATE_OK = "UpdateOk";
// public static final String DELETE_OK = "DeleteOk";
// public static final String OPERATE_OK = "OperateOk";
public static final String QUERY_OK = "查询成功";
public static final String ADD_OK = "添加成功";
public static final String UPDATE_OK = "修改成功";
public static final String DELETE_OK = "删除成功";
public static final String OPERATE_OK = "操作成功";
public static final String ADD_FAIL = "添加失败";
public static final String UPDATE_FAIL = "修改失败";
public static final String DELETE_FAIL = "删除失败";
/**
* 请求成功,返回msg,data为参数具体值
*
* @param msg
* @param data
* @return
*/
public static Result success(String msg, Object data) {
return new Result(SUCCESS_BOOL, SUCCESS_CODE, msg, data);
}
/**
* 请求成功,返回msg是"OPERATE_OK", data为参数具体值
*
* @param data
* @return
*/
public static Result success(Object data) {
// return new Result(SUCCESS_BOOL, SUCCESS_CODE, OPERATE_OK, data);
return success(OPERATE_OK, data);
}
/**
* 请求成功,返回data为null
*
* @return
*/
public static Result success() {
// return new Result(SUCCESS_BOOL, SUCCESS_CODE, OPERATE_OK);
return success(null);
}
/**
* 新增成功
* @param data
* @return
*/
public static Result insertSuccess(Object data) {
return success(ADD_OK, data);
}
/**
* 修改成功
* @param data
* @return
*/
public static Result updateSuccess(Object data) {
return success(UPDATE_OK, data);
}
/**
* 删除成功
* @param data
* @return
*/
public static Result deleteSuccess(Object data) {
return success(DELETE_OK, data);
}
/**
* 请求失败
*
* @param code
* @param msg
* @param data
* @return
*/
public static Result failure(int code, String msg, Object data) {
return new Result(FAILURE_BOOL, code, msg, data);
}
/**
* 请求失败
*
* @param failureEnum
* @param msg
* @return
*/
public static Result failure(FailureEnum failureEnum, String msg, Object data) {
int code = failureEnum.getCode();
if (SystemUtil.isEmpty(msg)){
msg = failureEnum.getMsg();
}
return new Result(FAILURE_BOOL, code, msg, data);
}
/**
* 请求失败
*
* @param failureEnum
* @param msg
* @return
*/
public static Result failure(FailureEnum failureEnum, String msg) {
return failure(failureEnum, msg, null);
}
/**
* 请求失败
*
* @param failureEnum
* @return
*/
public static Result failure(FailureEnum failureEnum) {
return failure(failureEnum, null);
}
/**
* 参数不能为空
*/
public static Result paramEmptyFailure() {
return failure(FailureEnum.PARAMETER_FAILURE, "参数不能为空");
}
/**
* name 不能为空
*/
public static Result paramEmptyFailure(String name) {
return failure(FailureEnum.PARAMETER_FAILURE, name + "不能为空");
}
/**
* 参数错误
* @param msg
*/
public static Result paramFailure(String msg) {
return failure(FailureEnum.PARAMETER_FAILURE, msg);
}
/**
* 记录已存在
*/
public static Result existFailure() {
return failure(FailureEnum.EXISTS_FAILURE);
}
/**
* 已存在
* @param msg
*/
public static Result existFailure(String msg) {
return failure(FailureEnum.EXISTS_FAILURE, msg);
}
/**
* 记录不存在
*/
public static Result notExistFailure() {
return failure(FailureEnum.NOTEXIST_FAILURE);
}
/**
* 不存在
* @param msg
*/
public static Result notExistFailure(String msg) {
return failure(FailureEnum.NOTEXIST_FAILURE, msg);
}
/**
* 新增失败
* @return
*/
public static Result insertFailure(Object data) {
return failure(FailureEnum.OPERATION_FAILURE, ADD_FAIL, data);
}
/**
* 修改失败
* @param data
* @return
*/
public static Result updateFailure(Object data) {
return failure(FailureEnum.OPERATION_FAILURE, UPDATE_FAIL, data);
}
/**
* 删除成功
* @param data
* @return
*/
public static Result deleteFailure(Object data) {
return failure(FailureEnum.OPERATION_FAILURE, DELETE_FAIL, data);
}
/**
* 请求出错
*
* @param failureEnum
* @param data
* @return
*/
public static Result error(FailureEnum failureEnum, Object data) {
int code = failureEnum.getCode();
String msg = failureEnum.getMsg();
return new Result(FAILURE_BOOL, code, msg, data);
}
/**
* 请求出错
*
* @param failureEnum
* @return
*/
public static Result error(FailureEnum failureEnum) {
return error(failureEnum, null);
}
/**
* 未知错误
*
* @return
*/
public static Result unknownError() {
return error(FailureEnum.UNKNOWN_ERROR);
}
/**
* 未知错误
*
* @param data
* @return
*/
public static Result unknownError(Object data) {
return error(FailureEnum.UNKNOWN_ERROR, data);
}
}
|
92363c7333bb478a5eaa52390ff67d57447c5337 | 15,885 | java | Java | osgi/bundles/desktop/src/org/knopflerfish/bundle/desktop/prefs/JPrefsTree.java | knopflerfish/knopflerfish.org | 1d70bbf651a1c509486d2cb39294ea78bb1b45b1 | [
"BSD-3-Clause"
] | 31 | 2015-12-09T08:02:10.000Z | 2022-03-22T16:20:23.000Z | osgi/bundles/desktop/src/org/knopflerfish/bundle/desktop/prefs/JPrefsTree.java | knopflerfish/knopflerfish.org | 1d70bbf651a1c509486d2cb39294ea78bb1b45b1 | [
"BSD-3-Clause"
] | 55 | 2016-04-13T09:41:30.000Z | 2022-01-27T13:52:47.000Z | osgi/bundles/desktop/src/org/knopflerfish/bundle/desktop/prefs/JPrefsTree.java | knopflerfish/knopflerfish.org | 1d70bbf651a1c509486d2cb39294ea78bb1b45b1 | [
"BSD-3-Clause"
] | 11 | 2015-12-09T08:02:18.000Z | 2022-01-07T10:51:17.000Z | 28.065371 | 103 | 0.58571 | 997,600 | /*
* Copyright (c) 2008-2013, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project 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 OWNER 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.
*/
package org.knopflerfish.bundle.desktop.prefs;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.util.prefs.*;
import java.util.*;
import java.io.*;
import org.knopflerfish.bundle.desktop.swing.Activator;
/**
* JTree that display display/edit a Preferences node and its sub-nodes.
*/
public class JPrefsTree extends JTree {
private static final long serialVersionUID = 1L;
JPopupMenu popup;
Collection<JMenuItem> menuItemsRO = new HashSet<JMenuItem>();
String rootName = "Preferences";
public JPrefsTree() {
super();
setModel(new PrefsTreeModel(null, rootName));
// To get icons and tooltips
setCellRenderer(new PrefsTreeRenderer());
ToolTipManager.sharedInstance().registerComponent(this);
addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent event) {
// log.info("collapsed " + event.getPath());
}
public void treeExpanded(TreeExpansionEvent event) {
onExpand(event.getPath());
}
});
popup = new JPopupMenu();
JMenuItem mi;
mi = new JMenuItem("Search...") {
private static final long serialVersionUID = 1L;
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
doSearch();
}
});
}
};
popup.add(mi);
mi = new JMenuItem("New node...") {
private static final long serialVersionUID = 1L;
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
doCreate();
}
});
}
};
menuItemsRO.add(mi);
popup.add(mi);
mi = new JMenuItem("New key...") {
private static final long serialVersionUID = 1L;
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
doAddKey();
}
});
}
};
menuItemsRO.add(mi);
popup.add(mi);
mi = new JMenuItem("Remove this node") {
private static final long serialVersionUID = 1L;
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
doRemove();
}
});
}
};
menuItemsRO.add(mi);
popup.add(mi);
mi = new JMenuItem("Sync") {
private static final long serialVersionUID = 1L;
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
doSync();
}
});
}
};
menuItemsRO.add(mi);
popup.add(mi);
mi = new JMenuItem("Flush") {
private static final long serialVersionUID = 1L;
{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
doFlush();
}
});
}
};
menuItemsRO.add(mi);
popup.add(mi);
popup.add(new JPopupMenu.Separator());
// mi = new JMenuItem("Export this node as XML...") {
// private static final long serialVersionUID = 1L;
//
// {
// addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent ev) {
// doExport();
// }
// });
// }
// };
// popup.add(mi);
// mi = new JMenuItem("Import XML...") {
// private static final long serialVersionUID = 1L;
//
// {
// addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent ev) {
// doImport();
// }
// });
// }
// };
// menuItemsRO.add(mi);
// popup.add(mi);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
return;
}
TreePath tp = getPathForLocation(e.getX(), e.getY());
if(tp != null) {
setSelectionPath(tp);
}
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
Preferences node;
public void setPreferences(Preferences node) {
this.node = node;
setModel(new PrefsTreeModel(node, rootName));
}
JFileChooser fc;
void doImport() {
if(fc == null) {
fc = new JFileChooser();
fc.setCurrentDirectory(new File(System.getProperty("user.dir", ".")));
}
fc.setDialogTitle("Import preferences XML");
fc.setApproveButtonText("Import");
int returnVal = fc.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
try {
InputStream in = new FileInputStream(fc.getSelectedFile());
Preferences.importPreferences(in);
setPreferences(node);
Activator.log.info("imported " + fc.getSelectedFile());
} catch (Exception e) {
Activator.log.warn("Failed to load", e);
}
}
}
public void setEditable(boolean b) {
super.setEditable(b);
for(Iterator<JMenuItem> it = menuItemsRO.iterator(); it.hasNext(); ) {
JMenuItem mi = it.next();
mi.setEnabled(b);
}
}
void doSearch() {
String name = JOptionPane.showInputDialog(this,
"Search for node or value",
"Search",
JOptionPane.OK_CANCEL_OPTION);
if(name == null || "".equals(name)) {
return;
}
searchAndExpand(name, 30);
}
public void searchAndExpand(String name, int maxLevel) {
try {
Collection<TreePath> paths = new LinkedHashSet<TreePath>();
TreePath tp = new TreePath(getModel().getRoot());
search(tp, paths, name.toLowerCase(), true, 0, maxLevel);
TreeUtils.expandPaths(this, paths);
} catch (Exception e) {
Activator.log.warn("Failed to search", e);
}
}
void search(TreePath tp, Collection<TreePath> paths,
String q,
boolean bMatchValues,
int level,
int maxLevel) throws BackingStoreException {
// guard against very deep trees
if(level > maxLevel) {
return;
}
Object obj = tp.getLastPathComponent();
if(!(obj instanceof PrefsTreeNode)) {
return;
}
PrefsTreeNode node = (PrefsTreeNode)obj;
node.assertLoad();
Preferences p = node.getPrefs();
if(-1 != p.name().toLowerCase().indexOf(q)) {
paths.add(tp);
}
String[] keys = p.keys();
for(int i = 0; i < keys.length; i++) {
if(-1 != keys[i].toLowerCase().indexOf(q)) {
paths.add(tp);
}
if(bMatchValues) {
String val = p.get(keys[i], null);
if(val != null && (-1 != val.toLowerCase().indexOf(q))) {
paths.add(tp);
}
}
}
for(Enumeration<?> e = node.children(); e.hasMoreElements(); ) {
Object child = e.nextElement();
search(tp.pathByAddingChild(child), paths, q, bMatchValues, level + 1, maxLevel);
}
}
void doCreate() {
TreePath tp = getSelectionPath();
if(tp == null) {
return;
}
try {
PrefsTreeNode node = (PrefsTreeNode)tp.getLastPathComponent();
String name = JOptionPane.showInputDialog(this,
"New node name",
"New node...",
JOptionPane.YES_NO_OPTION);
if(name != null && !"".equals(name)) {
Collection<TreePath> oldPaths = TreeUtils.getExpandedPaths(this);
Preferences p = node.getPrefs().node(name);
PrefsTreeNode pNode = new PrefsTreeNode(p);
oldPaths.add(tp);
oldPaths.add(tp.pathByAddingChild(pNode));
node.getPrefs().sync();
node.rescan();
setModel(getModel());
TreeUtils.expandPaths(this, oldPaths);
}
} catch (Exception e) {
Activator.log.warn("Failed to create", e);
}
}
void doSync() {
TreePath tp = getSelectionPath();
if(tp == null) {
return;
}
try {
Collection<TreePath> oldPaths = TreeUtils.getExpandedPaths(this);
PrefsTreeNode node = (PrefsTreeNode)tp.getLastPathComponent();
node.getPrefs().sync();
node.rescan();
setModel(getModel());
TreeUtils.expandPaths(this, oldPaths);
} catch (Exception e) {
Activator.log.warn("Failed to sync", e);
}
}
void doFlush() {
TreePath tp = getSelectionPath();
if(tp == null) {
return;
}
try {
PrefsTreeNode node = (PrefsTreeNode)tp.getLastPathComponent();
node.getPrefs().flush();
} catch (Exception e) {
Activator.log.warn("Failed to flush", e);
}
}
void doRemove() {
TreePath tp = getSelectionPath();
if(tp == null) {
return;
}
try {
PrefsTreeNode node = (PrefsTreeNode)tp.getLastPathComponent();
Collection<TreePath> oldPaths = TreeUtils.getExpandedPaths(this);
node.getPrefs().removeNode();
setModel(getModel());
TreeUtils.expandPaths(this, oldPaths);
} catch (Exception e) {
Activator.log.warn("Failed to create", e);
}
}
protected void doAddKey() {
TreePath tp = getSelectionPath();
if(tp == null) {
return;
}
try {
String name = JOptionPane.showInputDialog(this,
"New key name",
"New key...",
JOptionPane.YES_NO_OPTION);
if(name != null && !"".equals(name)) {
PrefsTreeNode node = (PrefsTreeNode)tp.getLastPathComponent();
node.getPrefs().put(name, node.getPrefs().get(name, ""));
node.getPrefs().flush();
}
// setPreferences(node);
} catch (Exception e) {
Activator.log.warn("Failed to add key", e);
}
}
void doExport() {
TreePath[] paths = getSelectionPaths();
if(paths == null || paths.length < 1) {
return;
}
if(fc == null) {
fc = new JFileChooser();
fc.setCurrentDirectory(new File(System.getProperty("user.dir", ".")));
}
fc.setDialogTitle("Export preferences XML");
fc.setApproveButtonText("Export");
int returnVal = fc.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
OutputStream out = null;
try {
PrefsTreeNode node = (PrefsTreeNode)paths[0].getLastPathComponent();
File f = fc.getSelectedFile();
out = new FileOutputStream(f);
node.getPrefs().exportSubtree(out);
} catch (Exception e) {
Activator.log.warn("Failed to export", e);
} finally {
try { out.close(); } catch (Exception ignored) { }
}
}
}
protected void onExpand(TreePath path) {
// log.info("expand " + path);
Object node = path.getLastPathComponent();
if(node instanceof PrefsTreeNode) {
PrefsTreeNode pNode = (PrefsTreeNode)node;
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
pNode.setHasBeenExpanded(true);
pNode.rescan();
TreeModel model = getModel();
if(model instanceof DefaultTreeModel) {
// log.info("changed " + pNode);
DefaultTreeModel dtModel = (DefaultTreeModel)model;
dtModel.nodeStructureChanged(pNode);
invalidate();
revalidate();
getParent().invalidate();
repaint();
}
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
}
class PrefsTreeRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
static Icon leafIcon = null;
static Icon nodeOpenIcon = null;
static Icon nodeClosedIcon = null;
Color bgColor = Color.white;
public PrefsTreeRenderer() {
super();
if(nodeOpenIcon == null) {
nodeOpenIcon = new ImageIcon(PrefsTreeRenderer.class.getResource("/prefs/folder_open16x16.png"));
nodeClosedIcon = new ImageIcon(PrefsTreeRenderer.class.getResource("/prefs/folder16x16.png"));
leafIcon = new ImageIcon(PrefsTreeRenderer.class.getResource("/prefs/Default.png"));
}
//setOpaque(false);
}
public void setBackground(Color c) {
super.setBackground(c);
this.bgColor = c;
}
Object node;
boolean bSel;
// This is only overridden because the GTK look and feel
// refuses to use my background colors
public void paintComponent(Graphics g) {
Dimension size = getSize();
if(!bSel) {
g.setColor(bgColor);
g.fillRect(0, 0, size.width-1, size.height - 1);
g.setColor(Color.black);
}
super.paintComponent(g);
}
public Component getTreeCellRendererComponent(JTree tree,
Object node,
boolean bSel,
boolean bExpanded,
boolean bLeaf,
int row,
boolean bFocus) {
this.node = node;
this.bSel = bSel;
// Initialize this renderer with defaults for the current request.
super.getTreeCellRendererComponent(tree, node, bSel, bExpanded,
bLeaf, row, bFocus);
// Special configuration for rendering the JPrefsTree.
setBackground(tree.getBackground());
setOpaque(false);
setLeafIcon(null);
setClosedIcon(null);
setOpenIcon(null);
if(node instanceof PrefsTreeNode) {
try {
PrefsTreeNode pNode = (PrefsTreeNode)node;
Preferences prefs = pNode.getPrefs();
String[] names = prefs.childrenNames();
String[] keys = prefs.keys();
if(names.length > 0) {
setIcon(bExpanded ? nodeOpenIcon : nodeClosedIcon);
} else {
if(keys.length > 0) {
setIcon(leafIcon);
} else {
setIcon(nodeClosedIcon);
}
}
setToolTipText(prefs.absolutePath());
} catch(Exception ignored) {
// log.warn("oups", e);
}
}
return this;
}
}
|
92363e3b1de8f643c98eaae229a0be64e615f434 | 522 | java | Java | inject-java/src/test/groovy/io/micronaut/inject/lifecycle/beancreationeventlistener/OffendingFieldListener.java | altro3/micronaut-core | d166511ce28f208f045553f04a5fedb709a6fd28 | [
"Apache-2.0"
] | null | null | null | inject-java/src/test/groovy/io/micronaut/inject/lifecycle/beancreationeventlistener/OffendingFieldListener.java | altro3/micronaut-core | d166511ce28f208f045553f04a5fedb709a6fd28 | [
"Apache-2.0"
] | null | null | null | inject-java/src/test/groovy/io/micronaut/inject/lifecycle/beancreationeventlistener/OffendingFieldListener.java | altro3/micronaut-core | d166511ce28f208f045553f04a5fedb709a6fd28 | [
"Apache-2.0"
] | null | null | null | 26.1 | 76 | 0.783525 | 997,601 | package io.micronaut.inject.lifecycle.beancreationeventlistener;
import io.micronaut.context.event.BeanCreatedEvent;
import io.micronaut.context.event.BeanCreatedEventListener;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
import jakarta.inject.Singleton;
@Singleton
public class OffendingFieldListener implements BeanCreatedEventListener<B> {
@Inject A a;
@Inject Provider<C> cProvider;
@Override
public B onCreated(BeanCreatedEvent<B> event) {
return event.getBean();
}
}
|
92363e54caf8526960b83b7bd4b57573f83d3b98 | 4,220 | java | Java | examples/src/main/java/org/apache/mahout/fpm/pfpgrowth/DeliciousTagsExample.java | UnimibSoftEngCourse1819/laboratorio-4-esercizio-sonarqube-mahout-claudiom4sir | 6267e5d8f6b13136f0c8151ea7e514b9733266ff | [
"Apache-2.0"
] | 2,073 | 2015-01-01T15:35:21.000Z | 2022-03-31T06:18:06.000Z | examples/src/main/java/org/apache/mahout/fpm/pfpgrowth/DeliciousTagsExample.java | UnimibSoftEngCourse1819/laboratorio-4-esercizio-sonarqube-mahout-claudiom4sir | 6267e5d8f6b13136f0c8151ea7e514b9733266ff | [
"Apache-2.0"
] | 224 | 2015-01-01T16:36:19.000Z | 2021-01-27T23:22:45.000Z | examples/src/main/java/org/apache/mahout/fpm/pfpgrowth/DeliciousTagsExample.java | UnimibSoftEngCourse1819/laboratorio-4-esercizio-sonarqube-mahout-claudiom4sir | 6267e5d8f6b13136f0c8151ea7e514b9733266ff | [
"Apache-2.0"
] | 1,109 | 2015-01-01T23:32:26.000Z | 2022-03-28T07:27:17.000Z | 44.421053 | 108 | 0.704739 | 997,602 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.fpm.pfpgrowth;
import java.io.IOException;
import org.apache.commons.cli2.CommandLine;
import org.apache.commons.cli2.Group;
import org.apache.commons.cli2.Option;
import org.apache.commons.cli2.OptionException;
import org.apache.commons.cli2.builder.ArgumentBuilder;
import org.apache.commons.cli2.builder.DefaultOptionBuilder;
import org.apache.commons.cli2.builder.GroupBuilder;
import org.apache.commons.cli2.commandline.Parser;
import org.apache.mahout.common.CommandLineUtil;
import org.apache.mahout.common.Parameters;
import org.apache.mahout.common.commandline.DefaultOptionCreator;
import org.apache.mahout.fpm.pfpgrowth.dataset.KeyBasedStringTupleGrouper;
public final class DeliciousTagsExample {
private DeliciousTagsExample() { }
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
ArgumentBuilder abuilder = new ArgumentBuilder();
GroupBuilder gbuilder = new GroupBuilder();
Option inputDirOpt = DefaultOptionCreator.inputOption().create();
Option outputOpt = DefaultOptionCreator.outputOption().create();
Option helpOpt = DefaultOptionCreator.helpOption();
Option recordSplitterOpt = obuilder.withLongName("splitterPattern").withArgument(
abuilder.withName("splitterPattern").withMinimum(1).withMaximum(1).create()).withDescription(
"Regular Expression pattern used to split given line into fields."
+ " Default value splits comma or tab separated fields."
+ " Default Value: \"[ ,\\t]*\\t[ ,\\t]*\" ").withShortName("regex").create();
Option encodingOpt = obuilder.withLongName("encoding").withArgument(
abuilder.withName("encoding").withMinimum(1).withMaximum(1).create()).withDescription(
"(Optional) The file encoding. Default value: UTF-8").withShortName("e").create();
Group group = gbuilder.withName("Options").withOption(inputDirOpt).withOption(outputOpt).withOption(
helpOpt).withOption(recordSplitterOpt).withOption(encodingOpt).create();
try {
Parser parser = new Parser();
parser.setGroup(group);
CommandLine cmdLine = parser.parse(args);
if (cmdLine.hasOption(helpOpt)) {
CommandLineUtil.printHelp(group);
return;
}
Parameters params = new Parameters();
if (cmdLine.hasOption(recordSplitterOpt)) {
params.set("splitPattern", (String) cmdLine.getValue(recordSplitterOpt));
}
String encoding = "UTF-8";
if (cmdLine.hasOption(encodingOpt)) {
encoding = (String) cmdLine.getValue(encodingOpt);
}
params.set("encoding", encoding);
String inputDir = (String) cmdLine.getValue(inputDirOpt);
String outputDir = (String) cmdLine.getValue(outputOpt);
params.set("input", inputDir);
params.set("output", outputDir);
params.set("groupingFieldCount", "2");
params.set("gfield0", "1");
params.set("gfield1", "2");
params.set("selectedFieldCount", "1");
params.set("field0", "3");
params.set("maxTransactionLength", "100");
KeyBasedStringTupleGrouper.startJob(params);
} catch (OptionException ex) {
CommandLineUtil.printHelp(group);
}
}
}
|
92363e92008fd137c0a985ecaeb0bd807d525ad7 | 624 | java | Java | src/test/java/seedu/address/logic/parser/deck/SelectDeckCommandParserTest.java | GabrielSimbingyang/tp | c479b6c445382d0bdc596d7efa364a26e40adea5 | [
"MIT"
] | null | null | null | src/test/java/seedu/address/logic/parser/deck/SelectDeckCommandParserTest.java | GabrielSimbingyang/tp | c479b6c445382d0bdc596d7efa364a26e40adea5 | [
"MIT"
] | null | null | null | src/test/java/seedu/address/logic/parser/deck/SelectDeckCommandParserTest.java | GabrielSimbingyang/tp | c479b6c445382d0bdc596d7efa364a26e40adea5 | [
"MIT"
] | null | null | null | 32.842105 | 120 | 0.817308 | 997,603 | package seedu.address.logic.parser.deck;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure;
import org.junit.jupiter.api.Test;
import seedu.address.logic.commands.deck.SelectDeckCommand;
public class SelectDeckCommandParserTest {
private SelectDeckCommandParser parser = new SelectDeckCommandParser();
@Test
public void parse_invalidArgs_throwsParseException() {
assertParseFailure(parser, "a", String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectDeckCommand.MESSAGE_USAGE));
}
}
|
92363f86180ea689f069b889323d6eaa1e9b4268 | 1,045 | java | Java | src/test/java/com/uneeddevs/finances/model/ProfileTest.java | uneeddevs/finnances-backend | 40eac4fa4dfb3390ca828b0ee63f740286278e8f | [
"Apache-2.0"
] | 1 | 2022-01-17T17:27:48.000Z | 2022-01-17T17:27:48.000Z | src/test/java/com/uneeddevs/finances/model/ProfileTest.java | uneeddevs/finnances-backend | 40eac4fa4dfb3390ca828b0ee63f740286278e8f | [
"Apache-2.0"
] | null | null | null | src/test/java/com/uneeddevs/finances/model/ProfileTest.java | uneeddevs/finnances-backend | 40eac4fa4dfb3390ca828b0ee63f740286278e8f | [
"Apache-2.0"
] | null | null | null | 29.857143 | 104 | 0.675598 | 997,604 | package com.uneeddevs.finances.model;
import com.uneeddevs.finances.mocks.ProfileMock;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ProfileTest {
@Test
void testProfileCreateInstanceNotNull() {
Profile profile = new Profile("ROLE_ADMIN");
assertNotNull(profile, "Expected profile instance");
}
@Test
void testProfileInstanceExpectedIllegalArgumentException() {
IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class,
() -> new Profile(""),
"Expected illegal argument exception");
assertEquals("Role Name is mandatory",
illegalArgumentException.getMessage()
);
}
@Test
void testEqualsAndHashCode() throws Exception{
Profile profile1 = ProfileMock.mock();
Profile profile2 = ProfileMock.mock();
assertEquals(profile2, profile1);
assertEquals(profile1.hashCode(), profile2.hashCode());
}
}
|
92363f8a23c13f6253d25b5e8e77221cbf8ce8d9 | 347 | java | Java | FallDetector/test/org/yu/dsp/test/LowPassFilterTest.java | Mrsunsunshine/ForElder | b92acc2b31cba3cff68545f52c72941f6719f7d9 | [
"Apache-2.0"
] | 2 | 2016-11-27T15:29:31.000Z | 2016-12-03T08:37:35.000Z | FallDetector/test/org/yu/dsp/test/LowPassFilterTest.java | jnzhou90/ForElder | b92acc2b31cba3cff68545f52c72941f6719f7d9 | [
"Apache-2.0"
] | null | null | null | FallDetector/test/org/yu/dsp/test/LowPassFilterTest.java | jnzhou90/ForElder | b92acc2b31cba3cff68545f52c72941f6719f7d9 | [
"Apache-2.0"
] | 1 | 2016-11-27T15:34:48.000Z | 2016-11-27T15:34:48.000Z | 17.35 | 52 | 0.726225 | 997,605 | package org.yu.dsp.test;
import static org.junit.Assert.*;
import org.heartwings.care.falldetect.LowPassFilter;
import org.junit.Test;
public class LowPassFilterTest {
private LowPassFilter lpf;
@Test
public void testNextValue() {
lpf = new LowPassFilter(40, 20);
for(int i=0;i<100;i++)
System.out.println(lpf.nextValue(i));
}
}
|
92363fd5530fcd8dc85ae8643c6844a73a55f701 | 4,627 | java | Java | brs-sys/moudles/brs-idm-rest/src/main/java/com/brs/idm/rest/api/login/LoginController.java | tinyjjlin/learn_mybatis | eaeda75b1ba9e805fff1eaf480f6abe70486c8f1 | [
"MIT"
] | null | null | null | brs-sys/moudles/brs-idm-rest/src/main/java/com/brs/idm/rest/api/login/LoginController.java | tinyjjlin/learn_mybatis | eaeda75b1ba9e805fff1eaf480f6abe70486c8f1 | [
"MIT"
] | null | null | null | brs-sys/moudles/brs-idm-rest/src/main/java/com/brs/idm/rest/api/login/LoginController.java | tinyjjlin/learn_mybatis | eaeda75b1ba9e805fff1eaf480f6abe70486c8f1 | [
"MIT"
] | null | null | null | 37.92623 | 114 | 0.682516 | 997,606 | package com.brs.idm.rest.api.login;
import com.brs.idm.api.IdmIdentityService;
import com.brs.idm.api.dto.LoginUserDto;
import com.brs.idm.api.dto.LoginUserInfoRepresentation;
import com.brs.sys.common.annotation.Authentication;
import com.brs.sys.common.jwt.JwtSupport;
import com.brs.sys.common.model.RestResult;
import com.brs.sys.common.model.TokenModel;
import com.brs.sys.common.service.AdService;
import com.brs.sys.common.service.ITokenService;
import com.brs.sys.common.util.CommonUtil;
import com.brs.sys.common.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* @author tiny lin
* @date 2018/11/29
*/
@RestController
@Api
public class LoginController {
private final static String USER_TYPE_CLIENT ="client";
private final static String USER_TYPE_STAFF = "staff";
static final Logger LOG = LoggerFactory.getLogger(LoginController.class);
@Autowired
private AdService ldapService;
@Autowired
private ITokenService tokenService;
@Autowired
private IdmIdentityService identityService;
@PostMapping("/api/idm/client/login")
@ApiOperation(value = "client login")
public RestResult clientLogin(HttpServletRequest request, @RequestBody LoginUserDto loginUserDto){
LoginUserInfoRepresentation loginUserInfo = identityService.getLoginUserInfo(loginUserDto.getLoginName());
if(loginUserInfo != null){
return new RestResult(2000,"client login success" );
}else{
return new RestResult(40001,"client login failed" );
}
}
@PostMapping("/api/idm/staff/login")
@ApiOperation(value = "brs staff login")
public RestResult login(HttpServletRequest request, @RequestBody LoginUserDto loginUserDto){
try {
// step1: ldap 用户认证
ldapService.authentication(loginUserDto);
//step2 :验证工号存在
Integer empNo = CommonUtil.getEmpNo(loginUserDto.getLoginName());
if(empNo == null){
return new RestResult(4001, "登录账号必须是姓名首字母+工号!", null);
}
//step3:验证mysql用户是否创建
if( identityService.getLoginUserInfo(empNo+"") == null){
return new RestResult(4001, "新员工没有在系统中注册!", null);
}
//step4:生成token
TokenModel tokenModel = tokenService.generateToken(loginUserDto.getLoginName(),empNo);
//step5:保持用户的登录ip地址
return new RestResult(200, "登录成功!", tokenModel);
} catch (Exception e) {
return new RestResult(4001, e.getMessage(),null);
}
}
@GetMapping("/api/idm/logout")
@ApiOperation(value = "logout")
@Authentication
public RestResult logout(@RequestHeader("Authorization")String token){
String loginName = JwtSupport.getLoginName(token);
tokenService.deleteToken(loginName);
return new RestResult(2000, "退出操作成功!");
}
/**
* login user info
* @param userId
* @return
*/
@ApiOperation("get login user info")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "userId", value = "登录账号", dataType = "string")
})
@GetMapping("/api/idm/userInfo")
public RestResult getLoginUserInfo(@RequestParam("userId")String userId){
LoginUserInfoRepresentation loginUserDto = identityService.getLoginUserInfo(userId);
if(loginUserDto != null){
return new RestResult(2000,"get login user inf success",loginUserDto );
}else{
return new RestResult(4001, "get login user inf failed");
}
}
@PostMapping("/api/idm/loginValidation")
@ApiOperation("login validation")
public RestResult loginValidation(HttpServletRequest request, @RequestBody LoginUserDto loginDto){
if(loginDto == null || StrUtil.isNUll(loginDto.getLoginName())){
return new RestResult(250, "该账号没有登录!",null);
}
if(!tokenService.loginValidation(loginDto.getLoginName())){
return new RestResult(250, "该账号没有登录", null);
}else{
Integer empNo = CommonUtil.getEmpNo(loginDto.getLoginName());
String loginAddress = "";
return new RestResult(451, "该账号"+loginDto.getLoginName()+"已经在"+loginAddress+"登录,是否继续登录?", null);
}
}
} |
923641a7cbbdf9a4885db64f1a0598dbcd40da87 | 5,807 | java | Java | Best_blue.java | choward64/ftc-app_master_3.2 | 5861833e8112fb53109d1b4f1713db8603825e7e | [
"Unlicense"
] | null | null | null | Best_blue.java | choward64/ftc-app_master_3.2 | 5861833e8112fb53109d1b4f1713db8603825e7e | [
"Unlicense"
] | null | null | null | Best_blue.java | choward64/ftc-app_master_3.2 | 5861833e8112fb53109d1b4f1713db8603825e7e | [
"Unlicense"
] | null | null | null | 37.224359 | 75 | 0.715516 | 997,607 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
/**Sean Cardosi
* Created by rpcardosimd on 12/17/16.
* Team Rise 7719
*/
@Disabled
@Autonomous(name = "Sparky blue", group = "Sparky")
public class Best_blue extends LinearOpMode {
DcMotor left_back_drive;
DcMotor left_front_drive;
DcMotor right_back_drive;
DcMotor right_front_drive;
DcMotor catapult;
public void runOpMode() throws InterruptedException {
left_back_drive = hardwareMap.dcMotor.get("1");
left_front_drive = hardwareMap.dcMotor.get("2");
left_back_drive.setDirection(DcMotor.Direction.REVERSE);
left_front_drive.setDirection(DcMotor.Direction.REVERSE);
right_back_drive = hardwareMap.dcMotor.get("3");
right_front_drive = hardwareMap.dcMotor.get("4");
right_back_drive.setDirection(DcMotor.Direction.FORWARD);
right_front_drive.setDirection(DcMotor.Direction.FORWARD);
catapult = hardwareMap.dcMotor.get("catapult");
left_back_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
left_front_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
right_back_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
right_front_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
left_back_drive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
left_front_drive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
right_back_drive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
right_front_drive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
waitForStart();
catapult.setPower(1);
Thread.sleep(2500);
catapult.setPower(0);
// turn towards the center vortex
left_back_drive.setTargetPosition(-350);
left_front_drive.setTargetPosition(-350);
right_back_drive.setTargetPosition(2350);
right_front_drive.setTargetPosition(2350);
left_back_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
left_front_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
right_back_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
right_front_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
left_back_drive.setPower(0.5);
left_front_drive.setPower(0.5);
right_back_drive.setPower(0.5);
right_front_drive.setPower(0.5);
Thread.sleep(3000);
// go forward and knock the cap ball off the center vortex
left_back_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
left_front_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
right_back_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
right_front_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
left_back_drive.setTargetPosition(2650);
left_front_drive.setTargetPosition(2650);
right_back_drive.setTargetPosition(2650);
right_front_drive.setTargetPosition(2650);
left_back_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
left_front_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
right_back_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
right_front_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
left_back_drive.setPower(0.5);
left_front_drive.setPower(0.5);
right_back_drive.setPower(0.5);
right_front_drive.setPower(0.5);
Thread.sleep(5500);
// turn towards the corner vortex
left_back_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
left_front_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
right_back_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
right_front_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
left_back_drive.setTargetPosition(1200);
left_front_drive.setTargetPosition(1200);
right_back_drive.setTargetPosition(-1200);
right_front_drive.setTargetPosition(-1200);
left_back_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
left_front_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
right_back_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
right_front_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
left_back_drive.setPower(0.5);
left_front_drive.setPower(0.5);
right_back_drive.setPower(0.5);
right_front_drive.setPower(0.5);
Thread.sleep(1000);
//go forward and park on the corner vortex
left_back_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
left_front_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
right_back_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
right_front_drive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
left_back_drive.setTargetPosition(4400);
left_front_drive.setTargetPosition(4400);
right_back_drive.setTargetPosition(4400);
right_front_drive.setTargetPosition(4400);
left_back_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
left_front_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
right_back_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
right_front_drive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
left_back_drive.setPower(0.5);
left_front_drive.setPower(0.5);
right_back_drive.setPower(0.5);
right_front_drive.setPower(0.5);
Thread.sleep(4000);
}
}
|
92364216fbc46b29f978620f7a13ec73d9015441 | 2,762 | java | Java | havoc.engine/src/core/math/Complex.java | kenWjohnson/Havoc | c2b2d1b6c9a72b5470d837ca81f4724abe0cd7f0 | [
"MIT"
] | null | null | null | havoc.engine/src/core/math/Complex.java | kenWjohnson/Havoc | c2b2d1b6c9a72b5470d837ca81f4724abe0cd7f0 | [
"MIT"
] | null | null | null | havoc.engine/src/core/math/Complex.java | kenWjohnson/Havoc | c2b2d1b6c9a72b5470d837ca81f4724abe0cd7f0 | [
"MIT"
] | null | null | null | 23.210084 | 88 | 0.579652 | 997,608 | package core.math;
import java.util.Objects;
public class Complex {
private final double re;
private final double im;
public Complex(double real, double imag) {
re = real;
im = imag;
}
public double real() {return re;}
public double imag() {return im;}
public String toString() {
if(im == 0) return String.format("%.3f", re);
if(re == 0) return String.format("%.3fi", im);
if(im < 0) return String.format("%.3f - %.3fi", re, -im);
return String.format("%.3f + %.3fi", re, im);
}
public double abs() {
return Math.hypot(re, im);
}
public double phase() {
return Math.atan2(re, im);
}
public Complex add(Complex b) {
Complex a = this;
double real = a.re + b.re;
double imag = a.im + b.im;
return new Complex(real, imag);
}
public Complex subtract(Complex b) {
Complex a = this;
double real = a.re - b.re;
double imag = a.im - b.im;
return new Complex(real, imag);
}
public Complex multiply(Complex b) {
Complex a = this;
double real = a.re * b.re - a.im * b.im;
double imag = a.re * b.im - a.im * b.im;
return new Complex(real, imag);
}
public Complex scale(double aplha) {
return new Complex(aplha * re, aplha * im);
}
public Complex conjugate() {
return new Complex(re, -im);
}
public Complex reciprocal() {
double scale = re*re + im*im;
return new Complex(re / scale, -im / scale);
}
public Complex divide(Complex b) {
Complex a = this;
return a.multiply(b.reciprocal());
}
public Complex exp() {
return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im));
}
public Complex sin() {
return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im));
}
public Complex cos() {
return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im));
}
public Complex tan() {
return sin().divide(cos());
}
public static Complex add(Complex a, Complex b) {
double real = a.re + b.re;
double imag = a.im + b.im;
Complex sum = new Complex(real, imag);
return sum;
}
public static Complex subtract(Complex a, Complex b) {
double real = a.re - b.re;
double imag = a.im - b.im;
Complex diff = new Complex(real, imag);
return diff;
}
public boolean equals(Object obj) {
if (obj == null) return false;
if (this.getClass() != obj.getClass()) return false;
Complex that = (Complex) obj;
return (this.re == that.re) && (this.im == that.im);
}
public int hashCode() {
return Objects.hash(re, im);
}
public Complex clone() {
return new Complex(re, im);
}
}
|
923642508f5057c496eac7c3491fd5756b9df0b7 | 1,706 | java | Java | testsuite/src/domts/level2/core/NamedNode_Map_Get_NamedItem_NS_02_Test.java | benravago/fx.html | a7ca6eb0554342b96eec94ca4ba8cb5594b44442 | [
"MIT"
] | null | null | null | testsuite/src/domts/level2/core/NamedNode_Map_Get_NamedItem_NS_02_Test.java | benravago/fx.html | a7ca6eb0554342b96eec94ca4ba8cb5594b44442 | [
"MIT"
] | null | null | null | testsuite/src/domts/level2/core/NamedNode_Map_Get_NamedItem_NS_02_Test.java | benravago/fx.html | a7ca6eb0554342b96eec94ca4ba8cb5594b44442 | [
"MIT"
] | null | null | null | 40.619048 | 142 | 0.756741 | 997,609 | package domts.level2.core;
import org.w3c.dom.*;
import java.util.*;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* The method getNamedItemNS retrieves a node specified by local name and namespace URI.
*
* Using the method getNamedItemNS, retreive an attribute node having namespaceURI=http://www.nist.gov
* and localName=domestic, from a NamedNodeMap of attribute nodes, for the second element
* whose namespaceURI=http://www.nist.gov and localName=address. Verify if the attr node
* has been retreived successfully by checking its nodeName atttribute.
* @author IBM
* @author Neil Delima
* @see <a href="http://www.w3.org/TR/DOM-Level-2-Core/core#ID-getNamedItemNS">http://www.w3.org/TR/DOM-Level-2-Core/core#ID-getNamedItemNS</a>
*/
class NamedNode_Map_Get_NamedItem_NS_02_Test extends domts.DOMTestCase {
@BeforeEach
void setup() {
setNamespaceAware(true);
// check if loaded documents are supported for content type
String contentType = getContentType();
preload(contentType, "staffNS", false);
}
@Test
@DisplayName("http://www.w3.org/2001/DOM_Test_Suite/level2/core/namednodemapgetnameditemns02")
void run() throws Throwable {
Document doc;
NamedNodeMap attributes;
Node element;
Attr attribute;
NodeList elementList;
String attrName;
doc = (Document) load("staffNS", false);
elementList = doc.getElementsByTagNameNS("http://www.nist.gov", "address");
element = elementList.item(1);
attributes = element.getAttributes();
attribute = (Attr) attributes.getNamedItemNS("http://www.nist.gov", "domestic");
attrName = attribute.getNodeName();
assertEquals("emp:domestic", attrName, "namednodemapgetnameditemns02");
}
} |
92364444c716fc1a0753c6da23da55a4f84c3ede | 390 | java | Java | src/TipoUtilizador.java | RicardoMartins07/ProjetoES1 | 920f4e9b15e2f1f8a5eb7e821e402cfb50e41d39 | [
"MIT"
] | null | null | null | src/TipoUtilizador.java | RicardoMartins07/ProjetoES1 | 920f4e9b15e2f1f8a5eb7e821e402cfb50e41d39 | [
"MIT"
] | null | null | null | src/TipoUtilizador.java | RicardoMartins07/ProjetoES1 | 920f4e9b15e2f1f8a5eb7e821e402cfb50e41d39 | [
"MIT"
] | null | null | null | 21.666667 | 65 | 0.671795 | 997,610 | public class TipoUtilizador{
String descricao;
int prazoEmprestimo;
public TipoUtilizador(String descricao, int prazoEmprestimo){
this.descricao = descricao;
this.prazoEmprestimo = prazoEmprestimo;
}
public String getDescricao() {
return this.descricao;
}
public int getPrazoEmprestimo() {
return this.prazoEmprestimo;
}
} |
92364481097afb3807e5a106561c8dcb065ffc4e | 533 | java | Java | src/main/java/reduction/xml/OutputXml.java | jeffdshen/grid-reductions | 081f0c4f78529d33e497c2c4f72aafc7e22ad9ec | [
"MIT"
] | null | null | null | src/main/java/reduction/xml/OutputXml.java | jeffdshen/grid-reductions | 081f0c4f78529d33e497c2c4f72aafc7e22ad9ec | [
"MIT"
] | 12 | 2020-09-27T20:03:03.000Z | 2020-09-28T23:06:19.000Z | src/main/java/reduction/xml/OutputXml.java | jeffdshen/grid-reductions | 081f0c4f78529d33e497c2c4f72aafc7e22ad9ec | [
"MIT"
] | null | null | null | 19.035714 | 42 | 0.572233 | 997,611 | package reduction.xml;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class OutputXml {
@XmlAttribute
private InputOutputXmlType type;
@XmlValue
private String output;
public String getOutput() {
return output;
}
public InputOutputXmlType getType() {
return type;
}
@Override
public String toString() {
return "OutputXml{" +
"type='" + type + '\'' +
", output='" + output + '\'' +
'}';
}
}
|
923644dd6f95fc9e5cf1bac7f417a57af58d3f64 | 3,043 | java | Java | src/main/java/com/chuntung/plugin/mybatis/builder/generator/DefaultParameters.java | gitter-badger/mybatis-builder | 6af137e5546b925367d4f9255ecf00f1d4fc0840 | [
"MIT"
] | 36 | 2019-06-05T09:11:45.000Z | 2022-02-18T01:40:16.000Z | src/main/java/com/chuntung/plugin/mybatis/builder/generator/DefaultParameters.java | gitter-badger/mybatis-builder | 6af137e5546b925367d4f9255ecf00f1d4fc0840 | [
"MIT"
] | 7 | 2019-06-05T09:20:39.000Z | 2021-11-18T05:24:59.000Z | src/main/java/com/chuntung/plugin/mybatis/builder/generator/DefaultParameters.java | gitter-badger/mybatis-builder | 6af137e5546b925367d4f9255ecf00f1d4fc0840 | [
"MIT"
] | 15 | 2019-07-23T01:21:03.000Z | 2022-03-11T14:17:58.000Z | 29.833333 | 97 | 0.738416 | 997,612 | /*
* Copyright (c) 2019-2021 Tony Ho. Some rights reserved.
*/
package com.chuntung.plugin.mybatis.builder.generator;
import com.chuntung.plugin.mybatis.builder.generator.plugins.MapperAnnotationPlugin;
import com.chuntung.plugin.mybatis.builder.generator.plugins.RenamePlugin;
import com.chuntung.plugin.mybatis.builder.generator.plugins.selectwithlock.SelectWithLockConfig;
import org.mybatis.generator.config.ModelType;
public class DefaultParameters {
private ModelType defaultModelType = ModelType.FLAT;
private String javaFileEncoding = "UTF-8";
private Boolean forceBigDecimals = true;
private Boolean useJSR310Types = false;
private String generatedComment = "generated automatically, do not modify!";
private Integer historySize = 10;
// plugin configs
private MapperAnnotationPlugin.Config mapperAnnotationConfig
= new MapperAnnotationPlugin.Config("org.springframework.stereotype.Repository");
private SelectWithLockConfig selectWithLockConfig = new SelectWithLockConfig();
private RenamePlugin.Config renameConfig = new RenamePlugin.Config();
public ModelType getDefaultModelType() {
return defaultModelType;
}
public void setDefaultModelType(ModelType defaultModelType) {
this.defaultModelType = defaultModelType;
}
public String getJavaFileEncoding() {
return javaFileEncoding;
}
public void setJavaFileEncoding(String javaFileEncoding) {
this.javaFileEncoding = javaFileEncoding;
}
public String getGeneratedComment() {
return generatedComment;
}
public void setGeneratedComment(String generatedComment) {
this.generatedComment = generatedComment;
}
public Boolean getForceBigDecimals() {
return forceBigDecimals;
}
public void setForceBigDecimals(Boolean forceBigDecimals) {
this.forceBigDecimals = forceBigDecimals;
}
public Boolean getUseJSR310Types() {
return useJSR310Types;
}
public void setUseJSR310Types(Boolean useJSR310Types) {
this.useJSR310Types = useJSR310Types;
}
public Integer getHistorySize() {
return historySize;
}
public void setHistorySize(Integer historySize) {
this.historySize = historySize;
}
public MapperAnnotationPlugin.Config getMapperAnnotationConfig() {
return mapperAnnotationConfig;
}
public void setMapperAnnotationConfig(MapperAnnotationPlugin.Config mapperAnnotationConfig) {
this.mapperAnnotationConfig = mapperAnnotationConfig;
}
public SelectWithLockConfig getSelectWithLockConfig() {
return selectWithLockConfig;
}
public void setSelectWithLockConfig(SelectWithLockConfig selectWithLockConfig) {
this.selectWithLockConfig = selectWithLockConfig;
}
public RenamePlugin.Config getRenameConfig() {
return renameConfig;
}
public void setRenameConfig(RenamePlugin.Config renameConfig) {
this.renameConfig = renameConfig;
}
}
|
9236476d4276e91240fd653c44cef858928f52b2 | 126 | java | Java | mago3d-user/src/main/java/gaia3d/domain/ApprovalStatus.java | ghJo-Gaia3D/mago3d | 4aec7975d76cf11ab1e9f46471455732766a38aa | [
"Apache-2.0"
] | 61 | 2017-07-06T03:31:24.000Z | 2021-11-03T15:17:23.000Z | mago3d-user/src/main/java/gaia3d/domain/ApprovalStatus.java | ghJo-Gaia3D/mago3d | 4aec7975d76cf11ab1e9f46471455732766a38aa | [
"Apache-2.0"
] | 50 | 2017-05-29T02:19:11.000Z | 2022-03-10T06:19:57.000Z | mago3d-user/src/main/java/gaia3d/domain/ApprovalStatus.java | ghJo-Gaia3D/mago3d | 4aec7975d76cf11ab1e9f46471455732766a38aa | [
"Apache-2.0"
] | 26 | 2017-06-20T09:09:14.000Z | 2022-03-11T00:52:37.000Z | 8.4 | 28 | 0.634921 | 997,613 | package gaia3d.domain;
public enum ApprovalStatus {
// 요청
REQUEST,
// 승인
APPROVAL,
// 기각
REJECT,
// 원복
ROLLBACK
}
|
923648561a7dcff36561d7de24feab683e89199c | 1,532 | java | Java | pokemon/Pokemon.java | Zetioun/pokedexer | 3e4d0d14a2fb72b4f6f2977f5a58281444aace81 | [
"MIT"
] | 1 | 2016-08-12T20:54:22.000Z | 2016-08-12T20:54:22.000Z | pokemon/Pokemon.java | Zetioun/Pokedexer | 3e4d0d14a2fb72b4f6f2977f5a58281444aace81 | [
"MIT"
] | null | null | null | pokemon/Pokemon.java | Zetioun/Pokedexer | 3e4d0d14a2fb72b4f6f2977f5a58281444aace81 | [
"MIT"
] | null | null | null | 37.365854 | 112 | 0.686031 | 997,614 | package pokemon;
import java.util.ArrayList;
import java.util.Iterator;
public class Pokemon {
/*
public static void main(String[] args){
new Pokemon("Tangela", 39.914944, -75.160876);
new Pokemon("Dangela", 39.914944, -75.160876);
new Pokemon("Dangela", 39.914944, -75.160876);
new Pokemon("Tangela", 39.1914944, -75.160876);
new Pokemon("Tangela", 39.914944, -75.1608376);
new Pokemon("Tangesada", 39.914944, -75.160876);
new Pokemon("Tangedsla", 39.914944, -75.160876);
new Pokemon("Tangela", 39.914944, -75.160876);
new Pokemon("Tangela", 39.914944, -75.160876);
new Pokemon("Tangelsada", 39.914944, -75.160876);
new Pokemon("Tangela", 39.914944, -75.160876);
new Pokemon("Tangesadla", 39.914944, -75.160876);
new Pokemon("Dangela", 39.9149441, -75.160876);
new Pokemon("Dangela", 39.9149441, -75.160876);
new Pokemon("Aangela", 39.914944, -75.160876);
new Pokemon("Dangela", 39.914944, -75.160876);
new Pokemon("Tangela", 39.914944, -75.160876);
new Pokemon("Qangela", 39.914944, -75.160876);
for(PokemonFactory v: PokemonFactory.pokemonList){
System.out.println("Name: " + v.toString() );
for(Coordinates x: v.coordsList){
System.out.print(" L: " +x.getLatitude() + " Lo: " + x.getLongtidue() + "\n");
}
}
}
*/
public Pokemon(String pokemonName, double latitude, double longitude) {
Coordinates coords = new Coordinates(latitude, longitude); //creates coordinate object (two strings lat & lon)
new PokemonFactory(pokemonName, coords); //makes the pokemon
}
}
|
9236488c13c28dd905fc66b7662d98dfae90ffff | 4,691 | java | Java | src/main/java/se/almstudio/booking/api/repository/impl/DefaultRoomAmenityRepository.java | alireza-mahzoon/booking-api | b5c3589b62f042688819eb557c94d94f7121927c | [
"Apache-2.0"
] | null | null | null | src/main/java/se/almstudio/booking/api/repository/impl/DefaultRoomAmenityRepository.java | alireza-mahzoon/booking-api | b5c3589b62f042688819eb557c94d94f7121927c | [
"Apache-2.0"
] | 1 | 2022-02-16T01:11:37.000Z | 2022-02-16T01:11:37.000Z | src/main/java/se/almstudio/booking/api/repository/impl/DefaultRoomAmenityRepository.java | alireza-mahzoon/booking-api | b5c3589b62f042688819eb557c94d94f7121927c | [
"Apache-2.0"
] | null | null | null | 36.648438 | 128 | 0.687274 | 997,615 | package se.almstudio.booking.api.repository.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.almstudio.booking.api.model.entity.RoomAmenity;
import se.almstudio.booking.api.repository.RoomAmenityRepository;
import se.almstudio.booking.api.util.ConnectionManager;
import se.almstudio.booking.api.util.impl.ConnectionUtils;
import java.sql.*;
import java.time.LocalDateTime;
public class DefaultRoomAmenityRepository implements RoomAmenityRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRoomAmenityRepository.class);
@Override
public Long create(RoomAmenity roomAmenity) {
LOGGER.info("Creating a roomAmenity");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = ConnectionManager.INSTANCE.getConnection();
String query = "INSERT INTO RoomAmenity(roomTypeId, Name, Description, Pricing, Registered, Updated) VALUES(?,?,?,?,?,?)";
ps = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps.setLong(1, roomAmenity.getRoomTypeId());
ps.setString(2, roomAmenity.getName());
ps.setString(3, roomAmenity.getDescription());
ps.setString( 4, roomAmenity.getPricing());
ps.setObject( 5, LocalDateTime.now());
ps.setObject(6, LocalDateTime.now());
ps.executeUpdate();
if (ps.getGeneratedKeys().next()) {
LOGGER.debug("RoomAmenity was created");
return ps.getGeneratedKeys().getLong(1);
}
return null;
} catch (SQLException e) {
LOGGER.warn("Failed to create roomAmenity");
throw new RuntimeException(e);
} finally {
ConnectionUtils.closeQuietly(ps);
ConnectionUtils.closeQuietly(connection);
}
}
@Override
public RoomAmenity findById(Long roomAmenityId) {
LOGGER.info("Finding room amenity");
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
connection = ConnectionManager.INSTANCE.getConnection();
String query = "SELECT * FROM RoomAmenity WHERE id=?";
ps = connection.prepareStatement(query);
ps.setLong(1, roomAmenityId);
ps.execute();
rs = ps.getResultSet();
if (rs.next()) {
RoomAmenity roomAmenity = new RoomAmenity();
roomAmenity.setId(roomAmenityId);
roomAmenity.setRoomTypeId(rs.getLong("roomTypeId"));
roomAmenity.setName(rs.getString("name"));
roomAmenity.setDescription(rs.getString("description"));
roomAmenity.setPricing(rs.getString("pricing"));
LOGGER.debug("Room amenity was found");
return roomAmenity;
}
return null;
} catch (SQLException e) {
LOGGER.warn("Failed to find room amenity", e);
throw new RuntimeException(e);
} finally {
ConnectionUtils.closeQuietly(rs);
ConnectionUtils.closeQuietly(ps);
ConnectionUtils.closeQuietly(connection);
}
}
@Override
public boolean update(RoomAmenity roomAmenity) {
LOGGER.info("Updating a roomAmenity information");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = ConnectionManager.INSTANCE.getConnection();
String query = "UPDATE RoomAmenity SET RoomTypeId=?, Name=?, Description=?, Pricing=? WHERE id=?";
ps = connection.prepareStatement(query);
ps.setLong(1, roomAmenity.getRoomTypeId());
ps.setString(2, roomAmenity.getName());
ps.setString(3, roomAmenity.getDescription());
ps.setString(4, roomAmenity.getPricing());
ps.setLong(5, roomAmenity.getId());
int resultUpdated = ps.executeUpdate();
LOGGER.debug("Room amenity was updated");
return resultUpdated == 1;
} catch (SQLException e) {
LOGGER.warn("Failed to update the room amenity", e);
throw new RuntimeException(e);
} finally {
ConnectionUtils.closeQuietly(ps);
ConnectionUtils.closeQuietly(connection);
}
}
@Override
public boolean delete(Long roomAmenityId) {
LOGGER.info("Deleting room amenity");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = ConnectionManager.INSTANCE.getConnection();
String query = "DELETE FROM RoomAmenity WHERE id =?";
ps = connection.prepareStatement(query);
ps.setLong(1, roomAmenityId);
int result = ps.executeUpdate();
LOGGER.debug("room amenity was deleted");
return result == 1;
} catch (SQLException e) {
LOGGER.warn("Failed to delete room Amenity");
throw new RuntimeException(e);
} finally {
ConnectionUtils.closeQuietly(ps);
ConnectionUtils.closeQuietly(connection);
}
}
}
|
923649085e370750fbd9a71458431a16d5c50510 | 5,231 | java | Java | server/src/test/java/io/redspark/ireadme/test/init/BasicControllerTest.java | TimeoutZero/ProjectTrail | 84f9c4a1c59efbcc95a70498708b96bd694a72da | [
"MIT"
] | null | null | null | server/src/test/java/io/redspark/ireadme/test/init/BasicControllerTest.java | TimeoutZero/ProjectTrail | 84f9c4a1c59efbcc95a70498708b96bd694a72da | [
"MIT"
] | null | null | null | server/src/test/java/io/redspark/ireadme/test/init/BasicControllerTest.java | TimeoutZero/ProjectTrail | 84f9c4a1c59efbcc95a70498708b96bd694a72da | [
"MIT"
] | null | null | null | 35.161074 | 134 | 0.814087 | 997,616 | package io.redspark.ireadme.test.init;
import static io.redspark.ireadme.init.AppProfile.TEST;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import io.redspark.ireadme.init.AppConfig;
import io.redspark.ireadme.init.AppWebConfig;
import java.io.UnsupportedEncodingException;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.context.WebApplicationContext;
import aleph.TestPersistentContext;
import com.jayway.jsonassert.JsonAssert;
import com.jayway.jsonassert.JsonAsserter;
@WebAppConfiguration
@ActiveProfiles(TEST)
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback = true)
@ContextConfiguration(classes = { AppConfig.class, AppWebConfig.class, AppTestProvider.class })
public abstract class BasicControllerTest {
protected MockMvc mock;
@Autowired
private WebApplicationContext context;
@Resource
private FilterChainProxy springSecurityFilterChain;
@Autowired
private TransactionTemplate transactionManager;
@Autowired
private JpaPersistenceProvider jpaPersistenceProvider;
private MockHttpSession session;
@Before
public void setupConfiguration() {
jpaPersistenceProvider.clear();
mock = MockMvcBuilders
.webAppContextSetup(context)
.alwaysDo(print())
.addFilters(this.springSecurityFilterChain)
.build();
}
public BasicControllerTest signIn() throws Exception {
MockHttpServletRequestBuilder post = MockMvcRequestBuilders.post("/api/login");
post.param("username", "ychag@example.com");
post.param("password", "12345");
session = (MockHttpSession) mock.perform(post).andExpect(status().isOk()).andReturn().getRequest().getSession();
return this;
}
protected void saveAll() {
transactionManager.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
TestPersistentContext.get().saveAll();
}
});
}
// UTIL
protected MockHttpServletRequestBuilder get(Object... variables) {
return MockMvcRequestBuilders.get(getControllerBase(), variables);
}
protected MockHttpServletRequestBuilder get(String uri, Object... variables) {
return MockMvcRequestBuilders.get(getControllerBase() + uri, variables);
}
protected MockHttpServletRequestBuilder post(Object... variables) {
return MockMvcRequestBuilders.post(getControllerBase(), variables);
}
protected MockHttpServletRequestBuilder post(String endpoint, Object... variables) {
return MockMvcRequestBuilders.post(getControllerBase() + endpoint, variables);
}
protected MockHttpServletRequestBuilder put(Object... variables) {
return MockMvcRequestBuilders.put(getControllerBase(), variables);
}
protected MockHttpServletRequestBuilder put(String endpoint, Object... variables) {
return MockMvcRequestBuilders.put(getControllerBase() + endpoint, variables);
}
protected MockHttpServletRequestBuilder delete(String endpoint, Object... variables){
return MockMvcRequestBuilders.delete(getControllerBase() + endpoint, variables);
}
private String getControllerBase() {
ControllerBase annotation = getClass().getAnnotation(ControllerBase.class);
String base = annotation.value();
return StringUtils.isNotBlank(base) ? base : StringUtils.EMPTY;
}
protected JsonAsserter jsonAssert(MvcResult result) throws UnsupportedEncodingException {
return JsonAssert.with(result.getResponse().getContentAsString());
}
protected AssertUtil jsonError(MvcResult result) throws UnsupportedEncodingException {
return AssertUtil.with(result.getResponse().getContentAsString()).isJsonError();
}
protected MvcResult perform(final MockHttpServletRequestBuilder requestBuilder, final ResultMatcher resultMatcher) throws Exception {
if(session != null) {
requestBuilder.session(session);
}
return mock.perform(requestBuilder).andExpect(resultMatcher).andDo(print()).andReturn();
}
}
|
923649a857c5e393cc2756b7347dfb47c553e3da | 4,817 | java | Java | src/main/java/org/wcdevs/blog/cdk/DeploymentSequencerStack.java | lealceldeiro/org.wcdevs.blog.cdk | 1672953e966ece16cf0d650089b751d55a613bac | [
"Apache-2.0"
] | 1 | 2021-11-05T09:42:59.000Z | 2021-11-05T09:42:59.000Z | src/main/java/org/wcdevs/blog/cdk/DeploymentSequencerStack.java | lealceldeiro/org.wcdevs.blog.cdk | 1672953e966ece16cf0d650089b751d55a613bac | [
"Apache-2.0"
] | 47 | 2021-09-23T16:01:50.000Z | 2022-02-26T09:48:22.000Z | src/main/java/org/wcdevs/blog/cdk/DeploymentSequencerStack.java | lealceldeiro/org.wcdevs.blog.cdk | 1672953e966ece16cf0d650089b751d55a613bac | [
"Apache-2.0"
] | null | null | null | 40.822034 | 100 | 0.667635 | 997,617 | package org.wcdevs.blog.cdk;
import lombok.AccessLevel;
import lombok.Getter;
import software.amazon.awscdk.Environment;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.StackProps;
import software.amazon.awscdk.services.events.targets.LambdaFunction;
import software.amazon.awscdk.services.lambda.Code;
import software.amazon.awscdk.services.lambda.Function;
import software.amazon.awscdk.services.lambda.FunctionProps;
import software.amazon.awscdk.services.lambda.Runtime;
import software.amazon.awscdk.services.lambda.eventsources.SqsEventSource;
import software.amazon.awscdk.services.logs.RetentionDays;
import software.amazon.awscdk.services.sqs.Queue;
import software.constructs.Construct;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public final class DeploymentSequencerStack extends Stack {
private static final String GITHUB_TOKEN_KEY = "GITHUB_TOKEN";
private static final String QUEUE_URL_KEY = "QUEUE_URL";
private static final String REGION_KEY = "REGION";
private static final String FUNCTION_ID = "depSeqFun";
private DeploymentSequencerStack(Construct scope, String id, StackProps props) {
super(Objects.requireNonNull(scope), Objects.requireNonNull(id), Objects.requireNonNull(props));
}
public static DeploymentSequencerStack newInstance(Construct scope, Environment awsEnvironment,
ApplicationEnvironment applicationEnvironment,
InputParameters inputParameters) {
var inParams = Objects.requireNonNull(inputParameters);
var appEnv = Objects.requireNonNull(applicationEnvironment);
var name = appEnv.prefixed(Util.joinedString(Util.DASH_JOINER, "deployment", "seq", "stack"));
var stackProps = StackProps.builder()
.stackName(name)
.env(awsEnvironment)
.build();
var stack = new DeploymentSequencerStack(scope, name, stackProps);
var queueName = appEnv.prefixed(inParams.getQueueName());
var deploymentQueue = Queue.Builder.create(stack, queueName)
.queueName(queueName)
.fifo(inParams.isFifo())
.build();
var eventSource = SqsEventSource.Builder.create(deploymentQueue).build();
var code = Code.fromAsset(Objects.requireNonNull(inParams.getCodeDirectory()));
var envVars = Map.of(inParams.getGithubTokenKey(),
Objects.requireNonNull(inParams.getGithubToken()),
inParams.getQueueUrlKey(),
Objects.requireNonNull(deploymentQueue.getQueueUrl()),
inParams.getRegionKey(),
Objects.requireNonNull(awsEnvironment.getRegion()));
var functionProps
= FunctionProps.builder()
.code(code)
.runtime(inParams.getRuntime())
.handler(inParams.getHandler())
.logRetention(inParams.getLogRetentionDays())
.reservedConcurrentExecutions(inParams.getReservedConcurrentExecutions())
.events(List.of(eventSource))
.environment(envVars)
.build();
var fnId = appEnv.prefixed(FUNCTION_ID);
LambdaFunction.Builder.create(new Function(stack, fnId, functionProps)).build();
return stack;
}
@lombok.Builder
@Getter(AccessLevel.PACKAGE)
public static class InputParameters {
private static final String FIFO_SUFFIX = ".fifo";
private static final String QUEUE_ID = "depQueue";
/**
* Path to the ZIP file containing the lambda function. This attribute is required.
*/
private String codeDirectory;
/**
* This attribute is required.
*/
private String githubToken;
@lombok.Builder.Default
private boolean fifo = true;
@lombok.Builder.Default
private String queueName = QUEUE_ID;
@lombok.Builder.Default
private Runtime runtime = Runtime.NODEJS_12_X;
@lombok.Builder.Default
private String handler = "index.handler";
@lombok.Builder.Default
private RetentionDays logRetentionDays = RetentionDays.TWO_WEEKS;
@lombok.Builder.Default
private int reservedConcurrentExecutions = 1;
@lombok.Builder.Default
private String githubTokenKey = GITHUB_TOKEN_KEY;
@lombok.Builder.Default
private String queueUrlKey = QUEUE_URL_KEY;
@lombok.Builder.Default
private String regionKey = REGION_KEY;
String getQueueName() {
return this.queueName + suffix();
}
private String suffix() {
return isFifo() ? FIFO_SUFFIX : "";
}
}
}
|
92364a2fc7bd2e85dbd392719bd46c8ec0f4f1dc | 1,371 | java | Java | src/main/java/dev/emi/trinkets/mixin/client/AbstractInventoryScreenMixin.java | florensie/trinkets | 35f0c80f66db33232e68fb76b29131a5b815831d | [
"MIT"
] | null | null | null | src/main/java/dev/emi/trinkets/mixin/client/AbstractInventoryScreenMixin.java | florensie/trinkets | 35f0c80f66db33232e68fb76b29131a5b815831d | [
"MIT"
] | null | null | null | src/main/java/dev/emi/trinkets/mixin/client/AbstractInventoryScreenMixin.java | florensie/trinkets | 35f0c80f66db33232e68fb76b29131a5b815831d | [
"MIT"
] | null | null | null | 31.159091 | 102 | 0.792852 | 997,618 | package dev.emi.trinkets.mixin.client;
import net.minecraft.client.gui.screen.ingame.HandledScreen;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.screen.ScreenHandler;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.screen.ingame.AbstractInventoryScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.text.Text;
/**
* Changes the rendering order of potion effects
*/
@Environment(EnvType.CLIENT)
@Mixin(AbstractInventoryScreen.class)
public abstract class AbstractInventoryScreenMixin<T extends ScreenHandler> extends HandledScreen<T> {
@Shadow
protected boolean drawStatusEffects;
public AbstractInventoryScreenMixin(T screenHandler, PlayerInventory inventory, Text text) {
super(screenHandler, inventory, text);
}
@Shadow
protected abstract void drawStatusEffects(MatrixStack matrices);
/**
* I was getting compiler warnings without this comment
* @author Emi
* @reason Had to change render order
*/
@Overwrite
public void render(MatrixStack matrices, int left, int top, float f) {
if (this.drawStatusEffects) {
this.drawStatusEffects(matrices);
}
super.render(matrices, left, top, f);
}
} |
92364c7b2e3cf4798b730329a99c60d2cb00137c | 1,565 | java | Java | app/src/main/java/com/mytian/lb/bean/user/UserResult.java | tengbinlive/aibao_demo | a7b89e0d8ebb16052887be5107ce7b7ff5401e47 | [
"Apache-2.0"
] | 65 | 2016-03-16T07:12:25.000Z | 2020-09-01T13:10:17.000Z | app/src/main/java/com/mytian/lb/bean/user/UserResult.java | tengbinlive/aibao_demo | a7b89e0d8ebb16052887be5107ce7b7ff5401e47 | [
"Apache-2.0"
] | 1 | 2016-03-18T07:14:35.000Z | 2016-03-18T09:36:50.000Z | app/src/main/java/com/mytian/lb/bean/user/UserResult.java | tengbinlive/aibao_demo | a7b89e0d8ebb16052887be5107ce7b7ff5401e47 | [
"Apache-2.0"
] | 12 | 2016-03-18T01:13:05.000Z | 2019-06-03T08:01:31.000Z | 40.128205 | 745 | 0.580831 | 997,619 | package com.mytian.lb.bean.user;
import com.alibaba.fastjson.JSON;
import com.core.openapi.OpenApiSimpleResult;
import com.dao.Parent;
/**
* 登录返回数据
* Created by bin.teng on 2015/10/28.
*/
public class UserResult extends OpenApiSimpleResult {
public final static int WOMAN = 0;
public final static int MAN = 1;
private Parent parent;
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
public static UserResult testData() {
String jsonStr = "{\"result\":1,\"description\":\"登录成功\",\"parent\":{\"uid\":50000001,\"createTime\":1453369278947,\"birthday\":0,\"sex\":1,\"phone\":\"13120979267\",\"appointId\":0,\"password\":\"\",\"sysThumbId\":100400,\"id\":41,\"isOnline\":1,\"obj3\":\"\",\"obj4\":\"\",\"time\":0,\"thumbType\":1,\"obj5\":\"\",\"obj6\":\"\",\"token\":\"8d090f04-9503-4ed0-a0b2-bfeb8960a096\",\"obj1\":\"\",\"name\":\"\",\"obj2\":\"\",\"verificationCode\":\"\",\"headThumb\":\"http://mytianimg.oss-cn-shanghai.aliyuncs.com/896C8F81BD156B92FF0260ACC2A901F2.jpg\",\"idCard\":\"\",\"updateTime\":0,\"status\":1,\"channelId\":\"\",\"alias\":\"嘘嘘\",\"obj7\":\"\",\"babyUid\":0,\"appointTime\":0,\"cmd\":0,\"category\":0,\"isIos\":0,\"realName\":\"\"}}";
UserResult result = JSON.parseObject(jsonStr, UserResult.class);
return result;
}
@Override
public String toString() {
return "UserResult{" +
"parent=" + parent +
'}';
}
}
|
92364cea1432ae3c69dfd89c393e4c7dfec6dafb | 983 | java | Java | src/test/java/info/estebanluengo/alfrescoAPI/test/AlfrescoAPITestSuite.java | estebanluengo/alfrescoAPI | c34b70d9aab7756b438acebf433bded311e80acd | [
"Apache-2.0"
] | null | null | null | src/test/java/info/estebanluengo/alfrescoAPI/test/AlfrescoAPITestSuite.java | estebanluengo/alfrescoAPI | c34b70d9aab7756b438acebf433bded311e80acd | [
"Apache-2.0"
] | null | null | null | src/test/java/info/estebanluengo/alfrescoAPI/test/AlfrescoAPITestSuite.java | estebanluengo/alfrescoAPI | c34b70d9aab7756b438acebf433bded311e80acd | [
"Apache-2.0"
] | null | null | null | 30.71875 | 76 | 0.744659 | 997,620 | /**
* Copyright 2015 Esteban Luengo Simón
*
* 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 info.estebanluengo.alfrescoAPI.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* A TestSuite to make a test using AlfrescoAPI
*
* @author Esteban Luengo Simón
* @version 1.0 11/May/2015
*/
@Suite.SuiteClasses({AlfrescoAPICRUDTest.class, AlfrescoAPIQueryTest.class})
@RunWith(Suite.class)
public class AlfrescoAPITestSuite {
}
|
92364d4b68f52d7fb3b499d350e6858da706764f | 999 | java | Java | encryption/encryption-api/src/main/java/com/quorum/tessera/nacl/KeyPair.java | aristt/tessera | 87fbb657cce9a67c4f0a7d60eb7e281b757bf735 | [
"Apache-2.0"
] | null | null | null | encryption/encryption-api/src/main/java/com/quorum/tessera/nacl/KeyPair.java | aristt/tessera | 87fbb657cce9a67c4f0a7d60eb7e281b757bf735 | [
"Apache-2.0"
] | null | null | null | encryption/encryption-api/src/main/java/com/quorum/tessera/nacl/KeyPair.java | aristt/tessera | 87fbb657cce9a67c4f0a7d60eb7e281b757bf735 | [
"Apache-2.0"
] | null | null | null | 23.232558 | 74 | 0.656657 | 997,621 | package com.quorum.tessera.nacl;
import java.util.Objects;
/**
* Container object for a public/private key pair
*
* The public and private key should be related to each other, not just an
* arbitrary pairing of two keys
*/
public class KeyPair {
private final Key publicKey;
private final Key privateKey;
public KeyPair(final Key publicKey, final Key privateKey) {
this.publicKey = Objects.requireNonNull(publicKey);
this.privateKey = Objects.requireNonNull(privateKey);
}
public Key getPublicKey() {
return publicKey;
}
public Key getPrivateKey() {
return privateKey;
}
@Override
public boolean equals(final Object o) {
return (o instanceof KeyPair) &&
Objects.equals(publicKey, ((KeyPair) o).publicKey) &&
Objects.equals(privateKey, ((KeyPair) o).privateKey);
}
@Override
public int hashCode() {
return Objects.hash(getPublicKey(), getPrivateKey());
}
}
|
92364e47ea4f8fffc9d209353445eedecd050e97 | 4,054 | java | Java | emp-platform/system/system-core/src/main/java/org/minxc/emp/system/core/manager/impl/SysAuthorizationManagerImpl.java | minxc/iEMPv7 | 428ba1b516fc0e0a6e6b345c8042e7aef0d14a63 | [
"Apache-2.0"
] | null | null | null | emp-platform/system/system-core/src/main/java/org/minxc/emp/system/core/manager/impl/SysAuthorizationManagerImpl.java | minxc/iEMPv7 | 428ba1b516fc0e0a6e6b345c8042e7aef0d14a63 | [
"Apache-2.0"
] | null | null | null | emp-platform/system/system-core/src/main/java/org/minxc/emp/system/core/manager/impl/SysAuthorizationManagerImpl.java | minxc/iEMPv7 | 428ba1b516fc0e0a6e6b345c8042e7aef0d14a63 | [
"Apache-2.0"
] | null | null | null | 34.355932 | 197 | 0.696349 | 997,622 | package org.minxc.emp.system.core.manager.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.minxc.emp.system.core.dao.SysAuthorizationDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.minxc.emp.base.core.util.BeanUtils;
import org.minxc.emp.base.core.util.StringUtil;
import org.minxc.emp.base.manager.impl.BaseManager;
import org.minxc.emp.organization.api.model.Group;
import org.minxc.emp.organization.api.service.GroupService;
import org.minxc.emp.system.api.constant.RightsObjectConstants;
import org.minxc.emp.system.core.manager.SystemAuthorizationManager;
import org.minxc.emp.system.core.model.SystemAuthorization;
import org.minxc.emp.system.util.ContextUtil;
@Service("sysAuthorizationManager")
public class SysAuthorizationManagerImpl extends BaseManager<String, SystemAuthorization> implements SystemAuthorizationManager {
@Resource
private SysAuthorizationDao sysAuthorizationDao;
@Autowired(required = false)
private GroupService userGroupService;
/**
* 获取用户的权限
* type-vale
*/
@Override
public Set<String> getUserRights(String userId) {
List<Group> list = userGroupService.getGroupsByUserId(userId);
Set<String> rights = new HashSet<String>();
rights.add(String.format("%s-%s", userId, SystemAuthorization.RIGHT_TYPE_USER));
rights.add(String.format("%s-%s", SystemAuthorization.RIGHT_TYPE_USER, SystemAuthorization.RIGHT_TYPE_ALL));
if (BeanUtils.isEmpty(list)) return rights;
for (Group group : list) {
rights.add(String.format("%s-%s", group.getGroupId(), group.getGroupType()));
}
return rights;
}
/**
* 获取用户的权限sql, sql中需要使用 ${rightsSql},若不使用可以使用 Set rights, 自行拼装
*
* @param targetKey 为permissionTarget的 字段ID
* 为授权对象名字
* @rightsSql = inner join sys_authorization rights on id_ = rights.rights_id_ and rights_permission_code_ in ( id-type,groupid-type )
*/
@Override
public Map<String, Object> getUserRightsSql(RightsObjectConstants rightsObject, String userId, String targetKey) {
if (StringUtil.isEmpty(targetKey)) {
targetKey = "id_";
}
StringBuffer sb = new StringBuffer();
Set<String> rights = getUserRights(userId);
for (String r : rights) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append("'").append(r).append("'");
}
sb.insert(0, "inner join sys_authorization rights on " + targetKey + " = rights.rights_target_ and rights.rights_object_ ='" + rightsObject.key() + "' and rights_permission_code_ in ( ");
sb.append(")");
Map<String, Object> param = new HashMap<String, Object>();
param.put("rightsSql", sb.toString());
param.put("rights", rights);
return param;
}
@Override
public List<SystemAuthorization> getByTarget(RightsObjectConstants rightsObject, String rightsTarget) {
return sysAuthorizationDao.getByTarget(rightsObject.key(), rightsTarget);
}
@Override
public void createAll(List<SystemAuthorization> sysAuthorizationList, String targetId, String targetObject) {
sysAuthorizationDao.deleteByTarget(targetObject, targetId);
for (SystemAuthorization authorization : sysAuthorizationList) {
authorization.setRightsPermissionCode(String.format("%s-%s", authorization.getRightsIdentity(), authorization.getRightsType()));
if (StringUtil.isEmpty(authorization.getRightsObject())) {
authorization.setRightsObject(targetObject);
}
authorization.setRightsCreateBy(ContextUtil.getCurrentUserId());
authorization.setRightsCreateTime(new Date());
sysAuthorizationDao.create(authorization);
}
}
}
|
92364f31467bdc3363025fc109632b1d0428d7ca | 454 | java | Java | src/test/java/services/TestingService.java | mohit-agrawal1989/SerenityAPIMukta | 0e3de15f50b669fb272fad6657a1014e9028fdbc | [
"MIT"
] | null | null | null | src/test/java/services/TestingService.java | mohit-agrawal1989/SerenityAPIMukta | 0e3de15f50b669fb272fad6657a1014e9028fdbc | [
"MIT"
] | null | null | null | src/test/java/services/TestingService.java | mohit-agrawal1989/SerenityAPIMukta | 0e3de15f50b669fb272fad6657a1014e9028fdbc | [
"MIT"
] | null | null | null | 26.705882 | 87 | 0.709251 | 997,623 | package services;
import helper.ApiHelper;
import io.restassured.response.Response;
import models.Postpets.PostPet;
public class TestingService extends ApiHelper {
public static Response getPetByStatus(String str) {
return getPetsData().when().queryParam("status", str).get("/pet/findByStatus");
}
public static Response postPet(PostPet pt) {
return getPetsData().body(gson().toJson(pt)).log().all().post("/pet");
}
}
|
92364f4fe20f8e1d7240f55d0ecffb83b813edd6 | 64,737 | java | Java | okapi/filters/mif/src/main/java/net/sf/okapi/filters/mif/MIFFilter.java | vistatec/vistatec-okapi | 17cd885f5fefd8236a95a0b203272795c42fea88 | [
"Apache-2.0"
] | 2 | 2018-08-15T02:40:30.000Z | 2019-12-20T12:43:56.000Z | okapi/filters/mif/src/main/java/net/sf/okapi/filters/mif/MIFFilter.java | vistatec/vistatec-okapi | 17cd885f5fefd8236a95a0b203272795c42fea88 | [
"Apache-2.0"
] | null | null | null | okapi/filters/mif/src/main/java/net/sf/okapi/filters/mif/MIFFilter.java | vistatec/vistatec-okapi | 17cd885f5fefd8236a95a0b203272795c42fea88 | [
"Apache-2.0"
] | 1 | 2019-08-21T06:22:25.000Z | 2019-08-21T06:22:25.000Z | 28.04896 | 121 | 0.621484 | 997,624 | /*===========================================================================
Copyright (C) 2008-2012 by the Okapi Framework contributors
-----------------------------------------------------------------------------
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
===========================================================================*/
package net.sf.okapi.filters.mif;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.okapi.common.BOMAwareInputStream;
import net.sf.okapi.common.Event;
import net.sf.okapi.common.EventType;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.MimeTypeMapper;
import net.sf.okapi.common.UsingParameters;
import net.sf.okapi.common.Util;
import net.sf.okapi.common.encoder.EncoderContext;
import net.sf.okapi.common.encoder.EncoderManager;
import net.sf.okapi.common.exceptions.OkapiBadFilterInputException;
import net.sf.okapi.common.exceptions.OkapiIOException;
import net.sf.okapi.common.exceptions.OkapiIllegalFilterOperationException;
import net.sf.okapi.common.exceptions.OkapiUnsupportedEncodingException;
import net.sf.okapi.common.filters.FilterConfiguration;
import net.sf.okapi.common.filters.FilterUtil;
import net.sf.okapi.common.filters.IFilter;
import net.sf.okapi.common.filters.IFilterConfigurationMapper;
import net.sf.okapi.common.filters.InlineCodeFinder;
import net.sf.okapi.common.filterwriter.IFilterWriter;
import net.sf.okapi.common.resource.Code;
import net.sf.okapi.common.resource.DocumentPart;
import net.sf.okapi.common.resource.Ending;
import net.sf.okapi.common.resource.ITextUnit;
import net.sf.okapi.common.resource.RawDocument;
import net.sf.okapi.common.resource.StartDocument;
import net.sf.okapi.common.resource.StartGroup;
import net.sf.okapi.common.resource.TextFragment;
import net.sf.okapi.common.resource.TextFragment.TagType;
import net.sf.okapi.common.resource.TextUnit;
import net.sf.okapi.common.skeleton.GenericSkeleton;
import net.sf.okapi.common.skeleton.GenericSkeletonPart;
import net.sf.okapi.common.skeleton.GenericSkeletonWriter;
import net.sf.okapi.common.skeleton.ISkeletonWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@UsingParameters(Parameters.class)
public class MIFFilter implements IFilter {
public static final String FRAMEROMAN = "x-FrameRoman";
static final String ILC_START = "\u169b"; // Rarely used character
static final char ILC_END = '\u169c'; // Rarely used character
private final Logger logger = LoggerFactory.getLogger(getClass());
private static final int BLOCKTYPE_TEXTFLOW = 1;
private static final int BLOCKTYPE_TABLE = 2;
private static final Hashtable<String, String> charTable = initCharTable();
private static final Hashtable<String, String> encodingTable = initEncodingTable();
private static final String TOPSTATEMENTSTOSKIP = "ColorCatalog;ConditionCatalog;BoolCondCatalog;"
+ "CombinedFontCatalog;PgfCatalog;ElementDefCatalog;FmtChangeListCatalog;DefAttrValuesCatalog;"
+ "AttrCondExprCatalog;FontCatalog;RulingCatalog;TblCatalog;KumihanCatalog;Views;"
+ "MarkerTypeCatalog;XRefFormats;Document;BookComponent;InitialAutoNums;Dictionary;AFrames;Page;"; // Must end with ';'
private static final String IMPORTOBJECT = "ImportObject";
private static final String MIFSTRING_MIME_TYPE = "application/x-mifstring";
private Parameters params;
private String lineBreak;
private String docName;
private BufferedReader reader;
private StringBuilder tagBuffer;
private StringBuilder strBuffer;
private int tuId;
private int otherId;
private int grpId;
private boolean canceled;
private LinkedList<Event> queue;
private LocaleId srcLang;
private GenericSkeleton skel;
private boolean hasNext;
private EncoderManager encoderManager;
private int inBlock;
private int blockLevel;
private double dbVersion;
private int paraLevel;
private StringBuilder paraSkelBuf;
private StringBuilder paraTextBuf;
private StringBuilder paraCodeBuf;
private StringBuilder paraCodeTypes;
private int tableGroupLevel;
private int rowGroupLevel;
private int cellGroupLevel;
private int fnoteGroupLevel;
private Stack<String> parentIds;
private ArrayList<Integer> textFlows;
private ArrayList<String> tables;
private boolean secondPass;
private ByteArrayOutputStream byteStream;
private FrameRomanCharsetProvider csProvider;
private CharsetDecoder[] decoders;
private boolean[] doubleConversion;
private CharsetDecoder firstDecoder;
private CharsetEncoder[] encoders;
private CharsetDecoder currentDecoder;
private boolean doDoubleConversion;
private int currentCharsetIndex;
private MIFEncoder encoder;
private int decodingErrors;
private String baseEncoding;
private boolean useUTF;
private String resname;
private int footnotesLevel;
private int textFlowNumber;
private ITextUnit refTU;
private RawDocument input;
private static Hashtable<String, String> initCharTable () {
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("Tab", "\t");
table.put("HardSpace", "\u00a0"); // = Unicode non-breaking space
table.put("SoftHyphen", ""); // "\u2010" = Unicode Hyphen (not Soft-Hyphen), but we remove those
table.put("HardHyphen", "\u2011"); // = Unicode Non-Breaking Hyphen
table.put("DiscHyphen", "\u00ad"); // = Unicode Soft-Hyphen
table.put("NoHyphen", "\u200d"); // = Unicode Zero-Width Joiner
table.put("Cent", "\u00a2");
table.put("Pound", "\u00a3");
table.put("Yen", "\u00a5");
table.put("EnDash", "\u2013");
table.put("EmDash", "\u2014");
table.put("Dagger", "\u2020");
table.put("DoubleDagger", "\u2021");
table.put("Bullet", "\u2022");
table.put("HardReturn", "\n");
table.put("NumberSpace", "\u2007");
table.put("ThinSpace", "\u2009");
table.put("EnSpace", "\u2002");
table.put("EmSpace", "\u2003");
return table;
}
private static Hashtable<String, String> initEncodingTable () {
Hashtable<String, String> table = new Hashtable<String, String>();
// Map the Java canonical charset names
table.put("FrameRoman", FRAMEROMAN);
table.put("JISX0208.ShiftJIS", "Shift_JIS");
table.put("BIG5", "Big5");
table.put("GB2312-80.EUC", "GB2312");
table.put("KSC5601-1992", "EUC-KR");
return table;
}
public MIFFilter () {
params = new Parameters();
}
@Override
public void cancel () {
canceled = true;
}
@Override
public void close () {
if (input != null) {
input.close();
}
try {
if ( reader != null ) {
reader.close();
reader = null;
}
hasNext = false;
docName = null;
}
catch ( IOException e ) {
throw new OkapiIOException(e);
}
}
@Override
public String getName () {
return "okf_mif";
}
@Override
public String getDisplayName () {
return "MIF Filter";
}
@Override
public String getMimeType () {
return MimeTypeMapper.MIF_MIME_TYPE;
}
@Override
public List<FilterConfiguration> getConfigurations () {
List<FilterConfiguration> list = new ArrayList<FilterConfiguration>();
list.add(new FilterConfiguration(getName(),
MimeTypeMapper.MIF_MIME_TYPE,
getClass().getName(),
"MIF (BETA)",
"Adobe FrameMaker MIF documents",
null,
".mif;"));
return list;
}
@Override
public EncoderManager getEncoderManager () {
if ( encoderManager == null ) {
encoderManager = new EncoderManager();
encoderManager.setMapping(MimeTypeMapper.MIF_MIME_TYPE, "net.sf.okapi.filters.mif.MIFEncoder");
encoderManager.setMapping(MIFSTRING_MIME_TYPE, "net.sf.okapi.filters.mif.MIFStringEncoder");
}
return encoderManager;
}
@Override
public Parameters getParameters () {
return params;
}
@Override
public boolean hasNext () {
return hasNext;
}
@Override
public void open (RawDocument input) {
open(input, true);
}
@Override
public void open (RawDocument input,
boolean generateSkeleton)
{
this.input = input;
if (( input.getInputURI() == null ) && ( input.getInputCharSequence() == null )) {
// Cannot do this currently because of the double pass
throw new OkapiBadFilterInputException("Direct stream input not supported for MIF.");
}
srcLang = input.getSourceLocale();
if ( input.getInputURI() != null ) {
docName = input.getInputURI().getPath();
}
input.setEncoding("UTF-8");
open(input.getStream(), input);
}
private void initialize () {
tagBuffer = new StringBuilder();
strBuffer = new StringBuilder();
paraSkelBuf = new StringBuilder();
paraCodeBuf = new StringBuilder();
paraCodeTypes = new StringBuilder();
paraTextBuf = new StringBuilder();
tuId = 0;
otherId = 0;
grpId = 0;
canceled = false;
hasNext = true;
inBlock = 0;
blockLevel = 0;
lineBreak = "\n"; //TODO: Get from input file
tableGroupLevel = -1;
rowGroupLevel = -1;
cellGroupLevel = -1;
fnoteGroupLevel = -1;
parentIds = new Stack<String>();
encoder = new MIFEncoder();
decodingErrors = 0;
footnotesLevel = -1;
textFlowNumber = 0;
}
private void open (InputStream input,
RawDocument rd)
{
try {
//--- First pass: gather information
csProvider = new FrameRomanCharsetProvider();
dbVersion = 0.0;
// Detect encoding
InputStream bomAwareInput = guessEncoding(input);
// Use directly a decoder to allow the MIF-specific encoder without having to register it
CharsetDecoder decoder;
if ( baseEncoding.equals(FRAMEROMAN) ) {
decoder = csProvider.charsetForName(FRAMEROMAN).newDecoder();
}
else {
decoder = Charset.forName(baseEncoding).newDecoder();
}
reader = new BufferedReader(new InputStreamReader(bomAwareInput, decoder)); //(InputStream)res[0], decoder));
initialize();
secondPass = false;
textFlows = new ArrayList<Integer>();
tables = new ArrayList<String>();
gatherExtractionInformation();
reader.close();
input.close();
//--- Second pass: extract
secondPass = true;
input = rd.getStream();
// The base encoding was detected before the first pass, so the decoder is already set
// But we do call guessEncoding to handle the possible BOM
bomAwareInput = guessEncoding(input);
reader = new BufferedReader(new InputStreamReader(bomAwareInput, decoder));
initialize();
String sdId = rd.getId();
if ( Util.isEmpty(sdId) ) sdId = "sd1";
parentIds.push(sdId);
// Compile code finder rules
if ( params.getUseCodeFinder() ) {
params.getCodeFinder().compile();
}
// Initialize the decoders
firstDecoder = csProvider.charsetForName(FRAMEROMAN).newDecoder();
// firstEncoder = Charset.forName("Windows-1252").newEncoder();
currentCharsetIndex = 0;
doubleConversion = new boolean[2];
doubleConversion[0] = false;
doubleConversion[1] = false;
doDoubleConversion = doubleConversion[currentCharsetIndex];
decoders = new CharsetDecoder[2];
if ( baseEncoding.equals(FRAMEROMAN) ) {
decoders[0] = firstDecoder;
}
else {
decoders[0] = Charset.forName(baseEncoding).newDecoder();
}
decoders[1] = decoders[0]; // Use the same to start
currentDecoder = decoders[currentCharsetIndex];
encoders = new CharsetEncoder[2];
if ( baseEncoding.equals(FRAMEROMAN) ) {
encoders[0] = csProvider.charsetForName(baseEncoding).newEncoder();
}
else {
encoders[0] = Charset.forName(baseEncoding).newEncoder();
}
encoders[1] = encoders[0];
byteStream = new ByteArrayOutputStream(20);
queue = new LinkedList<Event>();
StartDocument startDoc = new StartDocument(sdId);
startDoc.setName(docName);
startDoc.setLineBreak(lineBreak);
startDoc.setEncoding(baseEncoding, false);
// We assume no BOM in all case for MIF
startDoc.setLocale(srcLang);
startDoc.setFilterParameters(getParameters());
startDoc.setFilterWriter(createFilterWriter());
startDoc.setType(getMimeType());
startDoc.setMimeType(getMimeType());
queue.add(new Event(EventType.START_DOCUMENT, startDoc));
// load simplifier rules and send as an event
if (!Util.isEmpty(((Parameters)getParameters()).getSimplifierRules())) {
Event cs = FilterUtil.createCodeSimplifierEvent(((Parameters)getParameters()).getSimplifierRules());
queue.add(cs);
}
}
catch ( UnsupportedEncodingException e ) {
throw new OkapiUnsupportedEncodingException("Error reading MIF input.", e);
}
catch ( IOException e ) {
throw new OkapiIOException("Error reading MIF input.", e);
}
}
@Override
public void setFilterConfigurationMapper (IFilterConfigurationMapper fcMapper) {
// Not used
}
@Override
public void setParameters (IParameters params) {
this.params = (Parameters)params;
}
@Override
public Event next () {
// Treat cancel
if ( canceled ) {
queue.clear();
queue.add(new Event(EventType.CANCELED));
hasNext = false;
}
// Fill the queue if it's empty
if ( queue.isEmpty() ) {
read();
}
// Update hasNext flag on the FINISHED event
if ( queue.peek().getEventType() == EventType.END_DOCUMENT ) {
hasNext = false;
}
// Return the head of the queue
return queue.poll();
}
@Override
public ISkeletonWriter createSkeletonWriter () {
return new GenericSkeletonWriter();
}
@Override
public IFilterWriter createFilterWriter () {
return new MIFFilterWriter(createSkeletonWriter(), getEncoderManager());
}
/**
* Top-level read
*/
private void read () {
try {
skel = new GenericSkeleton();
int c;
// Check if we are still processing a TextFlow
if ( inBlock > 0 ) {
processBlock(inBlock, false);
return;
}
while ( (c = reader.read()) != -1 ) {
switch ( c ) {
case '#':
skel.append((char)c);
readComment(true, null);
break;
case '<': // Start of statement
skel.append((char)c);
blockLevel++;
String tag = readTag(true, true, null);
if ( TOPSTATEMENTSTOSKIP.indexOf(tag+";") > -1 ) {
skipOverContent(true, null);
blockLevel--;
}
else if ( "TextFlow".equals(tag) ) {
textFlowNumber++;
if ( startBlock(blockLevel, BLOCKTYPE_TEXTFLOW) ) return;
}
else if ( "Tbls".equals(tag) ) {
// Do nothing, but do not skip.
// The tables will be read in Tbl tags
continue;
}
else if ( "Tbl".equals(tag) ) {
if ( startBlock(blockLevel, BLOCKTYPE_TABLE) ) return;
}
else if ( "VariableFormats".equals(tag) ) {
if ( params.getExtractVariables() ) {
processVariables();
}
else {
skipOverContent(true, null);
blockLevel--;
}
}
else if ( "MIFFile".equals(tag) ) {
// Version was read already
// Just do nothing, except fill the skeleton
getNextTokenInStatement(true, null, true);
}
else {
// Default: skip over
skipOverContent(true, null);
blockLevel--;
}
// Flush the skeleton from time to time to allow very large files
queue.add(new Event(EventType.DOCUMENT_PART,
new DocumentPart(String.valueOf(++otherId), false),
skel));
return;
case '>': // End of statement
skel.append((char)c);
blockLevel--;
// Return skeleton
DocumentPart dp = new DocumentPart(String.valueOf(++otherId), false, skel);
queue.add(new Event(EventType.DOCUMENT_PART, dp));
return;
default:
skel.append((char)c);
break;
}
}
// We are done
Ending ending = new Ending(String.valueOf(++otherId));
queue.add(new Event(EventType.END_DOCUMENT, ending, skel));
}
catch ( IOException e ) {
throw new OkapiIOException(e);
}
}
/**
* Gather the information about what to extract.
* This method create a list of all text flow and table to extract, based
* on the filter's options.
*/
private void gatherExtractionInformation () {
try {
int c;
MIFToken token;
boolean inEscape = false;
boolean inString = false;
ArrayList<String> trToExtract = new ArrayList<String>();
ArrayList<String> tblIds = new ArrayList<String>();
boolean hasPages = false; // Simple MIF may not have any page
while ( true ) {
int res = -1;
while ( res == -1 ) {
c = reader.read();
// Parse a string content
if ( inString ) {
if ( c == '\'' ) inString = false;
continue;
}
// Else: we are outside a string
if ( inEscape ) {
inEscape = false;
}
else {
switch ( c ) {
case -1:
if ( !hasPages ) {
textFlows = null;
tables = null;
}
return; // No more data
case '`':
inString = true;
break;
case '\\':
inEscape = true;
break;
case '<':
blockLevel++;
res = 1;
break;
case '>':
blockLevel--;
res = 0;
break;
}
}
}
// Res can be 0 or 1 here
if ( res == 1 ) {
// We reached an opening <
// Get the tag name
String tag = readTag(false, false, null);
if ( tag.equals("Page") ) {
// If it's a Page: get the first TextRect id and the type
String pageType = null;
String textRectId = null;
hasPages = true;
while ( true ) {
tag = readUntil("PageType;TextRect;", false, null, blockLevel, true);
if ( tag == null ) {
// One of PageType or TextRect was not in the page
break;
}
// Else it's a PageType or a TextRect
if ( tag.equals("PageType") ) {
token = getNextTokenInStatement(false, null, true);
if ( token.getType() == MIFToken.TYPE_STRING ) {
pageType = token.getString();
}
else {
// Error: Missing page type value.
throw new OkapiIOException("Missing PageType value.");
}
if ( textRectId != null ) break;
}
else if ( tag.equals("TextRect") ) {
while ( true ) {
tag = readUntil("ID;", false, null, blockLevel, true);
if ( tag != null ) {
// Found
token = getNextTokenInStatement(false, null, true);
if ( token.getType() == MIFToken.TYPE_STRING ) {
textRectId = token.getString();
}
else {
// Error: Missing ID value
throw new OkapiIOException("Missing ID value.");
}
}
else {
// Error ID not found
throw new OkapiIOException("ID statement not found.");
}
break;
}
if ( pageType != null ) break;
}
} // End of while
// We have looked at the page data
if ( !Util.isEmpty(pageType) && !Util.isEmpty(textRectId) ) {
if ( pageType.equals("BodyPage") ) {
if ( params.getExtractBodyPages() ) {
trToExtract.add(textRectId);
}
}
else if ( pageType.equals("ReferencePage") ) {
if ( params.getExtractReferencePages() ) {
trToExtract.add(textRectId);
}
}
else if ( pageType.equals("HiddenPage") ) {
if ( params.getExtractHiddenPages() ) {
trToExtract.add(textRectId);
}
}
else if ( pageType.endsWith("MasterPage") ) {
if ( params.getExtractMasterPages() ) {
trToExtract.add(textRectId);
}
}
else {
// Else: unexpected type of page: extract it just in case
trToExtract.add(textRectId);
logger.warn("Unknown page type '{}' (It will be extracted)", pageType);
}
}
}
else if ( tag.equals("TextFlow") ) {
// Check which text flows have table reference,
// So we know which one to extract during the second pass
textFlowNumber++;
String textRectId = null;
boolean textRectDone = false;
// Next harvest the Para groups
// to get the first TextRectID and all ATbl in the ParaLine entries
int tfLevel = blockLevel;
while ( true ) {
if ( readUntil("Para;", false, null, tfLevel, true) == null ) {
break; // Done
}
tblIds.clear(); // Hold all table references for this paragraph
// Inside a Para:
while ( true ) {
if ( readUntil("ParaLine;", false, null, blockLevel, true) == null ) {
break; // Done for this Para
}
textRectDone = false; // reset per every paragraph line
// Else: inside a ParaLine
while ( true ) {
tag = readUntil("TextRectID;ATbl;", false, null, blockLevel, true);
if ( tag == null ) {
break; // Done
}
if ( !textRectDone && tag.equals("TextRectID") ) {
token = getNextTokenInStatement(false, null, true);
if ( token.getType() == MIFToken.TYPE_STRING ) {
textRectId = token.getString();
// A FNote may occur before the Para that holds the key TextRect id
// so we don't count them if we are inside a FNote group
if ( fnoteGroupLevel == -1 ) {
textRectDone = true;
}
}
}
else if ( tag.equals("ATbl") ) {
token = getNextTokenInStatement(false, null, true);
if ( token.getType() == MIFToken.TYPE_STRING ) {
tblIds.add(token.getString());
}
}
}
}
// Check the TextRect id against the ones found for the pages
if ( trToExtract.contains(textRectId) ) {
// This text flow is to be extracted
// and so are any table referenced in it
textFlows.add(textFlowNumber);
tables.addAll(tblIds);
}
}
}
else if ( tag.equals(IMPORTOBJECT) ) {
skipOverImportObject(false, null);
blockLevel--;
}
else if ( tag.equals("PgfCatalog") ) {
// Gather the encoding information for the paragraph formats
// based on the font and font encodings
int level = blockLevel;
while ( true ) {
if ( readUntil("Pgf;", false, null, level, true) == null ) {
break; // Done
}
// Inside a Pgf:
while ( true ) {
tag = readUntil("PgfTag;PgfFont;", false, null, blockLevel, true);
if ( tag == null ) {
break; // Done
}
else if ( tag.equals("PgfTag") ) {
}
}
}
}
else if ( "MIFFile".equals(tag) ) {
token = getNextTokenInStatement(false, null, true);
if ( token.getType() == MIFToken.TYPE_STRING ) {
token.getString(); // Consume the version
// No need to store/convert it it was done already
}
else {
throw new OkapiIOException("MIF version not found.");
}
}
}
// Else: Ending of statement. Nothing to do
}
}
catch ( IOException e ) {
throw new OkapiIOException("Error while gathering extraction information.\n" +e.getMessage(), e);
}
finally {
}
}
/**
* Skips over the content of the current statement.
* Normally "<token" has been processed and level for after '<'
* @param store true to store in the skeleton
* @param buffer the StringBuilder object where to copy the content, or null to not copy.
* @throws IOException if an error occurs.
*/
private void skipOverContent (boolean store,
StringBuilder buffer)
throws IOException
{
int baseLevel = 1;
int state = 0;
int c;
while ( (c = reader.read()) != -1 ) {
// Store if needed
if ( store ) {
if ( buffer != null ) buffer.append((char)c);
else skel.append((char)c);
}
// Parse according current state
switch ( state ) {
case 0:
switch ( c ) {
case '`':
state = 1; // In string
continue;
case '\\':
state = 2; // In escape
continue;
case '<':
baseLevel++;
tagBuffer.setLength(0);
state = 3; // In tag buffer mode
continue;
case '>':
baseLevel--;
if ( baseLevel == 0 ) {
return;
}
continue;
}
// Else do nothing
continue;
case 1: // In string
if ( c == '\'' ) state = 0;
continue;
case 2: // In escape
state = 0; // Go back to normal
continue;
case 3: // In tag buffer mode
switch ( c ) {
case '>':
baseLevel--;
if ( baseLevel == 0 ) {
return;
}
// Fall thru
case ' ':
case '\t':
if ( tagBuffer.toString().equals(IMPORTOBJECT) ) {
skipOverImportObject(store, buffer);
baseLevel--;
}
state = 0;
continue;
default:
tagBuffer.append((char)c);
continue;
}
}
}
// Unexpected end
throw new OkapiIllegalFilterOperationException(
String.format("Unexpected end of input at state = %d", state));
}
private void readComment (boolean store,
StringBuilder sb)
throws IOException
{
int c;
while ( (c = reader.read()) != -1 ) {
if ( store ) {
if ( sb != null ) sb.append((char)c);
else skel.append((char)c);
}
switch ( c ) {
case '\r':
case '\n':
return;
}
}
// A comment can end the file
}
private boolean startBlock (int stopLevel,
int type)
throws IOException
{
if ( type == BLOCKTYPE_TABLE ) {
// Get the table id
String tag = readUntil("TblID;", true, null, stopLevel, true);
if ( tag == null ) {
// Error: ID missing
throw new OkapiIOException("Missing id for the table.");
}
MIFToken token = getNextTokenInStatement(true, null, true);
if ( token.getType() != MIFToken.TYPE_STRING ) {
throw new OkapiIOException("Missing id value for the table.");
}
// If the table is not listed as to be extracted: we skip it
if (( tables != null ) && !tables.contains(token.getString()) ) {
skipOverContent(true, null);
blockLevel--;
return false;
}
tableGroupLevel = blockLevel;
StartGroup sg = new StartGroup(parentIds.peek());
sg.setId(parentIds.push(String.valueOf(++grpId)));
sg.setType("table");
queue.add(new Event(EventType.START_GROUP, sg));
// If tables==null it's because we didn't have any page, so we extract by default
// Else: extract: use fall thru code
resname = null;
}
else if ( type == BLOCKTYPE_TEXTFLOW ) {
// If the text flow is not listed as to be extracted: we skip it
if (( textFlows != null ) && !textFlows.contains(textFlowNumber) ) {
skipOverContent(true, null);
blockLevel--;
return false;
}
resname = null;
// If textFlows==null it's because we didn't have any page, so we extract by default
// Else: extract: use fall thru code
}
// Extract
processBlock(stopLevel, false);
return true;
}
/**
* Process the first or next entry of a TextFlow statement.
* @throws IOException if a low-level error occurs.
*/
private void processBlock (int stopLevel,
boolean inPara)
throws IOException
{
// Process one Para statement at a time
if ( inPara ) {
inBlock = stopLevel; // We are not done yet with this TextFlow statement
processPara();
blockLevel--; // Closing the Para statement here
}
else {
if ( readUntil("Para;", true, null, stopLevel, false) != null ) {
inBlock = stopLevel; // We are not done yet with this TextFlow statement
processPara();
blockLevel--; // Closing the Para statement here
}
else { // Done
inBlock = 0; // We are done
// Note that the end-group for a table is send when we detect the closing '>'
}
}
// If needed, create a document part and return
if ( !skel.isEmpty() ) {
queue.add(new Event(EventType.DOCUMENT_PART,
new DocumentPart(String.valueOf(++otherId), false),
skel));
}
}
private void processPara ()
throws IOException
{
TextFragment tf = new TextFragment();
boolean first = true;
paraLevel = 1;
paraSkelBuf.setLength(0);
paraTextBuf.setLength(0);
paraCodeBuf.setLength(0);
paraCodeTypes.setLength(0);
String endString = null;
resetToDefaultDecoder();
Code code = null;
boolean extractedMarker = false;
// Go to the first ParaLine
int res = readUntilText(first, false);
while ( res > 0 ) {
// Get the text to append
switch ( res ) {
case 2: // Extracted marker
code = new Code(TagType.PLACEHOLDER, "index", "'>"+TextFragment.makeRefMarker(refTU.getId())+"<String `");
code.setReferenceFlag(true);
extractedMarker = true;
break;
}
if ( first ) {
if ( paraSkelBuf.length() > 0 ) {
skel.append(paraSkelBuf.toString());
skel.append("<String `");
endString = "'>";
}
first = false;
}
if ( paraCodeBuf.length() > 0 ) {
Code code2 = new Code(TagType.PLACEHOLDER,
(( paraCodeTypes.length() > 0 ) ? paraCodeTypes.toString() : "code"),
"'>"+paraCodeBuf.toString()+"<String `");
tf.append(code2);
}
if ( code != null ) {
tf.append(code);
code = null;
}
if ( paraTextBuf.length() > 0 ) {
tf.append(paraTextBuf.toString());
}
// Reset the codes buffer for next sequence
paraSkelBuf.setLength(0);
paraTextBuf.setLength(0);
paraCodeBuf.setLength(0);
paraCodeTypes.setLength(0);
// Move to the next text
res = readUntilText(first, false);
}
// Check for inline codes
checkInlineCodes(tf);
ITextUnit tu = null;
if ( !tf.isEmpty() ) {
if ( tf.hasText() || extractedMarker ) {
// Add the text unit to the queue
tu = new TextUnit(String.valueOf(++tuId));
tu.setPreserveWhitespaces(true);
tu.setSourceContent(tf);
tu.setMimeType(MimeTypeMapper.MIF_MIME_TYPE);
tu.setName(resname); resname = null;
processILC(tu);
queue.add(new Event(EventType.TEXT_UNIT, tu, skel));
// Try to simplify when there is only one leading code which is a font
if ( tf.getCodedText().charAt(0) == TextFragment.MARKER_ISOLATED ) {
if ( tf.getCodes().size() == 1 ) {
code = tf.getCode(0);
if ( code.getType().equals("font") ) {
// Only one code, it's leading and it's a font: we can move it to the skeleton
Code tmp = tf.getCode(0);
tf.remove(0, 2);
skel.append(tmp.toString());
}
}
}
// Add the TU place holder in the skeleton
skel.addContentPlaceholder(tu);
}
else { // No text (only codes and/or white spaces) Put back the content/codes in skeleton
// We need to escape the text parts (white spaces like tabs)
String ctext = tf.getCodedText();
StringBuilder tmp = new StringBuilder();
for ( int i=0; i<ctext.length(); i++ ) {
char ch = ctext.charAt(i);
if ( TextFragment.isMarker(ch) ) {
tmp.append(tf.getCode(ctext.charAt(++i)));
}
else {
tmp.append(encoder.encode(ch, EncoderContext.SKELETON));
}
}
GenericSkeletonPart part = skel.getLastPart();
if (( part == null ) || !part.getData().toString().endsWith("<String `") ) {
skel.append("<String `");
endString = "'>";
}
skel.append(tmp.toString());
}
}
if ( endString != null ) {
skel.append(endString);
}
// Ending part
if ( paraSkelBuf.length() > 0 ) {
skel.append(paraSkelBuf.toString());
}
if ( paraCodeBuf.length() > 0 ) {
skel.append(paraCodeBuf.toString());
}
if ( tu != null ) {
// New skeleton object for the next parts of the parent statement
skel = new GenericSkeleton();
}
}
private MIFToken getNextTokenInStatement (boolean store,
StringBuilder sb,
boolean updateBlockLevel)
throws IOException
{
int n;
boolean leadingWSDone = false;
do {
n = reader.read();
if ( store ) {
if ( sb != null ) sb.append((char)n);
else skel.add((char)n);
}
switch ( n ) {
case ' ':
case '\t':
case '\r':
case '\n':
break;
case -1:
throw new OkapiIllegalFilterOperationException("Unexpected end of input.");
default:
leadingWSDone = true;
break;
}
}
while ( !leadingWSDone );
StringBuilder tmp = new StringBuilder();
tmp.append((char)n);
do {
n = reader.read();
if ( store ) {
if ( sb != null ) sb.append((char)n);
else skel.add((char)n);
}
switch ( n ) {
//TODO: what if the token is a string?
case ' ':
case '\t':
case '\r':
case '\n':
case '>': // End of statement
MIFToken token = new MIFToken(tmp.toString());
token.setLast(n == '>');
if ( updateBlockLevel && token.isLast() ) {
blockLevel--;
}
return token;
case -1:
throw new OkapiIllegalFilterOperationException("Unexpected end of input.");
default:
tmp.append((char)n);
break;
}
}
while ( true );
}
private MIFToken processChar (boolean store)
throws IOException
{
// Get the next token: the name of the character
MIFToken token = getNextTokenInStatement(store, null, false);
if ( !token.isLast() ) {
skipOverContent(store, null);
}
// Default return is also a token
MIFToken chToken = new MIFToken();
// Map the character to its string, if possible
if ( token.getType() == MIFToken.TYPE_STRING ) {
String str = charTable.get(token.getString());
if ( str == null ) {
logger.warn("Unknow character name '{}'. This character will be ignored.", token);
}
else {
chToken.setString(str);
}
}
else {
// Invalid statement
logger.warn("Unexpected token is Char statement. This character will be ignored.");
}
return chToken;
}
/**
* Processes a <Marker entry.
* @return An array of objects: 0=StringBuilder of the skeleton or null,
* 1=Text unit if this is extractable or null.
*/
private Object[] processMarker ()
throws IOException
{
refTU = null;
int level = blockLevel;
StringBuilder sb = new StringBuilder("<Marker ");
Object[] res = new Object[2];
res[0] = sb;
res[1] = null;
String tag = readUntil("MTypeName;", true, sb, -1, true);
if ( tag == null ) {
logger.warn("Marker without type or text found. It will be skipped.");
skipOverContent(true, sb);
return res;
}
// Is it a marker we need to extract?
String type = processString(true, sb);
String resType = null;
if ( "Index".equals(type) ) {
if ( params.getExtractIndexMarkers() ) resType = "x-index";
}
else if ( "Hypertext".equals(type) ) {
if ( params.getExtractLinks() ) resType = "link";
}
if ( resType == null ) {
// Not to extract
skipOverContent(true, sb);
blockLevel = level;
return res;
}
// Else: it is to extract: get the string
tag = readUntil("MText;", true, sb, -1, true);
if ( tag == null ) {
skipOverContent(true, sb);
blockLevel = level;
return res; // Nothing to extract
}
TextFragment tf = new TextFragment(processString(true, sb));
checkInlineCodes(tf);
if ( tf.hasText() ) {
// If there is translatable parts: create a new text unit
refTU = new TextUnit(String.valueOf(++tuId));
refTU.setPreserveWhitespaces(true);
refTU.setSourceContent(tf);
refTU.setType(resType);
refTU.setIsReferent(true);
refTU.setMimeType(MIFSTRING_MIME_TYPE);
// Remove string
int n = sb.lastIndexOf("`");
sb.delete(n+1, sb.length());
GenericSkeleton refSkel = new GenericSkeleton(sb.toString());
refSkel.addContentPlaceholder(refTU);
sb.setLength(0);
sb.append("'>");
skipOverContent(true, sb);
refSkel.add(sb.toString());
processILC(refTU);
queue.add(new Event(EventType.TEXT_UNIT, refTU, refSkel));
sb = null; // Now it is in the text unit skeleton
res[1] = refTU;
}
else {
// Store the remaining part of the marker
skipOverContent(true, sb);
}
blockLevel = level;
return res;
}
/**
* Reads until the next text.
* @param startOfPara true to indicate a start of paragraph.
* @param significant indicates if the current buffer is significant or can be removed.
* Set always to false except sometimes when called recursively.
* @return 0=end of paragraph, 1=text, 2=marker
*/
private int readUntilText (boolean startOfPara,
boolean significant)
throws IOException
{
StringBuilder sb;
if ( startOfPara ) sb = paraSkelBuf;
else sb = paraCodeBuf;
int c;
while ( (c = reader.read()) != -1 ) {
switch ( c ) {
case '#':
sb.append((char)c);
readComment(true, sb);
break;
case '<': // Start of statement
paraLevel++;
sb.append((char)c);
String tag = readTag(true, false, sb);
if ( "ParaLine".equals(tag) ) {
if ( !startOfPara ) {
int n = sb.lastIndexOf("<");
if ( significant ) sb.delete(n, sb.length());
else sb.setLength(0);
}
return readUntilText(startOfPara, significant);
}
else if ( "String".equals(tag) ) {
String text = processString(false, null);
int n = sb.lastIndexOf("<");
if ( significant ) sb.delete(n, sb.length());
else sb.setLength(0);
paraLevel--;
if ( !Util.isEmpty(text) ) {
paraTextBuf.append(text);
return 1;
}
// Else: continue. This basically remove the empty string
}
else if ( "Char".equals(tag) ) {
String text = processChar(false).toString();
if ( !significant ) sb.setLength(0);
paraLevel--;
if ( !Util.isEmpty(text) ) {
paraTextBuf.append(text);
return 1;
}
}
else if ( "Marker".equals(tag) ) {
int n = sb.lastIndexOf("<Marker");
if ( significant ) sb.delete(n, sb.length());
else sb.setLength(0);
Object[] res = processMarker();
significant = true;
if ( paraCodeTypes.length() > 0 ) paraCodeTypes.append(";");
paraCodeTypes.append(tag.toLowerCase());
paraLevel--;
if ( res[1] != null ) { // We have a text unit
return 2;
}
// No text unit: nothing to extract
sb.append(res[0]);
}
else if ( !useUTF && "PgfTag".equals(tag) ) {
// Try to update the encoding based of the font for the given paragraph tag
processString(true, sb);
//for test
// String paraName = processString(true, sb);
// if ( "Haupttext".equals(paraName) ) {
// updateCurrentDecoder("windows-1253", true);
// }
significant = true;
if ( paraCodeTypes.length() > 0 ) paraCodeTypes.append(";");
paraCodeTypes.append(tag.toLowerCase());
paraLevel--;
}
else if ( "Font".equals(tag) ) {
// Do the font-driven encoding resolving only for non-UTF-8 files
//TODO: Is it safe? need to be verified
monitorFontEncoding(sb);
significant = true;
if ( paraCodeTypes.length() > 0 ) paraCodeTypes.append(";");
paraCodeTypes.append(tag.toLowerCase());
paraLevel--;
}
// Default: skip over
else {
skipOverContent(true, sb);
significant = true;
if ( paraCodeTypes.length() > 0 ) paraCodeTypes.append(";");
paraCodeTypes.append(tag.toLowerCase());
paraLevel--;
}
if ( startOfPara ) {
// Check for inline codes: tags that should be inline even when they are leading before any text
if ( "Font;Marker;Conditional;Unconditional;ATbl;AFrame;FNote;Variable;XRef;XRefEnd;".indexOf(tag) != -1 ) {
// Switch buffer
int n = sb.lastIndexOf("<"+tag+" ");
paraCodeBuf.append(sb.substring(n));
sb.delete(n, sb.length()); // Remove from buffer since it's in the code now
sb = paraCodeBuf;
paraCodeTypes.setLength(0); // Rest for inline codes
paraCodeTypes.append(tag.toLowerCase());
startOfPara = false; // Done
}
}
break;
case '>': // End of statement
paraLevel--;
if ( paraLevel != 1 ) { // Exclude closing ParaLine
sb.append((char)c);
significant = true;
}
if ( paraLevel == 0 ) {
// Add final close of ParaLine
int n = sb.lastIndexOf(" # end of ParaLine");
// Do it before the corresponding comment if possible
if ( n > -1 ) {
sb.insert(n, '>');
}
else {
sb.append(" # end of ParaLine"+lineBreak+">");
}
return 0;
}
break;
default:
sb.append((char)c);
break;
}
}
return 0;
}
private void monitorFontEncoding (StringBuilder sb)
throws IOException
{
int c;
int baseLevel = 1;
String encoding = null;
String fontHint = null;
String ftag = null;
boolean inString = false;
MIFToken token = null;
while ( (c = reader.read()) != -1 ) {
sb.append((char)c);
// Handle string content
if ( inString ) {
if ( c == '\'' ) inString = false;
continue;
}
// Otherwise:
switch ( c ) {
case '#':
readComment(true, sb);
break;
case '`':
inString = true;
break;
case '<':
baseLevel++;
String tag = readTag(true, true, sb);
if ( "FTag".equals(tag) ) {
token = getNextTokenInStatement(true, sb, false);
if ( token.isLast() ) baseLevel--;
ftag = token.toString().substring(1, token.toString().length()-1);
}
else if ( "FEncoding".equals(tag) ) {
token = getNextTokenInStatement(true, sb, false);
if ( token.isLast() ) baseLevel--;
encoding = token.toString().substring(1, token.toString().length()-1);
}
else if ( "FPlatformName".equals(tag) ) {
token = getNextTokenInStatement(true, sb, false);
if ( token.isLast() ) baseLevel--;
fontHint = token.toString().substring(1, token.toString().length()-1);
}
// TODO: use Flanguage as well?
// FLanguage
break;
case '>':
baseLevel--;
if ( baseLevel == 0 ) {
if ( !useUTF ) {
Object[] res = mapFontEncoding(ftag, encoding, fontHint);
updateCurrentDecoder((String)res[0], (Boolean)res[1]);
}
return;
}
break;
}
}
// Unexpected end
throw new OkapiIllegalFilterOperationException(
"Unexpected end of input when reading a font");
}
private void resetToDefaultDecoder () {
currentCharsetIndex = 0;
currentDecoder = decoders[0];
// currentEncoder = encoders[0];
doDoubleConversion = doubleConversion[0];
}
private Object[] mapFontEncoding (String ftag,
String encoding,
String hint)
{
Object[] res = new Object[2];
res[1] = false;
if ( encoding == null ) {
if ( Util.isEmpty(ftag) ) {
// No FTag and no encoding: likely a default for the encoding
res[0] = "";
return res;
}
else {
//TODO: get the encoding info from the font of this paragraph style
return res; // For now do nothing
}
}
// Map the MIF encoding name to Java canonical charset name
String mappedEncoding = encodingTable.get(encoding);
if ( mappedEncoding == null ) {
// Warn if the name is not found (and just move on)
logger.warn("Unknown encoding name: '{}'.", encoding);
return res;
}
else {
res[0] = mappedEncoding;
}
// Special case for FrameRoman: it may be anything depending on the font
if ( mappedEncoding.equals(FRAMEROMAN) && !Util.isEmpty(hint) ) {
// Try to guess the real encoding from the platform font name
hint = hint.toLowerCase();
if ( hint.contains("greek") ) {
res[0] = "x-MacGreek";
res[1] = true;
}
else if ( hint.contains("cyrillic") ) {
res[0] = "x-MacCyrillic";
res[1] = true;
}
else if ( hint.contains(" ce ") ) {
res[0] = "x-MacCentralEurope";
res[1] = true;
}
}
return res;
}
/**
* Updates the current decoder if needed.
* @param newEncoding the new encoding to use. This must be a Java encoding.
* Use empty to reset to the default decoder. If the value is null, it is ignored.
*/
private void updateCurrentDecoder (String newEncoding,
boolean newDoubleConversion)
{
if ( newEncoding == null ) return; // Do nothing
if ( newEncoding.isEmpty() ) {
// Reset to default on empty new encoding
resetToDefaultDecoder();
return;
}
// Try to switch if needed only
// Check if the new encoding is the same as the current one
if ( !newEncoding.equals(currentDecoder.charset().name()) ) {
// Test the other one
int n = ((currentCharsetIndex == 0) ? 1 : 0);
if ( newEncoding.equals(decoders[n].charset().name()) ) {
// Use this one
currentCharsetIndex = n;
}
else { // Create a new one (keep the number 0 always the same)
if ( newEncoding.equals(FRAMEROMAN) ) {
decoders[1] = csProvider.charsetForName(newEncoding).newDecoder();
encoders[1] = csProvider.charsetForName(newEncoding).newEncoder();
}
else {
decoders[1] = Charset.forName(newEncoding).newDecoder();
encoders[1] = Charset.forName(newEncoding).newEncoder();
}
doubleConversion[1] = newDoubleConversion;
currentCharsetIndex = 1;
}
// Set the current one
currentDecoder = decoders[currentCharsetIndex];
// currentEncoder = encoders[currentCharsetIndex];
doDoubleConversion = doubleConversion[currentCharsetIndex];
}
// Else: current decoder in fine
}
/**
* Reads until the first occurrence of one of the given statements, or (if stopLevel
* is -1) at the end of the current level, or at the end of the given level.
* @param tagNames the list of tag names to stop at (separated and ending with ';')
* @param store true if we store the parsed characters into the skeleton.
* @param stopLevel -1=return if the end of the current blockLevel is reached.
* @param skipNotesBlock
* other values=return if the blockLevel get lower than that value
* False to stop when it reaches 0.
* @return the name of the tag found, or null if none was found.
* @throws IOException if a low-level error occurs.
*/
private String readUntil (String tagNames,
boolean store,
StringBuilder sb,
int stopLevel,
boolean skipNotesBlock)
throws IOException
{
int endNow = stopLevel;
if ( stopLevel == -1 ) {
endNow = blockLevel;
}
int c;
while ( (c = reader.read()) != -1 ) {
if ( store ) {
if ( sb == null ) skel.append((char)c);
else sb.append((char)c);
}
switch ( c ) {
case '#':
readComment(store, sb);
break;
case '<': // Start of statement
while ( true ) {
blockLevel++;
String tag = readTag(store, true, sb);
if ( tagNames.indexOf(tag+";") > -1 ) {
if ( !skipNotesBlock || ( footnotesLevel == -1) ) {
return tag;
}
break;
}
else if ( "Tbl".equals(tag) ) {
tableGroupLevel = blockLevel;
// Note that the start-group event is send from the startBlock() method
// But the end-group event is send from this method.
break;
}
else if ( "Row".equals(tag) ) {
rowGroupLevel = blockLevel;
if ( secondPass ) {
StartGroup sg = new StartGroup(parentIds.peek());
sg.setId(parentIds.push(String.valueOf(++grpId)));
sg.setType("row");
queue.add(new Event(EventType.START_GROUP, sg));
}
break;
}
else if ( "Cell".equals(tag) ) {
cellGroupLevel = blockLevel;
if ( secondPass ) {
StartGroup sg = new StartGroup(parentIds.peek(), String.valueOf(++grpId));
sg.setType("cell");
queue.add(new Event(EventType.START_GROUP, sg));
}
break;
}
else if ( "Notes".equals(tag) ) {
footnotesLevel = blockLevel;
break;
}
else if ( "FNote".equals(tag) ) {
if ( footnotesLevel > 0 ) {
fnoteGroupLevel = blockLevel;
if ( secondPass ) {
StartGroup sg = new StartGroup(parentIds.peek(), String.valueOf(++grpId));
sg.setType("fn");
queue.add(new Event(EventType.START_GROUP, sg));
}
}
break;
}
else if ( IMPORTOBJECT.equals(tag) ) {
skipOverImportObject(store, sb);
blockLevel--;
break;
}
else { // Default: skip over
if ( !readUntilOpenOrClose(store, sb) ) {
blockLevel--;
break;
}
// Else: re-process the next tag
}
// Else: re-process the next tag
}
break;
case '>': // End of statement
if ( tableGroupLevel == blockLevel ) {
tableGroupLevel = -1;
if ( secondPass ) {
queue.add(new Event(EventType.END_GROUP, new Ending(String.valueOf(++grpId))));
parentIds.pop();
}
}
else if ( rowGroupLevel == blockLevel ) {
rowGroupLevel = -1;
if ( secondPass ) {
queue.add(new Event(EventType.END_GROUP, new Ending(String.valueOf(++grpId))));
parentIds.pop();
}
}
else if ( cellGroupLevel == blockLevel ) {
cellGroupLevel = -1;
if ( secondPass ) {
queue.add(new Event(EventType.END_GROUP, new Ending(String.valueOf(++grpId))));
}
}
else if ( footnotesLevel == blockLevel ) {
footnotesLevel = -1;
}
else if ( fnoteGroupLevel == blockLevel ) {
if ( footnotesLevel > 0 ) {
fnoteGroupLevel = -1;
if ( secondPass ) {
queue.add(new Event(EventType.END_GROUP, new Ending(String.valueOf(++grpId))));
}
}
}
blockLevel--;
if ( blockLevel < endNow ) {
return null;
}
break;
}
}
//TODO: we shouldn't exit this way, except when starting at 0
return null;
}
private void skipOverImportObject (boolean store,
StringBuilder buffer)
throws IOException
{
// At the point only the tag has been read
// We should leave after the corresponding '>' is found
// The content may have one or more inset data (start with line-break and '&' per line)
int state = 0;
int c;
int baseLevel = 1;
while ( (c = reader.read()) != -1 ) {
// Store if needed
if ( store ) {
if ( buffer != null ) buffer.append((char)c);
else skel.append((char)c);
}
// Parse according current state
switch ( state ) {
case 0: // In facet mode wait for line-break
switch ( c ) {
case '`':
state = 1; // In string
continue;
case '<':
baseLevel++;
continue;
case '>':
baseLevel--;
if ( baseLevel == 0 ) {
// We are done
return;
}
case '\r':
case '\n':
state = 3;
continue;
}
// Else: stay in this current state
continue;
case 1: // In string
if ( c == '\'' ) {
state = 0; // Back to normal
}
continue;
case 2: // In escape
state = 0; // Back to normal
continue;
case 3: // After \r or \r: wait for & or =
switch ( c ) {
case '&':
state = 4; // In facet line
continue;
case '<':
state = 0;
baseLevel++;
continue;
case '>':
state = 0;
baseLevel--;
if ( baseLevel == 0 ) {
return; // Done
}
continue;
case '\n':
case '\r':
// Stay in this current state
continue;
default:
// Back to within an ImportObject (after a line-break)
state = 0;
continue;
}
case 4: // Inside a facet line, waiting for end-of-line
if (( c == '\r' ) || ( c == '\n' )) {
state = 3; // Back to after a line-break state
}
continue;
}
}
// Unexpected end
throw new OkapiIllegalFilterOperationException(
String.format("Unexpected end of input at state = %d", state));
}
/**
* Reads until the next opening or closing statement.
* @param store
* @return true if stops on opening, false if stops on closing.
* @throws IOException if the end of file occurs.
*/
private boolean readUntilOpenOrClose (boolean store,
StringBuilder sb)
throws IOException
{
int c;
boolean inEscape = false;
boolean inString = false;
while ( (c = reader.read()) != -1 ) {
if ( store ) {
if ( sb == null ) skel.append((char)c);
else sb.append((char)c);
}
// Parse a string content
if ( inString ) {
if ( c == '\'' ) inString = false;
continue;
}
// Else: we are outside a string
if ( inEscape ) {
inEscape = false;
}
else {
switch ( c ) {
case '`':
inString = true;
break;
case '\\':
inEscape = true;
break;
case '<':
return true;
case '>':
return false;
}
}
}
// Unexpected end
throw new OkapiIllegalFilterOperationException("Unexpected end of input.");
}
/**
* Reads a tag name.
* @param store true to store the tag codes
* @param storeCharStatement true to store if it's a Char statement.
* @param sb Not null to store there, null to store in the skeleton.
* @return The name of the tag.
* @throws IOException
*/
private String readTag (boolean store,
boolean storeCharStatement,
StringBuilder sb)
throws IOException
{
tagBuffer.setLength(0);
int c;
int wsStart = ((sb != null ) ? sb.length()-1 : -1);
boolean leadingWSDone = false;
// Skip and whitespace between '<' and the name
do {
switch ( c = reader.read() ) {
case ' ':
case '\t':
case '\r':
case '\n':
if ( store ) {
if ( sb != null ) sb.append((char)c);
else skel.add((char)c);
}
break;
case -1:
default:
leadingWSDone = true;
break;
}
}
while ( !leadingWSDone );
// Now read the name
while ( true ) {
switch ( c ) {
case ' ':
case '\t':
case '\r':
case '\n':
if ( store ) {
if ( !storeCharStatement && tagBuffer.toString().equals("Char") ) {
// Special case for <Char...>: we don't store it
if ( wsStart > 0 ) {
sb.delete(wsStart, sb.length());
}
}
else {
if ( sb != null ) {
sb.append(tagBuffer.toString());
sb.append((char)c);
}
else {
skel.append(tagBuffer.toString());
skel.append((char)c);
}
}
}
return tagBuffer.toString();
case -1:
throw new OkapiIllegalFilterOperationException("Unexpected end of input.");
default:
tagBuffer.append((char)c);
break;
}
c = reader.read();
}
}
private void processVariables ()
throws IOException
{
// We are inside VariableFormats
// blockLevel should be 1
boolean startGroupDone = false;
String tag = null;
ITextUnit tu = null;
do {
tag = readUntil("VariableFormat;", true, null, blockLevel-1, true);
if ( tag != null ) {
tag = readUntil("VariableDef;", true, null, blockLevel-1, true);
if ( tag != null ) {
String text = processString(false, null);
TextFragment tf = new TextFragment(text);
checkInlineCodes(tf);
skel.append("`");
// If we have only white spaces and/or codes
if ( tf.hasText() ) {
if ( !startGroupDone ) {
// Send the start group if needed
StartGroup sg = new StartGroup(parentIds.peek());
sg.setId(String.valueOf(++grpId));
sg.setType("variables");
queue.add(new Event(EventType.START_GROUP, sg));
startGroupDone = true;
}
// Add the text unit to the queue
tu = new TextUnit(String.valueOf(++tuId));
tu.setPreserveWhitespaces(true);
tu.setSourceContent(tf);
tu.setName(resname); resname = null;
tu.setMimeType(MIFSTRING_MIME_TYPE);
processILC(tu);
queue.add(new Event(EventType.TEXT_UNIT, tu, skel));
skel.addContentPlaceholder(tu);
}
else { // Put back the text in the skeleton
skel.append(toMIFString(tf));
}
skel.append("'>");
if ( tu != null ) {
// New skeleton object for the next parts of the parent statement
skel = new GenericSkeleton();
tu = null; // Reset for next entry
}
}
}
}
while ( tag != null );
if ( startGroupDone ) {
// Send the end-group if needed
queue.add(new Event(EventType.END_GROUP, new Ending(String.valueOf(++grpId))));
}
}
private String toMIFString (TextFragment tf) {
String ctext = tf.getCodedText();
StringBuilder tmp = new StringBuilder();
for ( int i=0; i<ctext.length(); i++ ) {
char ch = ctext.charAt(i);
if ( TextFragment.isMarker(ch) ) {
tmp.append(tf.getCode(ctext.charAt(++i)));
}
else {
tmp.append(encoder.encode(ch, EncoderContext.SKELETON));
}
}
return tmp.toString();
}
private void checkInlineCodes (TextFragment tf) {
if ( params.getUseCodeFinder() ) {
params.getCodeFinder().process(tf);
}
// Escape inline code content
List<Code> codes = tf.getCodes();
for ( Code code : codes ) {
// Escape the data of the new inline code (and only them)
if ( code.getType().equals(InlineCodeFinder.TAGTYPE) ) {
code.setData(encoder.encode(code.getData(), EncoderContext.SKELETON));
}
}
}
private String processString (boolean store,
StringBuilder sb)
throws IOException
{
strBuffer.setLength(0);
int c;
int state = 0;
boolean byteMode = false;
while ( (c = reader.read()) != -1 ) {
if ( store ) {
if ( sb == null ) skel.append((char)c);
else sb.append((char)c);
}
switch ( state ) {
case 0: // Outside the string
switch ( c ) {
case '`':
state = 1; // In string
continue;
case '>':
if ( byteMode ) {
try {
if ( doDoubleConversion ) {
CharBuffer buf1 = firstDecoder.decode(ByteBuffer.wrap(byteStream.toByteArray()));
byteStream.reset();
for ( char ch : buf1.array() ) {
byteStream.write((int)ch);
}
CharBuffer buf2 = currentDecoder.decode(ByteBuffer.wrap(byteStream.toByteArray()));
strBuffer.append(buf2.toString());
}
else {
CharBuffer buf = currentDecoder.decode(ByteBuffer.wrap(byteStream.toByteArray()));
strBuffer.append(buf.toString());
}
}
catch ( CharacterCodingException e ) {
if ( ++decodingErrors < 25 ) {
// Warning message, but only up to a point
logger.warn("Error with decoding character with encoding '{}'.",
currentDecoder.charset().name());
}
}
}
return strBuffer.toString();
}
continue;
case 1: // In string
switch ( c ) {
case '\'': // End of string
state = 0;
continue;
case '\\':
state = 2; // In escape mode
continue;
default:
if ( byteMode ) {
if ( c > 127 ) {
// Extended characters are normally all escaped in a byte string
logger.warn(String.format("A raw extended character (0x%04X) was found in a byte string.\n"
+ "This may be a problem.", c));
}
byteStream.write(c);
}
else strBuffer.append((char)c);
continue;
}
case 2: // In escape mode (after a backslash)
state = 1; // Reset to in-string state
switch ( c ) {
case '\\':
case '>':
if ( byteMode ) byteStream.write(c);
else strBuffer.append((char)c);
continue;
case 't':
if ( byteMode ) byteStream.write(c);
else strBuffer.append('\t');
continue;
case 'Q':
if ( byteMode ) byteStream.write(c);
else strBuffer.append('`');
continue;
case 'q':
if ( byteMode ) byteStream.write(c);
else strBuffer.append('\'');
continue;
case 'u':
c = readHexa(4, false, store, sb);
if ( c == Integer.MAX_VALUE ) {
continue; // warning already logged
}
if ( byteMode ) {
// We should not see this in byte mode
logger.warn("A Uniocde escape sequence was found in a byte string.\n"
+ "Mixed notations are not supported, this character will be skipped.");
}
else {
strBuffer.append((char)c);
}
continue;
case 'x':
c = readHexa(2, true, store, sb);
if ( c == Integer.MAX_VALUE ) {
continue; // warning already logged
}
String res = MIFStringEncoder.convertCtrl(c);
if ( res != null ) {
strBuffer.append(res);
continue;
}
// Else: no mapped string
if ( dbVersion < 8.0 ) { // Byte string
if ( !byteMode ) {
byteStream.reset();
byteMode = true;
}
byteStream.write((char)c);
}
else { // 8 and above: byte escape in unicode string.
logger.warn("Unknow control character found in string.\n"
+ "This character will be extracted as an inline code.");
strBuffer.append(String.format("%c\\x%02%c", ILC_START, c, ILC_END));
}
continue;
}
}
}
// Else: Missing end of string error
throw new OkapiIllegalFilterOperationException("End of string is missing.");
}
private int readHexa (int length,
boolean readExtraSpace,
boolean store,
StringBuilder sb)
throws IOException
{
tagBuffer.setLength(0);
int c;
// Fill the buffer
for ( int i=0; i<length; i++ ) {
c = reader.read();
if ( c == -1 ) {
throw new OkapiIllegalFilterOperationException("Unexpected end of file.");
}
if ( store ) {
if ( sb == null ) skel.append((char)c);
else sb.append((char)c);
}
tagBuffer.append((char)c);
}
if ( readExtraSpace ) {
c = reader.read();
if ( store ) {
if ( sb == null ) skel.append((char)c);
else sb.append((char)c);
}
}
// Try to convert
try {
int n = Integer.valueOf(tagBuffer.toString(), 16);
return n;
}
catch ( NumberFormatException e ) {
// Log warning
logger.warn("Invalid escape sequence found: '{}'", tagBuffer.toString());
}
// Error
return Integer.MAX_VALUE;
}
// Older versions: <MIFFile NN.00>
// Newer versions: <MIFFile 2015>
private static Pattern MIFFILE_PATTERN = Pattern.compile("^<MIFFile (\\d+(\\.00)?)\\D");
private InputStream guessEncoding (InputStream input)
throws IOException
{
BOMAwareInputStream bomDetector = new BOMAwareInputStream(input, "UTF-8");
baseEncoding = bomDetector.detectEncoding();
PushbackInputStream stream = new PushbackInputStream(bomDetector, 28);
byte buffer[] = new byte[28];
int n = stream.read(buffer, 0, 28);
String tmp = new String(buffer, baseEncoding);
Matcher m = MIFFILE_PATTERN.matcher(tmp);
if (!m.lookingAt()) {
throw new OkapiIOException("Invalid MIF header: '" + tmp + "'");
}
String version = m.group(1);
dbVersion = Double.valueOf(version);
if ( dbVersion < 8.00 ) {
baseEncoding = FRAMEROMAN;
}
useUTF = baseEncoding.startsWith("UTF-");
logger.debug("MIF version " + dbVersion + ", encoding=" + baseEncoding);
stream.unread(buffer, 0, n);
return stream;
}
// private Object[] guessEncoding (InputStream input)
// throws IOException
// {
// Object[] res = new Object[2];
// String defEncoding = "UTF-8"; // Use v8/v9 default by default
// if ( !Util.isEmpty(version) ) {
// // If we have a version, it means we are in the second pass and need to get the correct encoding
// if ( version.compareTo("8.00") < 0 ) {
// // Before 8.00 the default was not UTF-8
// defEncoding = FRAMEROMAN;
// }
// }
//
// // Detect any BOM-type encoded (and set the stream to skip over it)
// BOMAwareInputStream bais = new BOMAwareInputStream(input, defEncoding);
// res[0] = bais;
// res[1] = bais.detectEncoding();
// useUTF = (((String)res[1]).startsWith("UTF-"));
// if ( bais.autoDtected() ) {
// return res;
// }
//
// return res;
// }
/**
* Look a the source content of a text unit to see if any part of the text
* is bracketed by ILC_START/ILC_END and needs conversion to inline codes.
* @param tu the text unit to update.
*/
private void processILC (ITextUnit tu) {
TextFragment tf = tu.getSource().getFirstContent();
String ct = tf.getCodedText();
int start = 0;
int diff = 0; // No code found
// Convert each ILC span into inlinbe code
while ( true ) {
start = ct.indexOf(ILC_START, start);
if ( start == -1 ) break; // No more markers
int end = ct.indexOf(ILC_END, start);
if ( end == -1 ) {
throw new OkapiIllegalFilterOperationException("Expected ILC_END marker not found.");
}
diff = tf.changeToCode(start, end+1, TagType.PLACEHOLDER, "ctrl");
start = end+diff;
ct = tf.getCodedText();
}
// Remove the markers if needed
if ( diff != 0 ) { // This means we have at least one code
for ( Code code : tf.getCodes() ) {
if ( code.getData().startsWith(ILC_START) ) {
String data = code.getData();
// Trim both start and end markers
code.setData(data.substring(1, data.length()-1));
}
}
}
}
}
|
92364f704abddd4561a6b77b87ab750b584b0ea1 | 4,982 | java | Java | src/main/java/com/hosta/Floricraft2/module/ModuleFragrances.java | HostaPlantain/Floricraft2 | 91287e439975f57a5b7f08828ebde05799b256f5 | [
"MIT"
] | 3 | 2018-11-18T03:10:46.000Z | 2020-01-30T17:08:45.000Z | src/main/java/com/hosta/Floricraft2/module/ModuleFragrances.java | HostaPlantain/Floricraft2 | 91287e439975f57a5b7f08828ebde05799b256f5 | [
"MIT"
] | null | null | null | src/main/java/com/hosta/Floricraft2/module/ModuleFragrances.java | HostaPlantain/Floricraft2 | 91287e439975f57a5b7f08828ebde05799b256f5 | [
"MIT"
] | null | null | null | 41.173554 | 205 | 0.745684 | 997,625 | package com.hosta.Floricraft2.module;
import com.hosta.Floricraft2.Floricraft2;
import com.hosta.Floricraft2.item.ItemBase;
import com.hosta.Floricraft2.item.fragrance.ItemSachet;
import com.hosta.Floricraft2.item.fragrance.ItemVial;
import com.hosta.Floricraft2.item.fragrance.ItemVialEssence;
import com.hosta.Floricraft2.potion.EffectActive;
import com.hosta.Floricraft2.potion.EffectAntiMob;
import com.hosta.Floricraft2.util.Helper;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.oredict.OreDictionary;
public class ModuleFragrances implements IModule, IModuleRecipe {
// Potion
public static final Potion POTION_FLORIC = new EffectActive("effect.floric", ModuleOthers.COLOR_FLORIC, false).setIconIndex(0, 0);
public static final Potion POTION_HILLSTEP = new EffectActive("effect.hillstep", 0xEEFFDA, false).setIconIndex(0, 0);
public static final EffectAntiMob[] POTION_ANTIS = new EffectAntiMob[Floricraft2.CONFIG.getAddedAntiPotions().length];
static
{
int i = 0;
for (String anti : Floricraft2.CONFIG.getAddedAntiPotions())
{
POTION_ANTIS[i++] = getAntiEffect(anti);
}
}
private static EffectAntiMob getAntiEffect(String anti)
{
String[] config = anti.split(";");
Class[] antiClass = new Class[config.length - 3];
for (int j = 0; j < antiClass.length; j++)
{
try
{
antiClass[j] = Class.forName(config[3 + j]);
}
catch (ClassNotFoundException e) { }
}
return (EffectAntiMob)new EffectAntiMob("effect.anti_" + config[0], Integer.parseInt(config[1]), antiClass, config[2]).setIconIndex(0, 0);
}
public static final Potion POTION_NO_TARGET = new EffectActive("effect.no_target", ModuleOthers.COLOR_FLORIC, true).setIconIndex(0, 0);
// Vial
public static final Item VIAL_EMPTY = new ItemVial("vial_empty");
public static final Item VIAL_WATER = new ItemBase("vial_water").setMaxStackSize(1);
public static final Item VIAL_FLOWER = new ItemVialEssence("vial_flower").setMaxStackSize(1);
public static final Item VIAL_MOON = new ItemBase("vial_moon");
public static final Item VIAL_POTION = new ItemVialEssence("vial_potion").setMaxStackSize(1);
public static final Item VIAL_MIX = new ItemVialEssence("vial_mix").setMaxStackSize(1);
// Sachet
public static final Item SACHET_SAC = new ItemBase("sachet_sac");
public static final Item SACHET_FLOWER = new ItemSachet("sachet_flower");
// public static final Item SACHET_ENDEARING;
// Potpourri
// public static final Block POTPOURRI;
@Override
public void registerItems()
{
register(VIAL_EMPTY, VIAL_WATER, VIAL_FLOWER, VIAL_MOON, VIAL_POTION, VIAL_MIX, SACHET_SAC, SACHET_FLOWER);
}
@Override
public void registerOreDictionary()
{
OreDictionary.registerOre("vialBase", VIAL_FLOWER);
OreDictionary.registerOre("vialBase", VIAL_POTION);
OreDictionary.registerOre("vialEffective", VIAL_FLOWER);
OreDictionary.registerOre("vialEffective", VIAL_POTION);
OreDictionary.registerOre("vialEffective", VIAL_MIX);
}
@Override
public void registerPotions()
{
register(POTION_FLORIC, POTION_HILLSTEP);
register(POTION_ANTIS);
register(POTION_NO_TARGET);
}
@Override
public void registerRecipes()
{
register
(
shapedRecipe(null, SACHET_SAC, "tpt", "cpc", " c ", 'p', "petalsDry", 't', ModuleCrops.HEMP_TWINE, 'c', ModuleCrops.HEMP_CLOTH),
shapedRecipe(null, Helper.setEffect(new ItemStack(SACHET_FLOWER, 1, 0), new PotionEffect(POTION_FLORIC)), "ccc", "ccc", "tst", 'c', "petalsDry", 't', ModuleCrops.HEMP_TWINE, 's', SACHET_SAC),
shapedRecipe(null, new ItemStack(VIAL_EMPTY, 3), "b b", " b ", 'b', new ItemStack(Blocks.STAINED_GLASS_PANE, 1, EnumDyeColor.BROWN.getMetadata()))
);
register
(
effectRecipe(null, SACHET_FLOWER, "b", "a", 'a', SACHET_SAC, 'b', "vialEffective"),
effectRecipe(null, SACHET_FLOWER, "b", "a", 'a', SACHET_SAC, 'b', VIAL_MOON),
effectRecipe(null, VIAL_POTION, "b", "a", 'a', VIAL_MOON, 'b', Items.POTIONITEM),
effectRecipe(null, VIAL_MIX, "b", "a", 'a', VIAL_MOON, 'b', "vialBase"),
effectRecipe(null, VIAL_MIX, "b", "a", 'a', VIAL_MIX, 'b', "vialEffective")
);
ItemStack vialFlower = Helper.setEffect(new ItemStack(VIAL_FLOWER), new PotionEffect(POTION_FLORIC, 400, 0));
register(brewingRecipe(new ItemStack(VIAL_WATER), new ItemStack(ModuleFlowers.PETALS_RAW, 1, OreDictionary.WILDCARD_VALUE), vialFlower));
for (EffectAntiMob anti : POTION_ANTIS)
{
register(brewingRecipe(vialFlower, anti.getItemToCraft(), Helper.setEffect(new ItemStack(VIAL_FLOWER), new PotionEffect(anti, 400, 0))));
register(shapedRecipe(null, Helper.setEffect(new ItemStack(SACHET_FLOWER, 1, 0), new PotionEffect(anti)), "ccc", "ccc", "tst", 'c', anti.getItemToCraft(), 's', SACHET_SAC, 't', ModuleCrops.HEMP_TWINE));
}
}
}
|
9236502f47f3b2734356c10f159973dd1c5c0779 | 2,589 | java | Java | vcx/mobicents-sip/src/vidconference/java/com/openvcx/conference/PortManager.java | openvcx/openvcx | cf6e6ba25b5d879943e993e415507650c7e30bc1 | [
"Apache-2.0"
] | 63 | 2015-06-25T00:53:12.000Z | 2021-11-14T19:44:40.000Z | vcx/mobicents-sip/src/vidconference/java/com/openvcx/conference/PortManager.java | ahmadmysra/openvcx | cf6e6ba25b5d879943e993e415507650c7e30bc1 | [
"Apache-2.0"
] | 3 | 2018-07-29T05:21:01.000Z | 2019-10-25T06:37:01.000Z | vcx/mobicents-sip/src/vidconference/java/com/openvcx/conference/PortManager.java | ahmadmysra/openvcx | cf6e6ba25b5d879943e993e415507650c7e30bc1 | [
"Apache-2.0"
] | 41 | 2015-09-02T12:15:43.000Z | 2022-03-17T05:21:28.000Z | 32.3625 | 196 | 0.658942 | 997,626 | /**
* Copyright 2014 OpenVCX nnheo@example.com
*
* You may not use this file except in compliance with the OpenVCX License.
* The OpenVCX License is based on the Apache Version 2.0 License with
* additional credit attribution clauses mentioned in section 4 (e) and
* 4 (f).
*
* 4 (e) Redistributions in source or binary form must reproduce the
* aforementioned copyright notice, list of conditions and any
* disclaimers in the documentation and/or other materials provided
* with the distribution.
*
* (f) All advertising materials mentioning features or use of this
* software must display the following acknowledgement:
* "This product includes software from OpenVCX".
*
* You may obtain a copy of the Apache License, Version 2.0 at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.openvcx.conference;
import java.io.IOException;
/**
*
* TCP/UDP port allocation manager
*
*/
public class PortManager {
private int m_start;
private int m_end;
private int m_last;
private int m_mod;
/**
* Constructor used to initialize this instance
* @param start The starting port number for the managed range
* @param end The ending port number for the managed port range
* @param mod A modulus value for each call to <i>allocatePort</i>. A value of 2 will cause each call to the <i>allocatePort</i> method to return a port greater than 2 from the previous call.
* @throws IOException When the port range arguments are invalid
*/
public PortManager(int start, int end, int mod) throws IOException {
if((m_mod = mod) <= 0) {
m_mod = 1;
}
m_start = start / m_mod * m_mod;
m_end = end;
m_last = start;
if(m_end - m_start <= 0) {
throw new IOException("Illegal port range " + m_start + " - " + m_end);
}
}
/**
* Allocates a port from the port configured port range
* @return A port allocated from the configured port range
*/
public synchronized int allocatePort() {
int port = m_last;
m_last += m_mod;
if(m_last > m_end) {
m_last = m_start;
}
return port;
}
}
|
923650c85781cf48ac4c4e6699c8ec3c52b9099e | 2,121 | java | Java | battleships_core/src/main/java/org/hupisoft/battleships_core/IShip.java | PerttuP/battleships_android | 1bb839236c352e4ff2027f5934f4e5e8cb829d4e | [
"MIT"
] | null | null | null | battleships_core/src/main/java/org/hupisoft/battleships_core/IShip.java | PerttuP/battleships_android | 1bb839236c352e4ff2027f5934f4e5e8cb829d4e | [
"MIT"
] | null | null | null | battleships_core/src/main/java/org/hupisoft/battleships_core/IShip.java | PerttuP/battleships_android | 1bb839236c352e4ff2027f5934f4e5e8cb829d4e | [
"MIT"
] | null | null | null | 23.054348 | 87 | 0.609618 | 997,627 | package org.hupisoft.battleships_core;
import java.util.List;
/**
* Interface for ships.
*/
public interface IShip {
/**
* Ship orientation enumeration.
*/
public enum Orientation
{
/**
* Ship is placed vertically.
*/
VERTICAL,
/**
* Ship is placed horisontally.
*/
HORIZONTAL
}
/**
* Check if ship has been destroyed.
* @return True, if ship has been destroyed.
*/
public boolean isDestroyed();
/**
* Get ship orientation.
* @return Ship orientation.
*/
public Orientation orientation();
/**
* Set new orientation.
* @param orientation New ship orientation.
*/
public void setOrientation(Orientation orientation);
/**
* Get ship length.
* @return Ship length in squares.
*/
public int length();
/**
* Get coordinates of the bow of the ship.
* @return Coordinate pair for the head of the ship.
*/
public Coordinate getBowCoordinates();
/**
* Set new bow location. Occupied and restricted locations are updated accorcingly.
* @param coordinate New location.
*/
public void setBowCoordinates(Coordinate coordinate);
/**
* Get coordinates of the rear of the ship.
* @return Coordinate pair for the rear of the ship.
*/
public Coordinate getRearCoordinates();
/**
* Get list of coordinates occupied by the ship in order from bow to rear.
* @return List of coordinates.
*/
public List<Coordinate> getOccupiedCoordinates();
/**
* Get list of coordinates that are forbidden from other ships.
* List contains all occupied coordinates and their neighbours.
* Coordinates are not in any specific order.
* @return List of restricted coordinates.
*/
public List<Coordinate> getRestrictedCoordinates();
/**
* Get ship hit count.
* @return Number of hits that ship has received.
*/
public int hitCount();
/**
* Increase ship's hit counter.
*/
public boolean hit();
}
|
923650f43059ea24f92ccd1acd45be81915fbf44 | 2,830 | java | Java | 03-NumberGuessGame/app/src/main/java/com/jjh/android/games/MainActivity.java | johnehunt/AndroidIntroLabs | 337282084b1ff69d9e5f6f5d0eb871ff085a0703 | [
"Apache-2.0"
] | 1 | 2020-07-18T11:09:47.000Z | 2020-07-18T11:09:47.000Z | 03-NumberGuessGame/app/src/main/java/com/jjh/android/games/MainActivity.java | johnehunt/AndroidIntroLabs | 337282084b1ff69d9e5f6f5d0eb871ff085a0703 | [
"Apache-2.0"
] | null | null | null | 03-NumberGuessGame/app/src/main/java/com/jjh/android/games/MainActivity.java | johnehunt/AndroidIntroLabs | 337282084b1ff69d9e5f6f5d0eb871ff085a0703 | [
"Apache-2.0"
] | null | null | null | 31.797753 | 111 | 0.662898 | 997,628 | package com.jjh.android.games;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private static final int MAX_NUMBER = 10;
private static final String CORRECT_MSG = "You guessed correctly! The number was ";
private static final String INVALID_MSG = "Invalid input (input must be between 1 and " + MAX_NUMBER + ")";
private static final String HIGHER_MSG = "The correct answer is higher";
private static final String LOWER_MSG = "The correct answer is lower";
private EditText userGuessTextField;
private int numberToGuess;
public MainActivity() {
numberToGuess = generateRandomNumber();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userGuessTextField = findViewById(R.id.guessEditText);
userGuessTextField.setText("");
TextView title = findViewById(R.id.title);
title.setText(title.getText().toString() + MAX_NUMBER);
}
// Handle button click
public void onGuessButtonClick(View view) {
String userInput = userGuessTextField.getText().toString();
validateAndCheckGuess(userInput);
}
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(MAX_NUMBER - 1) + 1;
}
private void validateAndCheckGuess(String userInput) {
try {
int guessInput = Integer.parseInt(userInput);
if (guessInput < 1 || guessInput > MAX_NUMBER) {
displayInvalidUserInputToast();
} else {
checkForCorrectGuess(guessInput);
}
} catch (NumberFormatException e) {
displayInvalidUserInputToast();
}
}
private void checkForCorrectGuess(int guessInput) {
if (guessInput == numberToGuess) {
displayCorrectAnswerToast();
userGuessTextField.setText("");
numberToGuess = generateRandomNumber();
} else {
displayHintToast(guessInput > numberToGuess);
}
}
private void displayCorrectAnswerToast() {
Toast.makeText(this, CORRECT_MSG + numberToGuess, Toast.LENGTH_LONG).show();
}
private void displayInvalidUserInputToast() {
Toast.makeText(this, INVALID_MSG, Toast.LENGTH_SHORT).show();
}
private void displayHintToast(Boolean higher) {
String message = HIGHER_MSG;
if (higher) {
message = LOWER_MSG;
}
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
|
923650fbeac3f051350feec3bf7171715e703d2b | 21,454 | java | Java | server/src/main/java/org/opensearch/search/aggregations/InternalOrder.java | korpx-z/OpenSearch | dd9622fec64805141848537c0cf5265e8650ffb9 | [
"Apache-2.0"
] | 4,822 | 2021-04-12T15:03:57.000Z | 2022-03-31T23:37:49.000Z | server/src/main/java/org/opensearch/search/aggregations/InternalOrder.java | korpx-z/OpenSearch | dd9622fec64805141848537c0cf5265e8650ffb9 | [
"Apache-2.0"
] | 2,146 | 2021-04-12T14:10:48.000Z | 2022-03-31T23:58:34.000Z | server/src/main/java/org/opensearch/search/aggregations/InternalOrder.java | korpx-z/OpenSearch | dd9622fec64805141848537c0cf5265e8650ffb9 | [
"Apache-2.0"
] | 593 | 2021-04-12T16:26:05.000Z | 2022-03-31T11:33:45.000Z | 39.007273 | 136 | 0.596206 | 997,629 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.search.aggregations;
import org.opensearch.common.ParsingException;
import org.opensearch.common.io.stream.StreamInput;
import org.opensearch.common.io.stream.StreamOutput;
import org.opensearch.common.logging.DeprecationLogger;
import org.opensearch.common.util.Comparators;
import org.opensearch.common.xcontent.XContent;
import org.opensearch.common.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentParser;
import org.opensearch.search.aggregations.Aggregator.BucketComparator;
import org.opensearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket;
import org.opensearch.search.aggregations.support.AggregationPath;
import org.opensearch.search.sort.SortOrder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.function.ToLongFunction;
import static java.util.stream.Collectors.toList;
/**
* Implementations for {@link Bucket} ordering strategies.
*/
public abstract class InternalOrder extends BucketOrder {
// TODO merge the contents of this file into BucketOrder. The way it is now is relic.
/**
* {@link Bucket} ordering strategy to sort by a sub-aggregation.
*/
public static class Aggregation extends InternalOrder {
static final byte ID = 0;
private final SortOrder order;
private final AggregationPath path;
/**
* Create a new ordering strategy to sort by a sub-aggregation.
*
* @param path path to the sub-aggregation to sort on.
* @param asc direction to sort by: {@code true} for ascending, {@code false} for descending.
* @see AggregationPath
*/
Aggregation(String path, boolean asc) {
order = asc ? SortOrder.ASC : SortOrder.DESC;
this.path = AggregationPath.parse(path);
}
public AggregationPath path() {
return path;
}
@Override
public <T extends Bucket> Comparator<T> partiallyBuiltBucketComparator(ToLongFunction<T> ordinalReader, Aggregator aggregator) {
try {
BucketComparator bucketComparator = path.bucketComparator(aggregator, order);
return (lhs, rhs) -> bucketComparator.compare(ordinalReader.applyAsLong(lhs), ordinalReader.applyAsLong(rhs));
} catch (IllegalArgumentException e) {
throw new AggregationExecutionException("Invalid aggregation order path [" + path + "]. " + e.getMessage(), e);
}
}
@Override
public Comparator<Bucket> comparator() {
return (lhs, rhs) -> {
double l = path.resolveValue(((InternalAggregations) lhs.getAggregations()));
double r = path.resolveValue(((InternalAggregations) rhs.getAggregations()));
return Comparators.compareDiscardNaN(l, r, order == SortOrder.ASC);
};
}
@Override
byte id() {
return ID;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.startObject().field(path.toString(), order.toString()).endObject();
}
@Override
public int hashCode() {
return Objects.hash(path, order);
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Aggregation other = (Aggregation) obj;
return Objects.equals(path, other.path) && Objects.equals(order, other.order);
}
}
/**
* {@link Bucket} ordering strategy to sort by multiple criteria.
*/
public static class CompoundOrder extends BucketOrder {
static final byte ID = -1;
final List<BucketOrder> orderElements;
/**
* Create a new ordering strategy to sort by multiple criteria. A tie-breaker may be added to avoid
* non-deterministic ordering.
*
* @param compoundOrder a list of {@link BucketOrder}s to sort on, in order of priority.
*/
CompoundOrder(List<BucketOrder> compoundOrder) {
this(compoundOrder, true);
}
/**
* Create a new ordering strategy to sort by multiple criteria.
*
* @param compoundOrder a list of {@link BucketOrder}s to sort on, in order of priority.
* @param absoluteOrdering {@code true} to add a tie-breaker to avoid non-deterministic ordering if needed,
* {@code false} otherwise.
*/
CompoundOrder(List<BucketOrder> compoundOrder, boolean absoluteOrdering) {
this.orderElements = new LinkedList<>(compoundOrder);
BucketOrder lastElement = null;
for (BucketOrder order : orderElements) {
if (order instanceof CompoundOrder) {
throw new IllegalArgumentException("nested compound order not supported");
}
lastElement = order;
}
if (absoluteOrdering && isKeyOrder(lastElement) == false) {
// add key order ascending as a tie-breaker to avoid non-deterministic ordering
// if all user provided comparators return 0.
this.orderElements.add(KEY_ASC);
}
}
@Override
byte id() {
return ID;
}
/**
* @return unmodifiable list of {@link BucketOrder}s to sort on.
*/
public List<BucketOrder> orderElements() {
return Collections.unmodifiableList(orderElements);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startArray();
for (BucketOrder order : orderElements) {
order.toXContent(builder, params);
}
return builder.endArray();
}
@Override
public <T extends Bucket> Comparator<T> partiallyBuiltBucketComparator(ToLongFunction<T> ordinalReader, Aggregator aggregator) {
List<Comparator<T>> comparators = orderElements.stream()
.map(oe -> oe.partiallyBuiltBucketComparator(ordinalReader, aggregator))
.collect(toList());
return (lhs, rhs) -> {
Iterator<Comparator<T>> itr = comparators.iterator();
int result;
do {
result = itr.next().compare(lhs, rhs);
} while (result == 0 && itr.hasNext());
return result;
};
}
@Override
public Comparator<Bucket> comparator() {
List<Comparator<Bucket>> comparators = orderElements.stream().map(BucketOrder::comparator).collect(toList());
return (lhs, rhs) -> {
Iterator<Comparator<Bucket>> itr = comparators.iterator();
int result;
do {
result = itr.next().compare(lhs, rhs);
} while (result == 0 && itr.hasNext());
return result;
};
}
@Override
public int hashCode() {
return Objects.hash(orderElements);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CompoundOrder other = (CompoundOrder) obj;
return Objects.equals(orderElements, other.orderElements);
}
}
/**
* {@link BucketOrder} implementation for simple, fixed orders like
* {@link InternalOrder#COUNT_ASC}. Complex implementations should not
* use this.
*/
private static class SimpleOrder extends InternalOrder {
private final byte id;
private final String key;
private final SortOrder order;
private final Comparator<Bucket> comparator;
SimpleOrder(byte id, String key, SortOrder order, Comparator<Bucket> comparator) {
this.id = id;
this.key = key;
this.order = order;
this.comparator = comparator;
}
@Override
public Comparator<Bucket> comparator() {
return comparator;
}
@Override
byte id() {
return id;
}
@Override
public <T extends Bucket> Comparator<T> partiallyBuiltBucketComparator(ToLongFunction<T> ordinalReader, Aggregator aggregator) {
Comparator<Bucket> comparator = comparator();
return (lhs, rhs) -> comparator.compare(lhs, rhs);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.startObject().field(key, order.toString()).endObject();
}
@Override
public int hashCode() {
return Objects.hash(id, key, order);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SimpleOrder other = (SimpleOrder) obj;
return Objects.equals(id, other.id) && Objects.equals(key, other.key) && Objects.equals(order, other.order);
}
}
private static final byte COUNT_DESC_ID = 1;
private static final byte COUNT_ASC_ID = 2;
private static final byte KEY_DESC_ID = 3;
private static final byte KEY_ASC_ID = 4;
/**
* Order by the (higher) count of each bucket.
*/
static final InternalOrder COUNT_DESC = new SimpleOrder(COUNT_DESC_ID, "_count", SortOrder.DESC, comparingCounts().reversed());
/**
* Order by the (lower) count of each bucket.
*/
static final InternalOrder COUNT_ASC = new SimpleOrder(COUNT_ASC_ID, "_count", SortOrder.ASC, comparingCounts());
/**
* Order by the key of each bucket descending.
*/
static final InternalOrder KEY_DESC = new SimpleOrder(KEY_DESC_ID, "_key", SortOrder.DESC, comparingKeys().reversed());
/**
* Order by the key of each bucket ascending.
*/
static final InternalOrder KEY_ASC = new SimpleOrder(KEY_ASC_ID, "_key", SortOrder.ASC, comparingKeys());
/**
* @return compare by {@link Bucket#getDocCount()}.
*/
private static Comparator<Bucket> comparingCounts() {
return Comparator.comparingLong(Bucket::getDocCount);
}
/**
* @return compare by {@link Bucket#getKey()} from the appropriate implementation.
*/
@SuppressWarnings("unchecked")
private static Comparator<Bucket> comparingKeys() {
return (b1, b2) -> {
if (b1 instanceof KeyComparable) {
return ((KeyComparable) b1).compareKey(b2);
}
throw new IllegalStateException("Unexpected order bucket class [" + b1.getClass() + "]");
};
}
/**
* Determine if the ordering strategy is sorting on bucket count descending.
*
* @param order bucket ordering strategy to check.
* @return {@code true} if the ordering strategy is sorting on bucket count descending, {@code false} otherwise.
*/
public static boolean isCountDesc(BucketOrder order) {
return isOrder(order, COUNT_DESC);
}
/**
* Determine if the ordering strategy is sorting on bucket key (ascending or descending).
*
* @param order bucket ordering strategy to check.
* @return {@code true} if the ordering strategy is sorting on bucket key, {@code false} otherwise.
*/
public static boolean isKeyOrder(BucketOrder order) {
return isOrder(order, KEY_ASC) || isOrder(order, KEY_DESC);
}
/**
* Determine if the ordering strategy is sorting on bucket key ascending.
*
* @param order bucket ordering strategy to check.
* @return {@code true} if the ordering strategy is sorting on bucket key ascending, {@code false} otherwise.
*/
public static boolean isKeyAsc(BucketOrder order) {
return isOrder(order, KEY_ASC);
}
/**
* Determine if the ordering strategy is sorting on bucket key descending.
*
* @param order bucket ordering strategy to check.
* @return {@code true} if the ordering strategy is sorting on bucket key descending, {@code false} otherwise.
*/
public static boolean isKeyDesc(BucketOrder order) {
return isOrder(order, KEY_DESC);
}
/**
* Determine if the ordering strategy matches the expected one.
*
* @param order bucket ordering strategy to check. If this is a {@link CompoundOrder} the first element will be
* check instead.
* @param expected expected bucket ordering strategy.
* @return {@code true} if the order matches, {@code false} otherwise.
*/
private static boolean isOrder(BucketOrder order, BucketOrder expected) {
if (order == expected) {
return true;
} else if (order instanceof CompoundOrder) {
// check if its a compound order with the first element that matches
List<BucketOrder> orders = ((CompoundOrder) order).orderElements;
if (orders.size() >= 1) {
return isOrder(orders.get(0), expected);
}
}
return false;
}
/**
* Contains logic for reading/writing {@link BucketOrder} from/to streams.
*/
public static class Streams {
/**
* Read a {@link BucketOrder} from a {@link StreamInput}.
*
* @param in stream with order data to read.
* @return order read from the stream
* @throws IOException on error reading from the stream.
*/
public static BucketOrder readOrder(StreamInput in) throws IOException {
byte id = in.readByte();
switch (id) {
case COUNT_DESC_ID:
return COUNT_DESC;
case COUNT_ASC_ID:
return COUNT_ASC;
case KEY_DESC_ID:
return KEY_DESC;
case KEY_ASC_ID:
return KEY_ASC;
case Aggregation.ID:
boolean asc = in.readBoolean();
String key = in.readString();
return new Aggregation(key, asc);
case CompoundOrder.ID:
int size = in.readVInt();
List<BucketOrder> compoundOrder = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
compoundOrder.add(Streams.readOrder(in));
}
return new CompoundOrder(compoundOrder, false);
default:
throw new RuntimeException("unknown order id [" + id + "]");
}
}
/**
* ONLY FOR HISTOGRAM ORDER: Backwards compatibility logic to read a {@link BucketOrder} from a {@link StreamInput}.
*
* @param in stream with order data to read.
* @param bwcOrderFlag {@code true} to check {@code in.readBoolean()} in the backwards compat logic before reading
* the order. {@code false} to skip this flag (order always present).
* @return order read from the stream
* @throws IOException on error reading from the stream.
*/
public static BucketOrder readHistogramOrder(StreamInput in, boolean bwcOrderFlag) throws IOException {
return Streams.readOrder(in);
}
/**
* Write a {@link BucketOrder} to a {@link StreamOutput}.
*
* @param order order to write to the stream.
* @param out stream to write the order to.
* @throws IOException on error writing to the stream.
*/
public static void writeOrder(BucketOrder order, StreamOutput out) throws IOException {
out.writeByte(order.id());
if (order instanceof Aggregation) {
Aggregation aggregationOrder = (Aggregation) order;
out.writeBoolean(aggregationOrder.order == SortOrder.ASC);
out.writeString(aggregationOrder.path().toString());
} else if (order instanceof CompoundOrder) {
CompoundOrder compoundOrder = (CompoundOrder) order;
out.writeVInt(compoundOrder.orderElements.size());
for (BucketOrder innerOrder : compoundOrder.orderElements) {
innerOrder.writeTo(out);
}
}
}
/**
* ONLY FOR HISTOGRAM ORDER: Backwards compatibility logic to write a {@link BucketOrder} to a stream.
*
* @param order order to write to the stream.
* @param out stream to write the order to.
* @param bwcOrderFlag {@code true} to always {@code out.writeBoolean(true)} for the backwards compat logic before
* writing the order. {@code false} to skip this flag.
* @throws IOException on error writing to the stream.
*/
public static void writeHistogramOrder(BucketOrder order, StreamOutput out, boolean bwcOrderFlag) throws IOException {
order.writeTo(out);
}
}
/**
* Contains logic for parsing a {@link BucketOrder} from a {@link XContentParser}.
*/
public static class Parser {
private static final DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(Parser.class);
/**
* Parse a {@link BucketOrder} from {@link XContent}.
*
* @param parser for parsing {@link XContent} that contains the order.
* @return bucket ordering strategy
* @throws IOException on error a {@link XContent} parsing error.
*/
public static BucketOrder parseOrderParam(XContentParser parser) throws IOException {
XContentParser.Token token;
String orderKey = null;
boolean orderAsc = false;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
orderKey = parser.currentName();
} else if (token == XContentParser.Token.VALUE_STRING) {
String dir = parser.text();
if ("asc".equalsIgnoreCase(dir)) {
orderAsc = true;
} else if ("desc".equalsIgnoreCase(dir)) {
orderAsc = false;
} else {
throw new ParsingException(parser.getTokenLocation(), "Unknown order direction [" + dir + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(), "Unexpected token [" + token + "] for [order]");
}
}
if (orderKey == null) {
throw new ParsingException(parser.getTokenLocation(), "Must specify at least one field for [order]");
}
// _term and _time order deprecated in 6.0; replaced by _key
if ("_term".equals(orderKey) || "_time".equals(orderKey)) {
deprecationLogger.deprecate(
"aggregation_order_key",
"Deprecated aggregation order key [{}] used, replaced by [_key]",
orderKey
);
}
switch (orderKey) {
case "_term":
case "_time":
case "_key":
return orderAsc ? KEY_ASC : KEY_DESC;
case "_count":
return orderAsc ? COUNT_ASC : COUNT_DESC;
default: // assume all other orders are sorting on a sub-aggregation. Validation occurs later.
return aggregation(orderKey, orderAsc);
}
}
}
}
|
923651f539cbb9f2c9a1a831124903d3aa554590 | 935 | java | Java | app/models/Product.java | Clivern/Trent | 403ec2e9340330939fe9c9f511cee9c53ef7ad0f | [
"MIT"
] | 2 | 2017-06-24T11:17:06.000Z | 2018-04-28T21:56:11.000Z | app/models/Product.java | Clivern/Trent | 403ec2e9340330939fe9c9f511cee9c53ef7ad0f | [
"MIT"
] | null | null | null | app/models/Product.java | Clivern/Trent | 403ec2e9340330939fe9c9f511cee9c53ef7ad0f | [
"MIT"
] | 1 | 2018-04-28T21:55:25.000Z | 2018-04-28T21:55:25.000Z | 21.744186 | 57 | 0.574332 | 997,630 | package models;
import java.util.*;
import java.lang.*;
public class Product
{
public String name;
public String ean;
private static ArrayList<Product> products;
static{
products = new ArrayList<Product>();
products.add(new Product("Bottle-X1", "X1-123"));
products.add(new Product("Bottle-X2", "X2-234"));
products.add(new Product("Bottle-X3", "X3-738"));
products.add(new Product("Bottle-X4", "X4-283"));
}
public Product(){}
public Product(String name, String ean)
{
this.name = name;
this.ean = ean;
}
public static ArrayList<Product> findAll()
{
return new ArrayList<Product>(products);
}
public static Product findByEan(String ean)
{
for (Product product : products){
if(product.ean.equals(ean)){
return product;
}
}
return null;
}
} |
92365398a14c317a609ea9f68486131b9a891a9a | 1,970 | java | Java | app/src/main/java/com/tcity/android/background/runnable/chain/RunnableChain.java | sproshev/tcity | 0bdbd3904ca34dfbc5685033265ba1eb8a301e05 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/tcity/android/background/runnable/chain/RunnableChain.java | sproshev/tcity | 0bdbd3904ca34dfbc5685033265ba1eb8a301e05 | [
"Apache-2.0"
] | 16 | 2015-01-07T23:48:05.000Z | 2015-02-07T14:10:32.000Z | app/src/main/java/com/tcity/android/background/runnable/chain/RunnableChain.java | sproshev/tcity | 0bdbd3904ca34dfbc5685033265ba1eb8a301e05 | [
"Apache-2.0"
] | null | null | null | 31.269841 | 87 | 0.732487 | 997,631 | /*
* Copyright 2014 Semyon Proshev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tcity.android.background.runnable.chain;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class RunnableChain {
@NotNull
public static RunnableChain getAndRunnableChain(@NotNull Runnable... runnables) {
return new ZeroLevelRunnableChain(true, runnables);
}
@NotNull
public static RunnableChain getOrRunnableChain(@NotNull Runnable... runnables) {
return new ZeroLevelRunnableChain(false, runnables);
}
@NotNull
public static RunnableChain getSingleRunnableChain(@NotNull Runnable runnable) {
return new ZeroLevelRunnableChain(true, runnable);
}
@NotNull
public static RunnableChain getAndRunnableChain(@NotNull RunnableChain... chains) {
return new DeeperLevelRunnableChain(true, chains);
}
@NotNull
public static RunnableChain getOrRunnableChain(@NotNull RunnableChain... chains) {
return new DeeperLevelRunnableChain(false, chains);
}
@NotNull
public ExecutableRunnableChain toAsyncTask(@Nullable Listener listener) {
return new ExecutableRunnableChain(this, listener);
}
protected abstract boolean run(@Nullable Listener listener);
public static interface Listener {
public void onFinished();
public void onException(@NotNull Exception e);
}
}
|
923655f2b08f8af4b815fb47cfc1a12868ee3979 | 2,524 | java | Java | examples/hazelcast-3x/src/main/java/com/inomera/telco/commons/lock/hazelcastexample/service/HazelcastLockDemoService.java | sedran/lock-provider | 0c8074e1273a831f5fad78bf9e098c1357285434 | [
"MIT"
] | 7 | 2020-12-04T07:25:34.000Z | 2020-12-06T16:45:08.000Z | examples/hazelcast-3x/src/main/java/com/inomera/telco/commons/lock/hazelcastexample/service/HazelcastLockDemoService.java | sedran/lock-provider | 0c8074e1273a831f5fad78bf9e098c1357285434 | [
"MIT"
] | 7 | 2020-12-04T07:26:34.000Z | 2021-11-24T15:26:14.000Z | examples/hazelcast-3x/src/main/java/com/inomera/telco/commons/lock/hazelcastexample/service/HazelcastLockDemoService.java | sedran/lock-provider | 0c8074e1273a831f5fad78bf9e098c1357285434 | [
"MIT"
] | 2 | 2020-12-05T16:09:11.000Z | 2020-12-14T20:54:07.000Z | 34.575342 | 89 | 0.64065 | 997,632 | package com.inomera.telco.commons.lock.hazelcastexample.service;
import com.inomera.telco.commons.lock.LockProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Serdar Kuzucu
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class HazelcastLockDemoService {
private static final String LOCK_MAP_NAME = "lock-map-1";
private static final String PESSIMISTIC_LOCK_KEY = "lock-key-1";
private static final String OPTIMISTIC_LOCK_KEY = "lock-key-2";
private final ExecutorService executorService = Executors.newFixedThreadPool(10);
private final AtomicBoolean running = new AtomicBoolean(true);
private final LockProvider lockProvider;
@PostConstruct
public void startDemo() {
for (int i = 0; i < 5; i++) {
executorService.submit(this::sleepInPessimisticLock);
executorService.submit(this::sleepInOptimisticLock);
}
}
private void sleepInPessimisticLock() {
while (running.get()) {
lockProvider.executeInLock(LOCK_MAP_NAME, PESSIMISTIC_LOCK_KEY, () -> {
try {
LOG.info("{} in pessimistic lock", Thread.currentThread().getName());
Thread.sleep(5000);
} catch (InterruptedException e) {
LOG.debug("Thread is interrupted. Exiting.");
Thread.currentThread().interrupt();
}
});
}
}
private void sleepInOptimisticLock() {
while (running.get()) {
lockProvider.executeInTryLock(LOCK_MAP_NAME, OPTIMISTIC_LOCK_KEY, () -> {
try {
LOG.info("{} in optimistic lock", Thread.currentThread().getName());
Thread.sleep(5000);
} catch (InterruptedException e) {
LOG.debug("Thread is interrupted. Exiting.");
Thread.currentThread().interrupt();
}
});
}
}
@PreDestroy
public void stop() throws InterruptedException {
running.set(false);
this.executorService.shutdownNow();
this.executorService.awaitTermination(1, TimeUnit.MINUTES);
}
}
|
923656908b9d3046d71fcd0827476d94184010fc | 1,770 | java | Java | http-server/src/test/java/com/twitter/finatra/http/tests/integration/doeverything/main/HelloService.java | csaltos/finatra | 9a3b763a71c17d4cacee3517dce8f7ae912fb68c | [
"Apache-2.0"
] | 1,780 | 2015-01-02T08:30:13.000Z | 2022-03-31T00:36:10.000Z | http-server/src/test/java/com/twitter/finatra/http/tests/integration/doeverything/main/HelloService.java | csaltos/finatra | 9a3b763a71c17d4cacee3517dce8f7ae912fb68c | [
"Apache-2.0"
] | 415 | 2015-01-07T05:45:33.000Z | 2022-03-07T06:48:21.000Z | http/src/test/java/com/twitter/finatra/http/tests/integration/doeverything/main/HelloService.java | foursquare/finatra | 9c6135ae5f42b0e50aa9a80c6fb91ffdfb4d0265 | [
"Apache-2.0"
] | 423 | 2015-01-07T17:21:51.000Z | 2022-03-21T00:56:46.000Z | 30.517241 | 81 | 0.629944 | 997,633 | package com.twitter.finatra.http.tests.integration.doeverything.main;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import com.twitter.finagle.http.Request;
import com.twitter.finagle.http.Response;
import com.twitter.finatra.http.response.ResponseBuilder;
import com.twitter.util.Future;
public class HelloService {
private final ResponseBuilder response;
@Inject
public HelloService(ResponseBuilder response) {
this.response = response;
}
/** returns an http Response */
Response hi(Request request) {
return hi(request, true);
}
/** returns an http Response */
Response hi(Request request, Boolean verifyHeaders) {
if (verifyHeaders) {
assert request.headerMap().getAll("test").mkString("").equals("156");
}
return response.ok("Hello " + request.getParam("name"));
}
/** returns a Goodbye response */
GoodbyeResponse goodbye(Request request) {
return new GoodbyeResponse("guest", "cya", 123);
}
/** returns a Future Map[String, Object] */
Future<Map<String, Object>> computeQueryResult(Request request) {
String query = request.getParam("q");
Map<String, String> results = new HashMap<String, String>();
results.put("a", "1");
results.put("b", "2");
results.put("c", "3");
results.put("d", "4");
results.put("e", "5");
Map<String, Object> result = new HashMap<String, Object>();
result.put("query", query);
result.put("numResults", "5");
result.put("results", results);
result.put("user", "Bob");
result.put("timestamp", "Thu, 19 May 2016 00:00:00 +00:00");
return Future.value(result);
}
}
|
9236576a0cbe8407a8ec3078e5c305094a13288b | 5,512 | java | Java | src/ua/org/slovo/securesms/crypto/AsymmetricMasterCipher.java | varkon/MilChat | c68b8046f8767ffc7aea48e3801188bfde2501e6 | [
"Apache-2.0"
] | 1 | 2018-04-15T13:30:15.000Z | 2018-04-15T13:30:15.000Z | src/ua/org/slovo/securesms/crypto/AsymmetricMasterCipher.java | varkon/MilChat | c68b8046f8767ffc7aea48e3801188bfde2501e6 | [
"Apache-2.0"
] | null | null | null | src/ua/org/slovo/securesms/crypto/AsymmetricMasterCipher.java | varkon/MilChat | c68b8046f8767ffc7aea48e3801188bfde2501e6 | [
"Apache-2.0"
] | null | null | null | 39.654676 | 112 | 0.735305 | 997,634 | /**
* Copyright (C) 2011 Whisper Systems
* Copyright (C) 2013 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ua.org.slovo.securesms.crypto;
import ua.org.slovo.securesms.util.Base64;
import ua.org.slovo.securesms.util.Util;
import org.whispersystems.libsignal.InvalidKeyException;
import org.whispersystems.libsignal.InvalidMessageException;
import org.whispersystems.libsignal.ecc.Curve;
import org.whispersystems.libsignal.ecc.ECKeyPair;
import org.whispersystems.libsignal.ecc.ECPrivateKey;
import org.whispersystems.libsignal.ecc.ECPublicKey;
import ua.org.slovo.securesms.util.Conversions;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* This class is used to asymmetricly encrypt local data. This is used in the case
* where TextSecure receives an SMS, but the user's local encryption passphrase is
* not cached (either because of a timeout, or because it hasn't yet been entered).
*
* In this case, we have access to the public key of a local keypair. We encrypt
* the message with this, and put it into the DB. When the user enters their passphrase,
* we can get access to the private key of the local keypair, decrypt the message, and
* replace it into the DB with symmetric encryption.
*
* The encryption protocol is as follows:
*
* 1) Generate an ephemeral keypair.
* 2) Do ECDH with the public key of the local durable keypair.
* 3) Do KMF with the ECDH result to obtain a master secret.
* 4) Encrypt the message with that master secret.
*
* @author Moxie Marlinspike
*
*/
public class AsymmetricMasterCipher {
private final AsymmetricMasterSecret asymmetricMasterSecret;
public AsymmetricMasterCipher(AsymmetricMasterSecret asymmetricMasterSecret) {
this.asymmetricMasterSecret = asymmetricMasterSecret;
}
public byte[] encryptBytes(byte[] body) {
try {
ECPublicKey theirPublic = asymmetricMasterSecret.getDjbPublicKey();
ECKeyPair ourKeyPair = Curve.generateKeyPair();
byte[] secret = Curve.calculateAgreement(theirPublic, ourKeyPair.getPrivateKey());
MasterCipher masterCipher = getMasterCipherForSecret(secret);
byte[] encryptedBodyBytes = masterCipher.encryptBytes(body);
PublicKey ourPublicKey = new PublicKey(31337, ourKeyPair.getPublicKey());
byte[] publicKeyBytes = ourPublicKey.serialize();
return Util.combine(publicKeyBytes, encryptedBodyBytes);
} catch (InvalidKeyException e) {
throw new AssertionError(e);
}
}
public byte[] decryptBytes(byte[] combined) throws IOException, InvalidMessageException {
try {
byte[][] parts = Util.split(combined, PublicKey.KEY_SIZE, combined.length - PublicKey.KEY_SIZE);
PublicKey theirPublicKey = new PublicKey(parts[0], 0);
ECPrivateKey ourPrivateKey = asymmetricMasterSecret.getPrivateKey();
byte[] secret = Curve.calculateAgreement(theirPublicKey.getKey(), ourPrivateKey);
MasterCipher masterCipher = getMasterCipherForSecret(secret);
return masterCipher.decryptBytes(parts[1]);
} catch (InvalidKeyException e) {
throw new InvalidMessageException(e);
}
}
public String decryptBody(String body) throws IOException, InvalidMessageException {
byte[] combined = Base64.decode(body);
return new String(decryptBytes(combined));
}
public String encryptBody(String body) {
return Base64.encodeBytes(encryptBytes(body.getBytes()));
}
private MasterCipher getMasterCipherForSecret(byte[] secretBytes) {
SecretKeySpec cipherKey = deriveCipherKey(secretBytes);
SecretKeySpec macKey = deriveMacKey(secretBytes);
MasterSecret masterSecret = new MasterSecret(cipherKey, macKey);
return new MasterCipher(masterSecret);
}
private SecretKeySpec deriveMacKey(byte[] secretBytes) {
byte[] digestedBytes = getDigestedBytes(secretBytes, 1);
byte[] macKeyBytes = new byte[20];
System.arraycopy(digestedBytes, 0, macKeyBytes, 0, macKeyBytes.length);
return new SecretKeySpec(macKeyBytes, "HmacSHA1");
}
private SecretKeySpec deriveCipherKey(byte[] secretBytes) {
byte[] digestedBytes = getDigestedBytes(secretBytes, 0);
byte[] cipherKeyBytes = new byte[16];
System.arraycopy(digestedBytes, 0, cipherKeyBytes, 0, cipherKeyBytes.length);
return new SecretKeySpec(cipherKeyBytes, "AES");
}
private byte[] getDigestedBytes(byte[] secretBytes, int iteration) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secretBytes, "HmacSHA256"));
return mac.doFinal(Conversions.intToByteArray(iteration));
} catch (NoSuchAlgorithmException | java.security.InvalidKeyException e) {
throw new AssertionError(e);
}
}
}
|
92365853f23de2a7d12c97a8142f5c8ac23576a5 | 2,208 | java | Java | hermes-consumers/src/main/java/pl/allegro/tech/hermes/consumers/consumer/oauth/OAuthProvidersNotifyingCache.java | lukidzi/hermes | 051f0133b24b16f860d80b8069dbff7251d41132 | [
"Apache-2.0"
] | 743 | 2015-05-15T12:48:55.000Z | 2022-03-19T07:03:24.000Z | hermes-consumers/src/main/java/pl/allegro/tech/hermes/consumers/consumer/oauth/OAuthProvidersNotifyingCache.java | lukidzi/hermes | 051f0133b24b16f860d80b8069dbff7251d41132 | [
"Apache-2.0"
] | 898 | 2015-05-15T21:02:54.000Z | 2022-03-24T09:51:30.000Z | hermes-consumers/src/main/java/pl/allegro/tech/hermes/consumers/consumer/oauth/OAuthProvidersNotifyingCache.java | lukidzi/hermes | 051f0133b24b16f860d80b8069dbff7251d41132 | [
"Apache-2.0"
] | 205 | 2015-05-15T13:42:45.000Z | 2022-03-16T16:21:02.000Z | 36.196721 | 122 | 0.707428 | 997,635 | package pl.allegro.tech.hermes.consumers.consumer.oauth;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.allegro.tech.hermes.api.OAuthProvider;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
public class OAuthProvidersNotifyingCache extends PathChildrenCache implements PathChildrenCacheListener {
private static final Logger logger = LoggerFactory.getLogger(OAuthProvidersNotifyingCache.class);
private final ObjectMapper objectMapper;
private OAuthProviderCacheListener listener;
public OAuthProvidersNotifyingCache(CuratorFramework curator, String path, ExecutorService executorService,
ObjectMapper objectMapper) {
super(curator, path, true, false, executorService);
this.objectMapper = objectMapper;
getListenable().addListener(this);
}
@Override
public void start() throws Exception {
super.start();
}
public void setListener(OAuthProviderCacheListener listener) {
this.listener = listener;
}
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
if (event.getData() == null || event.getData().getData() == null) {
return;
}
switch (event.getType()) {
case CHILD_UPDATED:
parseEvent(event.getData().getPath(), event.getData().getData()).ifPresent(listener::oAuthProviderUpdate);
break;
}
}
private Optional<OAuthProvider> parseEvent(String path, byte[] data) {
try {
return Optional.of(objectMapper.readValue(data, OAuthProvider.class));
} catch (IOException e) {
logger.error("Failed to parse object at path {}", path);
return Optional.empty();
}
}
}
|
92365945191769615e64b86bb0efb8adae66090f | 1,059 | java | Java | wms-detect/src/main/java/com/deer/wms/detect/service/impl/MtAloneSampleClothOutDetServiceImpl.java | yuanfayang/wms-parent | 17d7796daf9f75d05c8505f69f2bc2baf3192cc6 | [
"0BSD"
] | null | null | null | wms-detect/src/main/java/com/deer/wms/detect/service/impl/MtAloneSampleClothOutDetServiceImpl.java | yuanfayang/wms-parent | 17d7796daf9f75d05c8505f69f2bc2baf3192cc6 | [
"0BSD"
] | null | null | null | wms-detect/src/main/java/com/deer/wms/detect/service/impl/MtAloneSampleClothOutDetServiceImpl.java | yuanfayang/wms-parent | 17d7796daf9f75d05c8505f69f2bc2baf3192cc6 | [
"0BSD"
] | null | null | null | 35.3 | 152 | 0.83475 | 997,636 | package com.deer.wms.detect.service.impl;
import com.deer.wms.detect.dao.MtAloneSampleClothOutDetMapper;
import com.deer.wms.detect.model.MtAloneSampleClothOutDet;
import com.deer.wms.detect.model.MtAloneSampleClothOutDetParams;
import com.deer.wms.detect.service.MtAloneSampleClothOutDetService;
import com.deer.wms.project.seed.core.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by guotuanting on 2019/08/28.
*/
@Service
@Transactional
public class MtAloneSampleClothOutDetServiceImpl extends AbstractService<MtAloneSampleClothOutDet, Integer> implements MtAloneSampleClothOutDetService {
@Autowired
private MtAloneSampleClothOutDetMapper mtAloneSampleClothOutDetMapper;
@Override
public List<MtAloneSampleClothOutDet> findList(MtAloneSampleClothOutDetParams params) {
return mtAloneSampleClothOutDetMapper.findList(params);
}
}
|
923659a20899b1438419ac013cc7c2f1d6744054 | 1,268 | java | Java | src/main/java/com/rapiddweller/common/LogCategoriesConstants.java | rapiddweller/rd-lib-common | 6083da11c44e1d43947dcddcdc0e4065fab33b51 | [
"Apache-2.0"
] | 1 | 2021-01-25T07:17:19.000Z | 2021-01-25T07:17:19.000Z | src/main/java/com/rapiddweller/common/LogCategoriesConstants.java | rapiddweller/rd-lib-common | 6083da11c44e1d43947dcddcdc0e4065fab33b51 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/rapiddweller/common/LogCategoriesConstants.java | rapiddweller/rd-lib-common | 6083da11c44e1d43947dcddcdc0e4065fab33b51 | [
"Apache-2.0"
] | null | null | null | 29.790698 | 76 | 0.709602 | 997,637 | /*
* Copyright (C) 2004-2015 Volker Bergmann (anpch@example.com).
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rapiddweller.common;
/**
* Defines log categories common for all databene components.
* Created at 02.08.2008 16:21:40
*
* @author Volker Bergmann
* @since 0.4.5
*/
public class LogCategoriesConstants {
/**
* The constant JDBC.
*/
public static final String JDBC = "com.rapiddweller.JDBC";
/**
* The constant SQL.
*/
public static final String SQL = "com.rapiddweller.SQL";
/**
* The constant CONFIG.
*/
public static final String CONFIG = "com.rapiddweller.CONFIG";
/**
* The constant COMMENT.
*/
public static final String COMMENT = "com.rapiddweller.COMMENT";
}
|
92365cf14df10516aa9419d7f656d304a9fa60a8 | 178 | java | Java | src/com/hetekivi/Listener.java | SanteriHetekivi/JavaAssignment | d1c7cf7e21d8d449eeb1ff25294418bad7d6f674 | [
"Apache-2.0"
] | null | null | null | src/com/hetekivi/Listener.java | SanteriHetekivi/JavaAssignment | d1c7cf7e21d8d449eeb1ff25294418bad7d6f674 | [
"Apache-2.0"
] | null | null | null | src/com/hetekivi/Listener.java | SanteriHetekivi/JavaAssignment | d1c7cf7e21d8d449eeb1ff25294418bad7d6f674 | [
"Apache-2.0"
] | null | null | null | 12.714286 | 42 | 0.629213 | 997,638 | package com.hetekivi;
/**
* Created by Santeri Hetekivi on 2/15/16.
*/
/**
* Listener for Threads.
*/
public interface Listener {
void Complete();
void Failed();
}
|
92365d0f16f1ed086c324df8511143bdcfc385a1 | 3,586 | java | Java | unix-common/src/main/java/com/roclas/mojo/unix/io/FileScanner.java | roclas/unix-maven-plugin | e89b342a5df1876948e9b1dec87f26eec714c883 | [
"MIT"
] | null | null | null | unix-common/src/main/java/com/roclas/mojo/unix/io/FileScanner.java | roclas/unix-maven-plugin | e89b342a5df1876948e9b1dec87f26eec714c883 | [
"MIT"
] | null | null | null | unix-common/src/main/java/com/roclas/mojo/unix/io/FileScanner.java | roclas/unix-maven-plugin | e89b342a5df1876948e9b1dec87f26eec714c883 | [
"MIT"
] | null | null | null | 31.45614 | 105 | 0.575851 | 997,639 | package com.roclas.mojo.unix.io;
/*
* The MIT License
*
* Copyright 2009 The Codehaus.
*
* 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.
*/
import fj.*;
import static fj.P.*;
import fj.data.List;
import fj.data.*;
import static fj.data.Option.*;
import static fj.data.Stream.*;
import static java.util.Arrays.*;
import com.roclas.mojo.unix.io.*;
import static com.roclas.mojo.unix.io.IncludeExcludeFilter.*;
import static com.roclas.mojo.unix.util.RelativePath.*;
import java.io.*;
import java.util.*;
public class FileScanner
{
private final File file;
private final String absolutePath;
private final IncludeExcludeFilter selector;
public FileScanner( File file, String[] includes, String[] excludes )
throws IOException
{
this.file = file.getAbsoluteFile();
if ( !file.isDirectory() )
{
throw new IOException( "Not a directory." );
}
selector = includeExcludeFilter().
addStringIncludes( includes == null ? Collections.<String>emptyList() : asList( includes ) ).
addStringExcludes( excludes == null ? Collections.<String>emptyList() : asList( excludes ) ).
create();
absolutePath = file.getAbsolutePath();
}
public Stream<File> toStream()
{
class State
{
private List<File> stack;
public State( File file )
{
stack = List.single( file );
}
}
return unfold( new F<State, Option<P2<File, State>>>()
{
public Option<P2<File, State>> f( State state )
{
if ( state.stack.isEmpty() )
{
return none();
}
String s;
while ( state.stack.isNotEmpty() )
{
File next = state.stack.head();
state.stack = state.stack.drop( 1 );
if ( next.isDirectory() )
{
File[] files = next.listFiles();
for ( File file : files )
{
state.stack = state.stack.cons( file );
}
}
if ( selector.matches( relativePathFromFiles( file, next ) ) )
{
return some( p( next, state ) );
}
}
return none();
}
}, new State( file ) );
}
}
|
92365d2c9a4a96c180875006f5184daa9b46e8a1 | 3,012 | java | Java | src/main/java/io/hermes/action/support/AdapterActionFuture.java | spancer/zeus | 3bb34cb69821027e349e8486376ccef5b0ef23fd | [
"Apache-2.0"
] | 12 | 2021-09-22T07:23:48.000Z | 2022-03-09T01:02:16.000Z | src/main/java/io/hermes/action/support/AdapterActionFuture.java | spancer/zeus | 3bb34cb69821027e349e8486376ccef5b0ef23fd | [
"Apache-2.0"
] | null | null | null | src/main/java/io/hermes/action/support/AdapterActionFuture.java | spancer/zeus | 3bb34cb69821027e349e8486376ccef5b0ef23fd | [
"Apache-2.0"
] | 3 | 2021-11-09T07:48:55.000Z | 2022-03-27T14:04:25.000Z | 31.375 | 84 | 0.685259 | 997,640 | /*******************************************************************************
* Copyright 2021 spancer
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.hermes.action.support;
import io.hermes.HermesException;
import io.hermes.HermesInterruptedException;
import io.hermes.HermesTimeoutException;
import io.hermes.action.ActionFuture;
import io.hermes.action.ActionListener;
import io.hermes.transport.TransportException;
import io.hermes.util.TimeValue;
import io.hermes.util.concurrent.AbstractFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author spancer.ray
*/
public abstract class AdapterActionFuture<T, L> extends AbstractFuture<T> implements
ActionFuture<T>, ActionListener<L> {
@Override
public T actionGet() throws HermesException {
try {
return get();
} catch (InterruptedException e) {
throw new HermesInterruptedException(e.getMessage());
} catch (ExecutionException e) {
if (e.getCause() instanceof HermesException) {
throw (HermesException) e.getCause();
} else {
throw new TransportException("Failed execution", e);
}
}
}
@Override
public T actionGet(String timeout) throws HermesException {
return actionGet(TimeValue.parseTimeValue(timeout, null));
}
@Override
public T actionGet(long timeoutMillis) throws HermesException {
return actionGet(timeoutMillis, TimeUnit.MILLISECONDS);
}
@Override
public T actionGet(TimeValue timeout) throws HermesException {
return actionGet(timeout.millis(), TimeUnit.MILLISECONDS);
}
@Override
public T actionGet(long timeout, TimeUnit unit) throws HermesException {
try {
return get(timeout, unit);
} catch (TimeoutException e) {
throw new HermesTimeoutException(e.getMessage());
} catch (InterruptedException e) {
throw new HermesInterruptedException(e.getMessage());
} catch (ExecutionException e) {
if (e.getCause() instanceof HermesException) {
throw (HermesException) e.getCause();
} else {
throw new HermesException("Failed execution", e);
}
}
}
@Override
public void onResponse(L result) {
set(convert(result));
}
@Override
public void onFailure(Throwable e) {
setException(e);
}
protected abstract T convert(L listenerResponse);
}
|
92365d3ba80b254426608750371faeddce718480 | 3,885 | java | Java | app/src/main/java/com/elmuj/learnmath/adapter/HistoryAdapter.java | 9m9n/quizzy | 1d84568d578d1bc34671739e863c7154b89b4496 | [
"MIT"
] | 4 | 2021-10-01T05:12:04.000Z | 2021-12-29T03:37:57.000Z | app/src/main/java/com/elmuj/learnmath/adapter/HistoryAdapter.java | 9m9n/quizzy | 1d84568d578d1bc34671739e863c7154b89b4496 | [
"MIT"
] | 5 | 2021-10-01T05:25:29.000Z | 2021-10-17T14:13:40.000Z | app/src/main/java/com/elmuj/learnmath/adapter/HistoryAdapter.java | 9m9n/quizzy | 1d84568d578d1bc34671739e863c7154b89b4496 | [
"MIT"
] | 7 | 2021-10-01T05:12:30.000Z | 2021-10-08T16:49:50.000Z | 32.375 | 102 | 0.679537 | 997,641 | package com.elmuj.learnmath.adapter;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.elmuj.learnmath.R;
import com.elmuj.learnmath.model.HistoryModel;
import com.elmuj.learnmath.utils.Constant;
import java.util.List;
public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.HistoryHolder> {
private Activity context;
private List<HistoryModel> historyNotesList;
public HistoryAdapter(Activity context, List<HistoryModel> historyNotes) {
this.context = context;
this.historyNotesList = historyNotes;
}
@NonNull
@Override
public HistoryAdapter.HistoryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_history, parent, false);
return new HistoryHolder(view);
}
@Override
public void onBindViewHolder(@NonNull HistoryAdapter.HistoryHolder holder, int position) {
HistoryModel historyNotes = historyNotesList.get(position);
Constant.setDefaultLanguage(context);
if (position == 0) {
holder.txt_id.setText(context.getString(R.string.no));
setBg(holder.txt_id);
setBg(holder.text_question);
setBg(holder.text_answer);
setBg(holder.text_userAnswer);
} else {
holder.txt_id.setText(Constant.getAllTranslatedDigit(String.valueOf(position)));
setBg1(holder.txt_id);
setBg1(holder.text_question);
setBg1(holder.text_answer);
setBg1(holder.text_userAnswer);
}
if (historyNotes != null) {
holder.text_question.setText(Constant.getAllTranslatedDigit(historyNotes.question));
holder.text_answer.setText(Constant.getAllTranslatedDigit(historyNotes.answer));
holder.text_userAnswer.setText(Constant.getAllTranslatedDigit(historyNotes.userAnswer));
}
}
private void setBg1(TextView textView) {
textView.setBackgroundResource(getDrawableBg());
textView.setTextColor(Constant.getThemeColor(context, R.attr.theme_text_color));
}
private void setBg(TextView textView) {
textView.setBackground(getDrawable());
textView.setTextColor(Color.WHITE);
}
public Drawable getDrawable() {
GradientDrawable gd = new GradientDrawable();
gd.setColor(Constant.getThemeColor(context, R.attr.colorPrimary));
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke(1, ContextCompat.getColor(context, R.color.white));
return gd;
}
private int getDrawableBg() {
return R.drawable.table_content_cell;
}
@Override
public int getItemCount() {
return historyNotesList.size();
}
class HistoryHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView text_answer, text_question, text_userAnswer, txt_id;
HistoryHolder(@NonNull View itemView) {
super(itemView);
txt_id = itemView.findViewById(R.id.txt_id);
imageView = itemView.findViewById(R.id.imageView);
text_question = itemView.findViewById(R.id.text_question);
text_answer = itemView.findViewById(R.id.txt_answer);
text_userAnswer = itemView.findViewById(R.id.txt_userAnswer);
}
}
}
|
92365d77705d72a96ae1f5cd46200987aa549377 | 1,998 | java | Java | subprojects/file-collections/src/main/java/org/gradle/api/internal/file/AntFileTreeBuilder.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 2 | 2018-02-10T18:44:02.000Z | 2018-03-25T07:17:04.000Z | subprojects/file-collections/src/main/java/org/gradle/api/internal/file/AntFileTreeBuilder.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 12 | 2020-07-11T15:43:32.000Z | 2020-10-13T23:39:44.000Z | subprojects/file-collections/src/main/java/org/gradle/api/internal/file/AntFileTreeBuilder.java | jdai8/gradle | 0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d | [
"Apache-2.0"
] | 4 | 2016-12-30T06:18:52.000Z | 2021-01-13T10:39:29.000Z | 36.327273 | 107 | 0.66016 | 997,642 | /*
* Copyright 2016 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.gradle.api.internal.file;
import com.google.common.collect.ImmutableMap;
import groovy.lang.Closure;
import org.gradle.api.tasks.AntBuilderAware;
import org.gradle.internal.metaobject.BeanDynamicObject;
import org.gradle.internal.metaobject.DynamicObject;
import java.io.File;
import java.util.Map;
public class AntFileTreeBuilder implements AntBuilderAware {
private final Map<String, File> files;
public AntFileTreeBuilder(Map<String, File> files) {
this.files = files;
}
@Override
public Object addToAntBuilder(Object node, String childNodeName) {
final DynamicObject dynamicObject = new BeanDynamicObject(node);
dynamicObject.invokeMethod(childNodeName == null ? "resources" : childNodeName, new Closure(this) {
public Object doCall(Object ignore) {
for (Map.Entry<String, File> entry : files.entrySet()) {
String name = entry.getKey();
File file = entry.getValue();
// gradleFileResource type is mapped to AntFileResource
dynamicObject.invokeMethod("gradleFileResource", ImmutableMap.of(
"file", file.getAbsolutePath(),
"name", name
));
}
return null;
}
});
return node;
}
}
|
92365e7224fd95a2a41ea46a7e21ccb2b6182ebb | 3,118 | java | Java | src/main/java/cn/qkmango/tms/deleteQuery/controller/DeleteController.java | qkmango/tms | 24d377c521c4bebe44a83140f911c484cbf1429a | [
"WTFPL"
] | 1 | 2021-07-20T15:32:27.000Z | 2021-07-20T15:32:27.000Z | src/main/java/cn/qkmango/tms/deleteQuery/controller/DeleteController.java | qkmango/tms | 24d377c521c4bebe44a83140f911c484cbf1429a | [
"WTFPL"
] | null | null | null | src/main/java/cn/qkmango/tms/deleteQuery/controller/DeleteController.java | qkmango/tms | 24d377c521c4bebe44a83140f911c484cbf1429a | [
"WTFPL"
] | null | null | null | 30.871287 | 124 | 0.721616 | 997,643 | package cn.qkmango.tms.deleteQuery.controller;
import cn.qkmango.tms.deleteQuery.service.DeleteService;
import cn.qkmango.tms.domain.orm.User;
import cn.qkmango.tms.domain.bind.PermissionType;
import cn.qkmango.tms.common.exception.DeleteException;
import cn.qkmango.tms.common.exception.InsertException;
import cn.qkmango.tms.common.annotation.Permission;
import cn.qkmango.tms.common.map.ResponseMap;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@RestController
@RequestMapping(value = "/delete",method = RequestMethod.POST)
public class DeleteController {
@Resource
private DeleteService service;
@Resource
private ReloadableResourceBundleMessageSource messageSource;
@Permission(PermissionType.admin)
@RequestMapping("/deleteBuilding.do")
public Map<String, Object> deleteBuilding(Integer id, Locale locale) throws DeleteException {
service.deleteBuilding(id,locale);
ResponseMap map = new ResponseMap();
map.setSuccess(true);
map.setMessage(messageSource.getMessage("db.deleteBuilding.success",null,locale));
return map;
}
@Permission(PermissionType.admin)
@RequestMapping("/deleteRoom.do")
public Map<String, Object> deleteRoom(Integer id, Locale locale) throws DeleteException {
service.deleteRoom(id,locale);
ResponseMap map = new ResponseMap();
map.setSuccess(true);
map.setMessage(messageSource.getMessage("db.deleteRoom.success",null,locale));
return map;
}
@Permission(PermissionType.admin)
@RequestMapping("/deleteYear.do")
public Map<String, Object> deleteYear(Integer year,Locale locale) throws DeleteException {
service.deleteYear(year,locale);
ResponseMap map = new ResponseMap();
map.setSuccess(true);
map.setMessage(messageSource.getMessage("db.deleteYear.success",null,locale));
return map;
}
/**
* 删除选课,删除学生已经选择的课程
* @param courseId
* @param session
* @param locale
* @return
* @throws InsertException
*/
@Permission(PermissionType.student)
@RequestMapping("/deleteElective.do")
public Map<String, Object> deleteElective(Integer courseId, HttpSession session, Locale locale) throws DeleteException {
User user = (User) session.getAttribute("user");
Integer id = user.getId();
HashMap<String, Object> param = new HashMap<>(2);
param.put("studentId",id);
param.put("courseId",courseId);
service.deleteElective(param,locale);
ResponseMap map = new ResponseMap();
map.setSuccess(true);
map.setMessage(messageSource.getMessage("db.deleteElective.success",null,locale));
return map;
}
}
|
92365e8880adf07a3daa102c5d71e23cab5e4fbb | 302 | java | Java | PadraoStrategy.Geofisica.N2_Questao01/src/model/services/VShale.java | enzoappi/ProjetoDeSistemas2.Java.FEMASS | 7a5326ae26a896d4bdea82e503bda6bca32e5495 | [
"MIT"
] | null | null | null | PadraoStrategy.Geofisica.N2_Questao01/src/model/services/VShale.java | enzoappi/ProjetoDeSistemas2.Java.FEMASS | 7a5326ae26a896d4bdea82e503bda6bca32e5495 | [
"MIT"
] | null | null | null | PadraoStrategy.Geofisica.N2_Questao01/src/model/services/VShale.java | enzoappi/ProjetoDeSistemas2.Java.FEMASS | 7a5326ae26a896d4bdea82e503bda6bca32e5495 | [
"MIT"
] | null | null | null | 17.764706 | 79 | 0.678808 | 997,644 | /*
* 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 model.services;
/**
*
* @author enzoappi
*/
public interface VShale {
public void run();
}
|
92365ea84c8e1b36ec79b11b1ac78f8ad9270c98 | 3,972 | java | Java | openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/TestEmbeddedCollection.java | simesi/openjpa | 503b8a2ee937737ae64688f2bb0f7d138811df70 | [
"Apache-2.0"
] | 104 | 2015-01-31T01:11:05.000Z | 2022-03-20T05:28:58.000Z | openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/TestEmbeddedCollection.java | simesi/openjpa | 503b8a2ee937737ae64688f2bb0f7d138811df70 | [
"Apache-2.0"
] | 56 | 2016-09-30T14:04:31.000Z | 2022-02-21T11:23:53.000Z | openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/datacache/TestEmbeddedCollection.java | simesi/openjpa | 503b8a2ee937737ae64688f2bb0f7d138811df70 | [
"Apache-2.0"
] | 127 | 2015-01-11T14:18:46.000Z | 2022-03-23T13:46:58.000Z | 33.661017 | 76 | 0.726838 | 997,645 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.persistence.datacache;
import java.util.List;
import javax.persistence.EntityManager;
import org.apache.openjpa.persistence.OpenJPAEntityManagerFactorySPI;
import org.apache.openjpa.persistence.OpenJPAPersistence;
import org.apache.openjpa.persistence.StoreCacheImpl;
import org.apache.openjpa.persistence.datacache.common.apps.EmbeddedEntity;
import org.apache.openjpa.persistence.datacache.common.apps.
EmbeddingOwnerEntity;
import org.apache.openjpa.persistence.test.SingleEMFTestCase;
/**
* Test removing members of embedded collection with active DataCache.
*
* Originally reported in
* <HREF="http://issues.apache.org/jira/browse/OPENJPA-625">OPENJPA-625</A>
*
* @author Pinaki Poddar
*
*/
public class TestEmbeddedCollection extends SingleEMFTestCase {
private static final int SIZE = 4;
/**
* Sets up EntityManagerFactory: with DataCache.
*/
@Override
public void setUp() throws Exception {
super.setUp("openjpa.jdbc.SynchronizeMappings", "buildSchema",
"openjpa.RuntimeUnenhancedClasses", "unsupported",
"openjpa.DataCache", "true", "openjpa.RemoteCommitProvider",
"sjvm", "openjpa.jdbc.UpdateManager", "constraint",
EmbeddingOwnerEntity.class,
EmbeddedEntity.class,
CLEAR_TABLES);
createData();
assertNotNull(emf);
assertNotNull(emf.getStoreCache());
assertTrue(isDataCacheActive(emf));
}
boolean isDataCacheActive(OpenJPAEntityManagerFactorySPI emf) {
return ((StoreCacheImpl) emf.getStoreCache()).getDelegate() != null
&& emf.getConfiguration().getDataCacheManagerInstance()
.getSystemDataCache() != null;
}
public void createData() {
EmbeddingOwnerEntity owner = new EmbeddingOwnerEntity();
for (int i = 0; i < SIZE; i++) {
EmbeddedEntity member = new EmbeddedEntity();
member.setMarker("Member-" + i);
owner.addMember(member);
}
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(owner);
em.getTransaction().commit();
Object id = OpenJPAPersistence.cast(em).getObjectId(owner);
em.clear();
EmbeddingOwnerEntity test = em.find(EmbeddingOwnerEntity.class, id);
assertNotNull(test);
List<EmbeddedEntity> members = test.getMembers();
assertNotNull(members);
assertEquals(SIZE, members.size());
for (int i = 0; i < SIZE; i++)
members.get(i).getMarker().equals("Member-" + i);
}
public void testRemoveMemberFromEmbeddedCollection() {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
List<EmbeddingOwnerEntity> result = em.createQuery(
"SELECT p FROM EmbeddingOwnerEntity p").getResultList();
assertNotNull(result);
assertFalse(result.isEmpty());
EmbeddingOwnerEntity owner = result.get(0);
Object id = owner.getId();
assertTrue(emf.getStoreCache().contains(EmbeddingOwnerEntity.class,
id));
List<EmbeddedEntity> members = owner.getMembers();
members.remove(0);
owner.removeMember(0);
owner.removeMember(members.get(0));
em.getTransaction().commit();
assertEquals(owner.getMembers().size(), SIZE-3);
}
}
|
92365f21babb25ae6f63c961b1afdefb3701dcc4 | 956 | java | Java | src/main/java/com/github/rami_sabbagh/codeforces/api/objects/Problem.java | Rami-Sabbagh/CodeforcesAPI | 12b11b6da6d06c01e040a2b60db0c4b5a64323cb | [
"MIT"
] | 1 | 2021-02-20T16:48:15.000Z | 2021-02-20T16:48:15.000Z | src/main/java/com/github/rami_sabbagh/codeforces/api/objects/Problem.java | Rami-Sabbagh/Codeforces-API | 12b11b6da6d06c01e040a2b60db0c4b5a64323cb | [
"MIT"
] | null | null | null | src/main/java/com/github/rami_sabbagh/codeforces/api/objects/Problem.java | Rami-Sabbagh/Codeforces-API | 12b11b6da6d06c01e040a2b60db0c4b5a64323cb | [
"MIT"
] | null | null | null | 19.916667 | 102 | 0.624477 | 997,646 | package com.github.rami_sabbagh.codeforces.api.objects;
import com.github.rami_sabbagh.codeforces.api.enums.ProblemType;
/**
* Represents a problem.
*/
@SuppressWarnings("unused")
public class Problem extends CFObject {
/**
* Can be absent. Id of the contest, containing the problem.
*/
public int contestId;
/**
* Can be absent. Short name of the problemset the problem belongs to.
*/
public String problemsetName;
/**
* Usually a letter of a letter, followed by a digit, that represent a problem index in a contest.
*/
public String index;
/**
* Localized.
*/
public String name;
public ProblemType type;
/**
* Can be absent. Maximum amount of points for the problem.
*/
public double points;
/**
* Can be absent. Problem rating (difficulty).
*/
public int rating;
/**
* Problem tags.
*/
public String[] tags;
}
|
923660061cc3bee6ed103a3d5950ccef038faef6 | 1,106 | java | Java | gulimall_coupon/src/main/java/com/wu/gulimall/gulimall_coupon/service/impl/CouponHistoryServiceImpl.java | DOCCA0/gulimall | 1ecf200119ba389c631f70d24ecd729388aee0ea | [
"Apache-2.0"
] | null | null | null | gulimall_coupon/src/main/java/com/wu/gulimall/gulimall_coupon/service/impl/CouponHistoryServiceImpl.java | DOCCA0/gulimall | 1ecf200119ba389c631f70d24ecd729388aee0ea | [
"Apache-2.0"
] | null | null | null | gulimall_coupon/src/main/java/com/wu/gulimall/gulimall_coupon/service/impl/CouponHistoryServiceImpl.java | DOCCA0/gulimall | 1ecf200119ba389c631f70d24ecd729388aee0ea | [
"Apache-2.0"
] | null | null | null | 38.137931 | 130 | 0.790235 | 997,647 | package com.wu.gulimall.gulimall_coupon.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.wu.gulimall.gulimall_common.common.utils.PageUtils;
import com.wu.gulimall.gulimall_common.common.utils.Query;
import com.wu.gulimall.gulimall_coupon.dao.CouponHistoryDao;
import com.wu.gulimall.gulimall_coupon.entity.CouponHistoryEntity;
import com.wu.gulimall.gulimall_coupon.service.CouponHistoryService;
@Service("couponHistoryService")
public class CouponHistoryServiceImpl extends ServiceImpl<CouponHistoryDao, CouponHistoryEntity> implements CouponHistoryService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<CouponHistoryEntity> page = this.page(
new Query<CouponHistoryEntity>().getPage(params),
new QueryWrapper<CouponHistoryEntity>()
);
return new PageUtils(page);
}
} |
9236602cc067fbdb8362144da589b0809c3574eb | 2,577 | java | Java | truman/src/main/java/com/diguage/truman/aop/AspectAnnotationTest.java | diguage/spring-framework | 4b6c9224aff6067f5a19c1ae329d562a0db1fb6b | [
"Apache-2.0"
] | 7 | 2015-01-06T09:01:44.000Z | 2021-09-21T09:41:15.000Z | truman/src/main/java/com/diguage/truman/aop/AspectAnnotationTest.java | diguage/spring-framework | 4b6c9224aff6067f5a19c1ae329d562a0db1fb6b | [
"Apache-2.0"
] | 4 | 2021-01-25T05:00:24.000Z | 2022-03-16T12:17:09.000Z | truman/src/main/java/com/diguage/truman/aop/AspectAnnotationTest.java | diguage/spring-framework | 4b6c9224aff6067f5a19c1ae329d562a0db1fb6b | [
"Apache-2.0"
] | 5 | 2015-01-06T03:35:38.000Z | 2021-04-21T02:30:24.000Z | 23.861111 | 72 | 0.740784 | 997,648 | package com.diguage.truman.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.*;
import org.springframework.core.type.AnnotationMetadata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author D瓜哥, https://www.diguage.com/
* @since 2021-07-18 23:40:42
*/
@Slf4j
public class AspectAnnotationTest {
@Test
public void test() {
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext();
context.register(Config.class);
context.refresh();
DiguageTask task = context.getBean(DiguageTask.class);
task.run();
}
@Configuration
@Import(AnnoImportSelector.class)
@EnableAspectJAutoProxy // 注意:这行必须加
public static class Config {
}
public static class AnnoImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata metadata) {
return new String[]{
DiguageTask.class.getName(),
AnnoTypeAspect.class.getName(),
AnnoMethodAspect.class.getName()
};
}
}
@AnnoTypeAnnotation
public static class DiguageTask {
@AnnoMethodAnnotation
public void run() {
log.info("Diguage.run executing...");
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AnnoMethodAnnotation {
}
@Aspect
public static class AnnoMethodAspect {
@Pointcut("@annotation(com.diguage.truman.aop." +
"AspectAnnotationTest.AnnoMethodAnnotation)")
public void annoMethod() {
}
@Around("annoMethod()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
try {
return joinPoint.proceed();
} finally {
log.info("AnnoMethodAspect.annoMethod executing...");
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AnnoTypeAnnotation {
}
@Aspect
public static class AnnoTypeAspect {
@Pointcut("@annotation(com.diguage.truman.aop." +
"AspectAnnotationTest.AnnoTypeAnnotation)")
public void annoType() {
}
/**
* 这里的代码没有执行到,说明对于 @annotation 注解来说,只支持方法注解。
*/
@Around("annoType()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
try {
return joinPoint.proceed();
} finally {
log.info("AnnoTypeAspect.annoType executing...");
}
}
}
}
|
923661a5ddeb4dd89b82a5808e67462be79f5dea | 228 | java | Java | sources/com/google/api/client/auth/oauth/OAuthCallbackUrl.java | tonioshikanlu/tubman-hack | 8277e47c058174ca4411965ed67d05d2aba1c7fc | [
"MIT"
] | 2 | 2021-03-20T07:33:30.000Z | 2021-06-29T18:50:21.000Z | sources/com/google/api/client/auth/oauth/OAuthCallbackUrl.java | tonioshikanlu/tubman-hack | 8277e47c058174ca4411965ed67d05d2aba1c7fc | [
"MIT"
] | null | null | null | sources/com/google/api/client/auth/oauth/OAuthCallbackUrl.java | tonioshikanlu/tubman-hack | 8277e47c058174ca4411965ed67d05d2aba1c7fc | [
"MIT"
] | 2 | 2021-03-20T15:56:20.000Z | 2021-03-21T02:06:29.000Z | 19 | 41 | 0.688596 | 997,649 | package com.google.api.client.auth.oauth;
import b.l.b.a.b.c;
import b.l.b.a.d.n;
public class OAuthCallbackUrl extends c {
@n("oauth_token")
public String token;
@n("oauth_verifier")
public String verifier;
}
|
92366358abfe473764f1a5344845e2096d26cab5 | 3,202 | java | Java | app/src/main/java/com/example/android/pets/PetCursorAdapter.java | shenron-cipher/Pets | 46dda1122ee08282c65b376fb74b32010127ecc3 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/pets/PetCursorAdapter.java | shenron-cipher/Pets | 46dda1122ee08282c65b376fb74b32010127ecc3 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/pets/PetCursorAdapter.java | shenron-cipher/Pets | 46dda1122ee08282c65b376fb74b32010127ecc3 | [
"Apache-2.0"
] | null | null | null | 39.530864 | 98 | 0.684884 | 997,650 | package com.example.android.pets;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.example.android.pets.data.PetContract;
import static android.R.attr.name;
/**
* {@link PetCursorAdapter} is an adapter for a list or grid view
* that uses a {@link Cursor} of pet data as its data source. This adapter knows
* how to create list items for each row of pet data in the {@link Cursor}.
*/
public class PetCursorAdapter extends CursorAdapter {
/**
* Constructs a new {@link PetCursorAdapter}.
*
* @param context The context
* @param c The cursor from which to get the data.
*/
public PetCursorAdapter(Context context, Cursor c) {
super(context, c, 0 /* flags */);
}
/**
* Makes a new blank list item view. No data is set (or bound) to the views yet.
*
* @param context app context
* @param cursor The cursor from which to get the data. The cursor is already
* moved to the correct position.
* @param parent The parent to which the new view is attached to
* @return the newly created list item view.
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item,parent, false);
}
/**
* This method binds the pet data (in the current row pointed to by cursor) to the given
* list item layout. For example, the name for the current pet can be set on the name TextView
* in the list item layout.
*
* @param view Existing view, returned earlier by newView() method
* @param context app context
* @param cursor The cursor from which to get the data. The cursor is already moved to the
* correct row.
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) view.findViewById(R.id.name);
TextView summaryTextView = (TextView) view.findViewById(R.id.summary);
// Find the columns of pet attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(PetContract.PetEntry.COLUMN_PET_NAME);
int breedColumnIndex = cursor.getColumnIndex(PetContract.PetEntry.COLUMN_PET_BREED);
// Read the pet attributes from the Cursor for the current pet
String petName = cursor.getString(nameColumnIndex);
String petBreed = cursor.getString(breedColumnIndex);
// If the pet breed is empty string or null, then use some default text
// that says "Unknown breed", so the TextView isn't blank.
if (TextUtils.isEmpty(petBreed)) {
petBreed = context.getString(R.string.unknown_breed);
}
// Update the TextViews with the attributes for the current pet
nameTextView.setText(petName);
summaryTextView.setText(petBreed);
}
} |
923664588e1e84436b65ddade124d938f06d52df | 784 | java | Java | winterwell.maths/src/com/winterwell/maths/stats/distributions/discrete/SingletonDistribution.java | rmsaab/open-code | 8758d61e15734c5d38b1d4509ef1d7b780ee9225 | [
"MIT"
] | 2 | 2016-12-13T15:12:41.000Z | 2017-05-04T08:00:23.000Z | winterwell.maths/src/com/winterwell/maths/stats/distributions/discrete/SingletonDistribution.java | rmsaab/open-code | 8758d61e15734c5d38b1d4509ef1d7b780ee9225 | [
"MIT"
] | 11 | 2017-06-09T17:16:42.000Z | 2021-03-10T13:59:57.000Z | winterwell.maths/src/com/winterwell/maths/stats/distributions/discrete/SingletonDistribution.java | rmsaab/open-code | 8758d61e15734c5d38b1d4509ef1d7b780ee9225 | [
"MIT"
] | 5 | 2017-06-09T11:27:23.000Z | 2022-02-25T22:47:57.000Z | 16.680851 | 76 | 0.692602 | 997,651 | package com.winterwell.maths.stats.distributions.discrete;
import java.util.Collections;
import java.util.Iterator;
/**
* Distribution with only one non-zero element.
*
* @author daniel
*
* @param <T>
*/
public final class SingletonDistribution<T> extends AFiniteDistribution<T> {
private final T v;
public SingletonDistribution(T v) {
this.v = v;
normalised = true;
}
@Override
public T getMostLikely() {
return v;
}
@Override
public Iterator<T> iterator() throws UnsupportedOperationException {
return Collections.singleton(v).iterator();
}
@Override
public double prob(T x) {
return v.equals(x) ? 1 : 0;
}
@Override
public int size() {
return 1;
}
@Override
public String toString() {
return "SingletonDistribution[" + v + "]";
}
}
|
9236645de070d5dc5583a0232c71bb1c1721a4ec | 326 | java | Java | src/main/java/ru/contentforge/formconstructor/form/element/validator/Validator.java | ContentForge/FormConstructor | 7c5b53845cefb83ebe50f8bf706d7f4777200e6e | [
"MIT"
] | 5 | 2021-07-24T04:38:10.000Z | 2021-09-08T12:09:11.000Z | src/main/java/ru/contentforge/formconstructor/form/element/validator/Validator.java | ContentForge/FormConstructor | 7c5b53845cefb83ebe50f8bf706d7f4777200e6e | [
"MIT"
] | null | null | null | src/main/java/ru/contentforge/formconstructor/form/element/validator/Validator.java | ContentForge/FormConstructor | 7c5b53845cefb83ebe50f8bf706d7f4777200e6e | [
"MIT"
] | null | null | null | 19.176471 | 63 | 0.726994 | 997,652 | package ru.contentforge.formconstructor.form.element.validator;
import lombok.Getter;
public abstract class Validator {
@Getter protected final String name;
@Getter protected boolean validated;
public Validator(String name){
this.name = name;
}
public abstract void validate(String input);
}
|
923664dbfa3c013f028bf8da091267b5d9cad3fe | 433 | java | Java | spring/spring-certification-spilca/lesson-14/src/main/java/com/laurentiuspilca/webscopes/services/RandomNameProvider.java | thomasrobertz/web-tutorials | ee1de584a383c9c10549bc49f22d4e6584255be0 | [
"MIT"
] | null | null | null | spring/spring-certification-spilca/lesson-14/src/main/java/com/laurentiuspilca/webscopes/services/RandomNameProvider.java | thomasrobertz/web-tutorials | ee1de584a383c9c10549bc49f22d4e6584255be0 | [
"MIT"
] | null | null | null | spring/spring-certification-spilca/lesson-14/src/main/java/com/laurentiuspilca/webscopes/services/RandomNameProvider.java | thomasrobertz/web-tutorials | ee1de584a383c9c10549bc49f22d4e6584255be0 | [
"MIT"
] | null | null | null | 36.083333 | 91 | 0.847575 | 997,653 | package com.laurentiuspilca.webscopes.services;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.INTERFACES)
public interface RandomNameProvider {
public String next();
}
|
923664e9ebbcbc9f6960a083fc7cb99cffb7e3c8 | 3,734 | java | Java | ql/src/java/org/apache/hadoop/hive/ql/io/SequenceFileInputFormatChecker.java | sho25/hive | 7a6a045c2a487bd200aeaded38497c843ec6a83c | [
"Apache-2.0"
] | null | null | null | ql/src/java/org/apache/hadoop/hive/ql/io/SequenceFileInputFormatChecker.java | sho25/hive | 7a6a045c2a487bd200aeaded38497c843ec6a83c | [
"Apache-2.0"
] | 3 | 2020-05-15T22:28:40.000Z | 2022-01-27T16:24:32.000Z | ql/src/java/org/apache/hadoop/hive/ql/io/SequenceFileInputFormatChecker.java | sho25/hive | 7a6a045c2a487bd200aeaded38497c843ec6a83c | [
"Apache-2.0"
] | null | null | null | 14.995984 | 813 | 0.787895 | 997,654 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|io
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|FileStatus
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|FileSystem
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|conf
operator|.
name|HiveConf
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|IOUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|SequenceFile
import|;
end_import
begin_comment
comment|/** * SequenceFileInputFormatChecker. * */
end_comment
begin_class
specifier|public
class|class
name|SequenceFileInputFormatChecker
implements|implements
name|InputFormatChecker
block|{
annotation|@
name|Override
specifier|public
name|boolean
name|validateInput
parameter_list|(
name|FileSystem
name|fs
parameter_list|,
name|HiveConf
name|conf
parameter_list|,
name|List
argument_list|<
name|FileStatus
argument_list|>
name|files
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
name|files
operator|.
name|size
argument_list|()
operator|<=
literal|0
condition|)
block|{
return|return
literal|false
return|;
block|}
for|for
control|(
name|int
name|fileId
init|=
literal|0
init|;
name|fileId
operator|<
name|files
operator|.
name|size
argument_list|()
condition|;
name|fileId
operator|++
control|)
block|{
name|SequenceFile
operator|.
name|Reader
name|reader
init|=
literal|null
decl_stmt|;
try|try
block|{
name|reader
operator|=
operator|new
name|SequenceFile
operator|.
name|Reader
argument_list|(
name|fs
argument_list|,
name|files
operator|.
name|get
argument_list|(
name|fileId
argument_list|)
operator|.
name|getPath
argument_list|()
argument_list|,
name|conf
argument_list|)
expr_stmt|;
name|reader
operator|.
name|close
argument_list|()
expr_stmt|;
name|reader
operator|=
literal|null
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
return|return
literal|false
return|;
block|}
finally|finally
block|{
name|IOUtils
operator|.
name|closeStream
argument_list|(
name|reader
argument_list|)
expr_stmt|;
block|}
block|}
return|return
literal|true
return|;
block|}
block|}
end_class
end_unit
|
92366552d5cb182362a22a66cf25cf2717cfbe6a | 1,685 | java | Java | src/main/java/org/onap/sdc/dcae/composition/model/Property.java | onap/archive-sdc-dcae-d-dt-be-property | 444dcb71f828985f96e0c425ce9ea470854866fb | [
"Apache-2.0"
] | null | null | null | src/main/java/org/onap/sdc/dcae/composition/model/Property.java | onap/archive-sdc-dcae-d-dt-be-property | 444dcb71f828985f96e0c425ce9ea470854866fb | [
"Apache-2.0"
] | null | null | null | src/main/java/org/onap/sdc/dcae/composition/model/Property.java | onap/archive-sdc-dcae-d-dt-be-property | 444dcb71f828985f96e0c425ce9ea470854866fb | [
"Apache-2.0"
] | null | null | null | 31.792453 | 83 | 0.5727 | 997,655 | /*-
* ============LICENSE_START=======================================================
* sdc-dcae-d-dt-be-property
* ================================================================================
* Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.sdc.dcae.composition.model;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Property {
@SerializedName("format")
@Expose
private List<Format> format = null;
@SerializedName("version")
@Expose
private List<Version> version = null;
public List<Format> getFormat() {
return format;
}
public void setFormat(List<Format> format) {
this.format = format;
}
public List<Version> getVersion() {
return version;
}
public void setVersion(List<Version> version) {
this.version = version;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.