hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
10743b03a058e9ef9d3e3c5aacac3406426a1016 | 6,857 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.tooling.ignore;
import com.google.auto.service.AutoService;
import io.opentelemetry.instrumentation.api.config.Config;
import io.opentelemetry.javaagent.bootstrap.AgentClassLoader;
import io.opentelemetry.javaagent.extension.ignore.IgnoredTypesBuilder;
import io.opentelemetry.javaagent.extension.ignore.IgnoredTypesConfigurer;
import io.opentelemetry.javaagent.tooling.ExtensionClassLoader;
@AutoService(IgnoredTypesConfigurer.class)
public class GlobalIgnoredTypesConfigurer implements IgnoredTypesConfigurer {
@Override
public void configure(Config config, IgnoredTypesBuilder builder) {
configureIgnoredTypes(builder);
configureIgnoredClassLoaders(builder);
configureIgnoredTasks(builder);
}
private static void configureIgnoredTypes(IgnoredTypesBuilder builder) {
builder
.ignoreClass("org.gradle.")
.ignoreClass("net.bytebuddy.")
.ignoreClass("jdk.")
.ignoreClass("org.aspectj.")
.ignoreClass("datadog.")
.ignoreClass("com.intellij.rt.debugger.")
.ignoreClass("com.p6spy.")
.ignoreClass("com.dynatrace.")
.ignoreClass("com.jloadtrace.")
.ignoreClass("com.appdynamics.")
.ignoreClass("com.newrelic.agent.")
.ignoreClass("com.newrelic.api.agent.")
.ignoreClass("com.nr.agent.")
.ignoreClass("com.singularity.")
.ignoreClass("com.jinspired.")
.ignoreClass("org.jinspired.");
// allow JDK HttpClient
builder.allowClass("jdk.internal.net.http.");
// groovy
builder
.ignoreClass("org.groovy.")
.ignoreClass("org.apache.groovy.")
.ignoreClass("org.codehaus.groovy.")
// We seem to instrument some classes in runtime
.allowClass("org.codehaus.groovy.runtime.");
// clojure
builder.ignoreClass("clojure.").ignoreClass("$fn__");
// all classes in the AgentClassLoader are ignored separately
// this is used to ignore agent classes that are in the bootstrap class loader
// the reason not to use "io.opentelemetry.javaagent." is so that javaagent instrumentation
// tests under "io.opentelemetry.javaagent." will still be instrumented
builder.ignoreClass("io.opentelemetry.javaagent.bootstrap.");
builder.ignoreClass("io.opentelemetry.javaagent.instrumentation.api.");
builder.ignoreClass("io.opentelemetry.javaagent.shaded.");
builder.ignoreClass("io.opentelemetry.javaagent.slf4j.");
builder
.ignoreClass("java.")
.allowClass("java.net.URL")
.allowClass("java.net.HttpURLConnection")
.allowClass("java.net.URLClassLoader")
.allowClass("java.rmi.")
.allowClass("java.util.concurrent.")
.allowClass("java.lang.reflect.Proxy")
.allowClass("java.lang.ClassLoader")
.allowClass("java.lang.invoke.InnerClassLambdaMetafactory")
// Concurrent instrumentation modifies the structure of
// Cleaner class incompatibly with java9+ modules.
// Working around until a long-term fix for modules can be
// put in place.
.allowClass("java.util.logging.")
.ignoreClass("java.util.logging.LogManager$Cleaner");
builder
.ignoreClass("com.sun.")
.allowClass("com.sun.messaging.")
.allowClass("com.sun.jersey.api.client")
.allowClass("com.sun.appserv")
.allowClass("com.sun.faces")
.allowClass("com.sun.xml.ws");
builder
.ignoreClass("sun.")
.allowClass("sun.net.www.protocol.")
.allowClass("sun.rmi.server")
.allowClass("sun.rmi.transport")
.allowClass("sun.net.www.http.HttpClient");
builder.ignoreClass("org.slf4j.").allowClass("org.slf4j.MDC");
builder
.ignoreClass("org.springframework.core.$Proxy")
// Tapestry Proxy, check only specific class that we know would be instrumented since there
// is no common prefix for its proxies other than "$". ByteBuddy fails to instrument this
// proxy, and as there is no reason why it should be instrumented anyway, exclude it.
.ignoreClass("$HttpServletRequest_");
}
private static void configureIgnoredClassLoaders(IgnoredTypesBuilder builder) {
builder
.ignoreClassLoader("org.codehaus.groovy.runtime.callsite.CallSiteClassLoader")
.ignoreClassLoader("sun.reflect.DelegatingClassLoader")
.ignoreClassLoader("jdk.internal.reflect.DelegatingClassLoader")
.ignoreClassLoader("clojure.lang.DynamicClassLoader")
.ignoreClassLoader("org.apache.cxf.common.util.ASMHelper$TypeHelperClassLoader")
.ignoreClassLoader("sun.misc.Launcher$ExtClassLoader")
.ignoreClassLoader(AgentClassLoader.class.getName())
.ignoreClassLoader(ExtensionClassLoader.class.getName());
builder
.ignoreClassLoader("datadog.")
.ignoreClassLoader("com.dynatrace.")
.ignoreClassLoader("com.appdynamics.")
.ignoreClassLoader("com.newrelic.agent.")
.ignoreClassLoader("com.newrelic.api.agent.")
.ignoreClassLoader("com.nr.agent.");
}
private static void configureIgnoredTasks(IgnoredTypesBuilder builder) {
// ForkJoinPool threads are initialized lazily and continue to handle tasks similar to an
// event loop. They should not have context propagated to the base of the thread, tasks
// themselves will have it through other means.
builder.ignoreTaskClass("java.util.concurrent.ForkJoinWorkerThread");
// ThreadPoolExecutor worker threads may be initialized lazily and manage interruption of
// other threads. The actual tasks being run on those threads will propagate context but
// we should not propagate onto this management thread.
builder.ignoreTaskClass("java.util.concurrent.ThreadPoolExecutor$Worker");
// TODO Workaround for
// https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/787
builder.ignoreTaskClass("org.apache.tomcat.util.net.NioEndpoint$SocketProcessor");
// HttpConnection implements Runnable. When async request is completed HttpConnection
// may be sent to process next request while context from previous request hasn't been
// cleared yet.
builder.ignoreTaskClass("org.eclipse.jetty.server.HttpConnection");
// Avoid context leak on jetty. Runnable submitted from SelectChannelEndPoint is used to
// process a new request which should not have context from them current request.
builder.ignoreTaskClass("org.eclipse.jetty.io.nio.SelectChannelEndPoint$");
// Don't instrument the executor's own runnables. These runnables may never return until
// netty shuts down.
builder.ignoreTaskClass("io.netty.util.concurrent.SingleThreadEventExecutor$");
}
}
| 43.398734 | 99 | 0.71314 |
1c9e9b061fc1e55caef5e1f00dc6799845731df6 | 1,306 | package io.github.squid233.javaprogrammereditor;
import io.github.squid233.javaprogrammereditor.setting.Settings;
import javax.swing.*;
/**
* @author squid233
*/
public class Main {
public static Frame frame;
public static final String VERSION = "0.2.0-pre-alpha";
public static final String UPDATE_DATE = "2020-8-8";
public static final String BUILD_VERSION = "build.2";
public static void main(String[] args) {
Settings.load();
try {
if (Settings.getSetting(Settings.PROGRAM_LOOK_AND_FEEL).equals(Settings.PROGRAM_LOOK_AND_FEEL_DEFAULT)) {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} else {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if (info.getName().equals(Settings.getSetting(Settings.PROGRAM_LOOK_AND_FEEL))) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
System.out.println("Cannot set look and feel cause by: " + e);
}
frame = new Frame();
}
}
| 36.277778 | 128 | 0.632466 |
dfdaece9cb83a55b705f5410a5a58a73324fc3ab | 1,944 | //Leetcode problem 217 Contains Duplicate
//Leetcode problem 219 Contains Duplicate II
//Leetcode problem 220 Contains Duplicate III
//Solution written by Xuqiang Fang on 22 March 2018
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
class Solution{
public boolean containsDuplicate(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++){
if(!map.containsKey(nums[i])){
map.put(nums[i],1);
}else{
return true;
}
}
return false;
}
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++){
if(!map.containsKey(nums[i])){
map.put(nums[i], i);
}else{
if(i - map.get(nums[i]) <= k){
System.out.println(nums[i] + "key" + i+ map.get(nums[i]));
return true;
}else{
map.replace(nums[i],i);
}
}
}
return false;
}
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if(t < 0) return false;
Map<Long, Long> dict = new HashMap<>();
long w = (long)t + 1;
for(int i=0; i<nums.length; ++i){
long m = getID(nums[i], w);
if (dict.containsKey(m)) return true;
else if(dict.containsKey(m-1) && Math.abs(nums[i]-dict.get(m-1))<w) return true;
else if(dict.containsKey(m+1) && Math.abs(nums[i]-dict.get(m+1))<w) return true;
dict.put(m, (long)nums[i]);
if(i >= k) dict.remove(getID(nums[i-k], w));
}
return false;
}
private long getID(long i, long w){
return i < 0 ? (i+1) / w -1 : i / w;
}
}
public class ContainDuplicate{
public static void main(String[] args){
Solution s = new Solution();
int[] nums = {1,6,2,34,5,6};
int[] nums2 = {1,2,3,4,1,3,2,1};
System.out.println(s.containsDuplicate(nums));
System.out.println(s.containsNearbyAlmostDuplicate(nums2,2,3));
}
}
| 29.907692 | 92 | 0.598765 |
9b3e7c8b02de279f593bc27b3c74d56d81deec5d | 762 | package ru.atoroschin;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import ru.atoroschin.auth.AuthService;
public class AuthHandler extends ChannelInboundHandlerAdapter {
private final AuthService authService;
public AuthHandler(AuthService authService) {
this.authService = authService;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
if (buf.readableBytes() > 0) {
byte b = buf.readByte();
CommandsAuth command = CommandsAuth.getCommand(b);
command.receiveAndSend(ctx, buf, authService, null);
}
}
}
| 29.307692 | 85 | 0.707349 |
7c3996903f5edaf0d55db4337897a73af83b5b78 | 364 | /**
* Copyright 2015, Xiaomi.
* All rights reserved.
* Author: yongxing@xiaomi.com
*/
package com.xiaomi.infra.galaxy.talos.consumer;
public class TalosMessageReaderFactory implements MessageReaderFactory {
@Override
public MessageReader createMessageReader(TalosConsumerConfig consumerConfig) {
return new TalosMessageReader(consumerConfig);
}
}
| 22.75 | 80 | 0.782967 |
db05c421cc468861485887c255d32a092274fd01 | 1,588 | /*
Leetcode Problem 198: House Robber
https://leetcode.com/problems/house-robber/description/
You are a professional robber planning to rob houses along a street. Each house has a certain amount
of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses
have security system connected and it will automatically contact the police if two adjacent houses
were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine
the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
*/
public class HouseRobber {
public static int rob(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int n = nums.length;
if (n == 1) return nums[0];
int[] dp = new int[n];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i-1], nums[i]+dp[i-2]);
}
return dp[n-1];
}
public static void main(String[] args) {
int[] arr1 = new int[] {1,2,3,1};
int[] arr2 = new int[] {2,7,9,3,1};
System.out.println("rob[1,2,3,1] = " + rob(arr1)); // 4
System.out.println("rob[2,7,9,3,1] = " + rob(arr2)); // 12
}
}
| 29.962264 | 100 | 0.639798 |
ef2e2311305c40258ac66ae75164e27d93515796 | 364 | package iitb.Segment;
import iitb.CRF.*;
/**
*
* @author Sunita Sarawagi
*
*/
public interface TrainData extends DataIter {
int size(); // number of training records
void startScan(); // start scanning the training data
boolean hasMoreRecords();
public TrainRecord nextRecord();
boolean hasNext();
public DataSequence next();
};
| 20.222222 | 57 | 0.673077 |
d37252d9d5ec48e624473dba42ae22f2c51a395f | 1,284 | package ex;
import java.util.Scanner;
/*
* Topic: 輸入所使用的度數,換算夏月及非夏月之電費金額。
* Date: 2016/12/05
* Author: 105021062 鄭雅韵
*/
public class ex02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn=new Scanner(System.in);
float n=scn.nextInt();
float a=0;
float b=0;
if(n<=120){
a=(float) (n*2.10);
b=(float)(n*2.10);
System.out.println(a);
System.out.println(b);
}else if(n>120 && n<=330){
a=(float)((120*2.10)+((n-120)*3.02));
b=(float)((120*2.10)+((n-120)*2.68));
System.out.println(a);
System.out.println(b);
}else if(n>330 && n<=500){
a=(float)((120*2.10)+((330-120)*3.02)+((n-330)*4.39));
b=(float)((120*2.10)+((330-120)*2.68)+((n-330)*3.61));
System.out.println(a);
System.out.println(b);
}else if(n>500 && n<=700){
a=(float)((120*2.10)+((330-120)*3.02)+((500-330)*4.39)+((n-500)*4.97));
b=(float)((120*2.10)+((330-120)*2.68)+((500-330)*3.61)+((n-500)*4.01));
System.out.println(a);
System.out.println(b);
}else if(n>=701){
a=(float)((120*2.10)+((330-120)*3.02)+((500-330)*4.39)+((700-500)*4.97)+((n-700)*5.63));
b=(float)((120*2.10)+((330-120)*2.68)+((500-330)*3.61)+((700-500)*4.01)+((n-700)*4.50));
System.out.println(a);
System.out.println(b);
}
}
}
| 27.319149 | 91 | 0.563863 |
05a66b67654863767a740076839656b66630abdb | 5,808 | package com.google.android.gms.vision.barcode;
import android.graphics.Point;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.safeparcel.zza;
import com.google.android.gms.vision.barcode.Barcode.CalendarEvent;
import com.google.android.gms.vision.barcode.Barcode.ContactInfo;
import com.google.android.gms.vision.barcode.Barcode.DriverLicense;
import com.google.android.gms.vision.barcode.Barcode.Email;
import com.google.android.gms.vision.barcode.Barcode.GeoPoint;
import com.google.android.gms.vision.barcode.Barcode.Phone;
import com.google.android.gms.vision.barcode.Barcode.Sms;
import com.google.android.gms.vision.barcode.Barcode.UrlBookmark;
import com.google.android.gms.vision.barcode.Barcode.WiFi;
public class zzb implements Creator<Barcode> {
static void zza(Barcode barcode, Parcel parcel, int i) {
int zzav = com.google.android.gms.common.internal.safeparcel.zzb.zzav(parcel);
com.google.android.gms.common.internal.safeparcel.zzb.zzc(parcel, 1, barcode.versionCode);
com.google.android.gms.common.internal.safeparcel.zzb.zzc(parcel, 2, barcode.format);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 3, barcode.rawValue, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 4, barcode.displayValue, false);
com.google.android.gms.common.internal.safeparcel.zzb.zzc(parcel, 5, barcode.valueFormat);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 6, barcode.cornerPoints, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 7, barcode.email, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 8, barcode.phone, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 9, barcode.sms, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 10, barcode.wifi, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 11, barcode.url, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 12, barcode.geoPoint, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 13, barcode.calendarEvent, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 14, barcode.contactInfo, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zza(parcel, 15, barcode.driverLicense, i, false);
com.google.android.gms.common.internal.safeparcel.zzb.zzI(parcel, zzav);
}
public /* synthetic */ Object createFromParcel(Parcel x0) {
return zzgK(x0);
}
public /* synthetic */ Object[] newArray(int x0) {
return zzkd(x0);
}
public Barcode zzgK(Parcel parcel) {
int zzau = zza.zzau(parcel);
int i = 0;
int i2 = 0;
String str = null;
String str2 = null;
int i3 = 0;
Point[] pointArr = null;
Email email = null;
Phone phone = null;
Sms sms = null;
WiFi wiFi = null;
UrlBookmark urlBookmark = null;
GeoPoint geoPoint = null;
CalendarEvent calendarEvent = null;
ContactInfo contactInfo = null;
DriverLicense driverLicense = null;
while (parcel.dataPosition() < zzau) {
int zzat = zza.zzat(parcel);
switch (zza.zzcc(zzat)) {
case 1:
i = zza.zzg(parcel, zzat);
break;
case 2:
i2 = zza.zzg(parcel, zzat);
break;
case 3:
str = zza.zzp(parcel, zzat);
break;
case 4:
str2 = zza.zzp(parcel, zzat);
break;
case 5:
i3 = zza.zzg(parcel, zzat);
break;
case 6:
pointArr = (Point[]) zza.zzb(parcel, zzat, Point.CREATOR);
break;
case 7:
email = (Email) zza.zza(parcel, zzat, Email.CREATOR);
break;
case 8:
phone = (Phone) zza.zza(parcel, zzat, Phone.CREATOR);
break;
case 9:
sms = (Sms) zza.zza(parcel, zzat, Sms.CREATOR);
break;
case 10:
wiFi = (WiFi) zza.zza(parcel, zzat, WiFi.CREATOR);
break;
case 11:
urlBookmark = (UrlBookmark) zza.zza(parcel, zzat, UrlBookmark.CREATOR);
break;
case 12:
geoPoint = (GeoPoint) zza.zza(parcel, zzat, GeoPoint.CREATOR);
break;
case 13:
calendarEvent = (CalendarEvent) zza.zza(parcel, zzat, CalendarEvent.CREATOR);
break;
case 14:
contactInfo = (ContactInfo) zza.zza(parcel, zzat, (Creator) ContactInfo.CREATOR);
break;
case 15:
driverLicense = (DriverLicense) zza.zza(parcel, zzat, (Creator) DriverLicense.CREATOR);
break;
default:
zza.zzb(parcel, zzat);
break;
}
}
if (parcel.dataPosition() == zzau) {
return new Barcode(i, i2, str, str2, i3, pointArr, email, phone, sms, wiFi, urlBookmark, geoPoint, calendarEvent, contactInfo, driverLicense);
}
throw new zza.zza("Overread allowed size end=" + zzau, parcel);
}
public Barcode[] zzkd(int i) {
return new Barcode[i];
}
}
| 46.095238 | 154 | 0.590565 |
7f8c4af45eacd510a4c31f69128fd12eda7fd540 | 368 | package code.madhan.sfmovietour.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import code.madhan.sfmovietour.model.Movie;
@Repository
public interface MovieRepository extends PagingAndSortingRepository<Movie, String>, CustomMovieRepository{
Movie findById(String id);
}
| 24.533333 | 107 | 0.839674 |
bef0d5f7c80f5a4e3c98717166442743565b754b | 1,378 | package com.alibaba.smart.framework.engine.smart.parser;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;
import com.alibaba.smart.framework.engine.extension.annoation.ExtensionBinding;
import com.alibaba.smart.framework.engine.extension.constant.ExtensionConstant;
import com.alibaba.smart.framework.engine.smart.Property;
import com.alibaba.smart.framework.engine.xml.parser.AbstractElementParser;
import com.alibaba.smart.framework.engine.xml.parser.ParseContext;
import com.alibaba.smart.framework.engine.xml.util.XmlParseUtil;
import java.util.List;
@ExtensionBinding(group = ExtensionConstant.ELEMENT_PARSER, bindKey = Property.class)
public class PropertyParser extends AbstractElementParser<Property> {
@Override
protected Property parseModel(XMLStreamReader reader, ParseContext context) {
Property property = new Property();
property.setType(XmlParseUtil.getString(reader, "type"));
property.setName(XmlParseUtil.getString(reader, "name"));
property.setValue(XmlParseUtil.getString(reader, "value"));
return property;
}
@Override
public QName getQname() {
return null;
}
@Override
public List<QName> getQnames() {
return Property.qtypes;
}
@Override
public Class<Property> getModelType() {
return Property.class;
}
}
| 29.319149 | 85 | 0.748911 |
b66c05a868283417ea3b7ea9ab99f1216a50026b | 7,966 | /**
* Copyright 2017 ZuInnoTe (Jörn Franke) <zuinnote@gmail.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 org.zuinnote.hadoop.ethereum.format.mapred;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.Seekable;
import org.apache.hadoop.io.compress.CodecPool;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.io.compress.Decompressor;
import org.apache.hadoop.io.compress.SplitCompressionInputStream;
import org.apache.hadoop.io.compress.SplittableCompressionCodec;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.zuinnote.hadoop.ethereum.format.common.EthereumBlockReader;
/**
*
*/
public abstract class AbstractEthereumRecordReader <K,V> implements RecordReader<K,V> {
public static final String CONF_BUFFERSIZE=org.zuinnote.hadoop.ethereum.format.mapreduce.AbstractEthereumRecordReader.CONF_BUFFERSIZE;
public static final String CONF_MAXBLOCKSIZE= org.zuinnote.hadoop.ethereum.format.mapreduce.AbstractEthereumRecordReader.CONF_MAXBLOCKSIZE;
public static final String CONF_USEDIRECTBUFFER= org.zuinnote.hadoop.ethereum.format.mapreduce.AbstractEthereumRecordReader.CONF_USEDIRECTBUFFER;
public static final int DEFAULT_BUFFERSIZE= org.zuinnote.hadoop.ethereum.format.mapreduce.AbstractEthereumRecordReader.DEFAULT_BUFFERSIZE;
public static final int DEFAULT_MAXSIZE_ETHEREUMBLOCK= org.zuinnote.hadoop.ethereum.format.mapreduce.AbstractEthereumRecordReader.DEFAULT_MAXSIZE_ETHEREUMBLOCK;
public static final boolean DEFAULT_USEDIRECTBUFFER= org.zuinnote.hadoop.ethereum.format.mapreduce.AbstractEthereumRecordReader.DEFAULT_USEDIRECTBUFFER;
private static final Log LOG = LogFactory.getLog(AbstractEthereumRecordReader.class.getName());
private int bufferSize=0;
private int maxSizeEthereumBlock=0;
private boolean useDirectBuffer=false;
private CompressionCodec codec;
private Decompressor decompressor;
private Reporter reporter;
private Configuration conf;
private long start;
private long end;
private final Seekable filePosition;
private FSDataInputStream fileIn;
private EthereumBlockReader ebr;
/**
* Creates an Abstract Record Reader for Ethereum blocks
* @param split Split to use (assumed to be a file split)
* @param job Configuration:
* io.file.buffer.size: Size of in-memory specified in the given Configuration. If io.file.buffer.size is not specified the default buffersize will be used. Furthermore, one may specify hadoopcryptoledger.ethereumblockinputformat.maxblocksize, which defines the maximum size a Ethereum block may have. By default it is 1M). If you want to experiment with performance using DirectByteBuffer instead of HeapByteBuffer you can use "hadoopcryptoledeger.ethereumblockinputformat.usedirectbuffer" (default: false). Note that it might have some unwanted consequences such as circumwenting Yarn memory management. The option is experimental and might be removed in future versions.
* @param reporter Reporter
*
*
* @throws java.io.IOException in case of errors reading from the filestream provided by Hadoop
*
*/
public AbstractEthereumRecordReader(FileSplit split,JobConf job, Reporter reporter) throws IOException {
LOG.debug("Reading configuration");
// parse configuration
this.reporter=reporter;
this.conf=job;
this.maxSizeEthereumBlock=conf.getInt(AbstractEthereumRecordReader.CONF_MAXBLOCKSIZE,AbstractEthereumRecordReader.DEFAULT_MAXSIZE_ETHEREUMBLOCK);
this.bufferSize=conf.getInt(AbstractEthereumRecordReader.CONF_BUFFERSIZE,AbstractEthereumRecordReader.DEFAULT_BUFFERSIZE);
this.useDirectBuffer=conf.getBoolean(AbstractEthereumRecordReader.CONF_USEDIRECTBUFFER,AbstractEthereumRecordReader.DEFAULT_USEDIRECTBUFFER);
// Initialize start and end of split
start = split.getStart();
end = start + split.getLength();
final Path file = split.getPath();
codec = new CompressionCodecFactory(job).getCodec(file);
final FileSystem fs = file.getFileSystem(job);
fileIn = fs.open(file);
// open stream
if (isCompressedInput()) { // decompress
LOG.debug("Decompressing file");
decompressor = CodecPool.getDecompressor(codec);
if (codec instanceof SplittableCompressionCodec) {
LOG.debug("SplittableCompressionCodec");
final SplitCompressionInputStream cIn =((SplittableCompressionCodec)codec).createInputStream(fileIn, decompressor, start, end,SplittableCompressionCodec.READ_MODE.CONTINUOUS);
ebr = new EthereumBlockReader(cIn, this.maxSizeEthereumBlock,this.bufferSize,this.useDirectBuffer);
start = cIn.getAdjustedStart();
end = cIn.getAdjustedEnd();
filePosition = cIn; // take pos from compressed stream
} else {
LOG.debug("Not-splitable compression codec");
ebr = new EthereumBlockReader(codec.createInputStream(fileIn,decompressor), this.maxSizeEthereumBlock,this.bufferSize,this.useDirectBuffer);
filePosition = fileIn;
}
} else {
LOG.debug("Processing file without compression");
fileIn.seek(start);
ebr = new EthereumBlockReader(fileIn, this.maxSizeEthereumBlock,this.bufferSize,this.useDirectBuffer);
filePosition = fileIn;
}
// initialize reader
this.reporter.setStatus("Ready to read");
}
/**
* Get the current file position in a compressed or uncompressed file.
*
* @return file position
*
* @throws java.io.IOException in case of errors reading from the filestream provided by Hadoop
*
*/
public long getFilePosition() throws IOException {
return filePosition.getPos();
}
/**
* Get the end of file
*
* @return end of file position
*
*/
public long getEnd() {
return end;
}
/**
* Get the current Block Reader
*
* @return end of file position
*
*/
public EthereumBlockReader getEbr() {
return this.ebr;
}
/*
* Returns how much of the file has been processed in terms of bytes
*
* @return progress percentage
*
* @throws java.io.IOException in case of errors reading from the filestream provided by Hadoop
*
*/
@Override
public synchronized float getProgress() throws IOException {
if (start == end) {
return 0.0f;
} else {
return Math.min(1.0f, (getFilePosition() - start) / (float)(end - start));
}
}
/*
* Determines if the input is compressed or not
*
* @return true if compressed, false if not
*/
private boolean isCompressedInput() {
return codec != null;
}
/*
* Get current position in the stream
*
* @return position
*
* @throws java.io.IOException in case of errors reading from the filestream provided by Hadoop
*
*/
@Override
public synchronized long getPos() throws IOException {
return filePosition.getPos();
}
/*
* Clean up InputStream and Decompressor after use
*
*
* @throws java.io.IOException in case of errors reading from the filestream provided by Hadoop
*
*/
@Override
public synchronized void close() throws IOException {
try {
if (ebr != null) {
ebr.close();
}
} finally {
if (decompressor != null) {
CodecPool.returnDecompressor(decompressor);
decompressor = null;
}
}
}
}
| 35.721973 | 675 | 0.774793 |
d308ec01d8489e64459fcbe383df7214b90c85fb | 4,324 | package cn.newcapec.function.platform.dao;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import cn.newcapec.framework.core.dao.hibernate.HibernateEntityDao;
import cn.newcapec.framework.core.utils.pagesUtils.Page;
import cn.newcapec.function.platform.model.Role;
import cn.newcapec.function.platform.model.RoleGroup;
/**
*
* @Description: 角色组实体类
* @author gaochongfei
* @date 2014-4-4 下午04:00:50
* @version V1.0
*/
@SuppressWarnings("all")
@Repository("roleGroupDAO")
public class RoleGroupDAO extends HibernateEntityDao {
@Override
protected Class getReferenceClass() {
return RoleGroup.class;
}
/**
*
* @Title: queryRoles --
* @Description: 查询所有角色
* @param @param params
* @param @param orderby
* @param @return 设定文件
* @return Page 返回类型
* @throws
*/
public List<Map<String, Object>> queryRoleGroups(
Map<String, Object> params, LinkedHashMap<String, String> orderby) {
/* 参数集合类 */
List<Object> param = new ArrayList<Object>();
StringBuffer sb = new StringBuffer(
" select a.groupname, a.id ,a.groupstate,count(t.id) empnum");
sb.append(" from base_role_group a ");
sb.append(" left join BASE_user t ");
sb.append(" on a.id = t.roleid ");
sb.append(" and a.customerunitcode=? ");
sb.append(" and t.roletype = 1 ");
sb.append(" group by a.groupstate,a.id,a.groupname");
// orderby.put("t.create_datetime", "desc");
return this.sqlQueryForList(sb.toString(),
new Object[] { params.get("customerunitcode").toString() },
null);
}
public Page queryUserRoles(Map<String, Object> params,
LinkedHashMap<String, String> orderby) {
/* 参数集合类 */
List<Object> param = new ArrayList<Object>();
StringBuffer sb = new StringBuffer(
"select t1.name role_name ,t1.id role_id, "
+ "from t_role t1,t_user_role t2 where 1=1 and t1.id=t2.role_id and t2.user_id = t3.id ");
if (params.containsKey("name")
&& StringUtils.isNotBlank(params.get("name").toString())) {
sb.append(" and t.name=:name ");
param.add(params.get("name"));
}
return this.sqlQueryForPage(sb.toString(), param.toArray(), orderby);
}
public Role findRoleByName(String name) {
String hql = "select r from Role r where r.roleName=?";
Role role = (Role) this.findForObject(hql.toString(),
new Object[] { name });
return role;
}
public void deleteRole(String[] ids) {
if (null != ids && ids.length > 0) {
StringBuffer sb = new StringBuffer(
"delete from base_role where 1=1");
StringBuffer roleids = new StringBuffer();
for (int i = 0; i < ids.length; i++) {
roleids.append(ids[i]).append(",");
}
roleids.deleteCharAt(roleids.length() - 1);
sb.append(" and id in (" + roleids.toString() + ")");
getSession().createSQLQuery(sb.toString()).executeUpdate();
}
}
/**
* 获取角色信息根据客户code ---
*
* @param userid
* @return
*/
public Page queryRoleGroupByCustomerCode(Map<String, Object> params,
LinkedHashMap<String, String> orderby) {
/* 参数集合类 */
List<Object> param = new ArrayList<Object>();
StringBuffer sb = new StringBuffer(
"select t.* from BASE_ROLE_GROUP t where 1 = 1 and t.customerunitcode = ?");
return this.sqlQueryForPage(sb.toString(),
new Object[] { params.get("customerunitcode") }, orderby);
}
/**
* 查询角色组所有的角色 --
*
* @return
*/
public List<Map<String, Object>> queryByRoleGroupidId(String rolegroupid) {
String sql = "select distinct dr.role_id from BASE_ROLE dr where dr.roleid in "
+ "(select du.depatement_id from t_department_user du,t_user u ,t_department d "
+ " where du.depatement_id=d.id and du.user_id=u.id and du.user_id=?) ";
return sqlQueryForList(sql, new Object[] { rolegroupid }, null);
}
/**
*
* @Description: TODO
* @param @param key
* @param @return
* @return Role
* @throws
*/
public RoleGroup get(java.io.Serializable key) {
return (RoleGroup) get(getReferenceClass(), key);
}
/**
*
* @Description: 删除
* @param @param id
* @return void
* @throws
*/
public void delete(java.io.Serializable id) {
String sql = "delete from base_role_group where id=?";
getSession().createSQLQuery(sql).setParameter(0, id).executeUpdate();
}
}
| 28.826667 | 97 | 0.678538 |
ffd5d0ac5edcffbb8da7d3134af6fe22ddcbc2db | 5,421 | /*
* Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.map.impl.querycache;
import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.QueryCacheConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import com.hazelcast.map.QueryCache;
import com.hazelcast.query.Predicates;
import com.hazelcast.spi.properties.ClusterProperty;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static com.hazelcast.map.impl.querycache.AbstractQueryCacheTestSupport.getMap;
import static org.junit.Assert.assertEquals;
/**
* This test does not test an actual event arrival guarantee between the subscriber and publisher.
* The guarantee should be deemed in the context of {@link QueryCache} design.
* Because the design relies on a fire&forget eventing system.
* So this test should be thought under query-cache-context-guarantees and it is fragile.
*/
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class QueryCacheGuaranteesTest extends HazelcastTestSupport {
@Test
public void continuesToReceiveEvents_afterNodeJoins() {
String mapName = randomString();
String queryCacheName = randomString();
TestHazelcastInstanceFactory instanceFactory = createHazelcastInstanceFactory(3);
Config config = new Config();
config.setProperty(ClusterProperty.PARTITION_COUNT.getName(), "271");
QueryCacheConfig queryCacheConfig = new QueryCacheConfig(queryCacheName);
queryCacheConfig.setBatchSize(100);
queryCacheConfig.setDelaySeconds(3);
MapConfig mapConfig = config.getMapConfig(mapName);
mapConfig.addQueryCacheConfig(queryCacheConfig);
HazelcastInstance node = instanceFactory.newHazelcastInstance(config);
IMap<Integer, Integer> map = getMap(node, mapName);
final QueryCache<Integer, Integer> queryCache = map.getQueryCache(queryCacheName, Predicates.sql("this > 20"), true);
for (int i = 0; i < 30; i++) {
map.put(i, i);
}
HazelcastInstance node2 = instanceFactory.newHazelcastInstance(config);
IMap<Integer, Integer> map2 = node2.getMap(mapName);
for (int i = 100; i < 120; i++) {
map2.put(i, i);
}
HazelcastInstance node3 = instanceFactory.newHazelcastInstance(config);
IMap<Integer, Integer> map3 = node3.getMap(mapName);
for (int i = 150; i < 157; i++) {
map3.put(i, i);
}
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(36, queryCache.size());
}
});
}
@Test
public void continuesToReceiveEvents_afterNodeShutdown() {
String mapName = randomString();
String queryCacheName = randomString();
TestHazelcastInstanceFactory instanceFactory = createHazelcastInstanceFactory(3);
Config config = new Config();
QueryCacheConfig queryCacheConfig = new QueryCacheConfig(queryCacheName);
queryCacheConfig.setBatchSize(100);
queryCacheConfig.setDelaySeconds(6);
MapConfig mapConfig = config.getMapConfig(mapName);
mapConfig.addQueryCacheConfig(queryCacheConfig);
HazelcastInstance node = instanceFactory.newHazelcastInstance(config);
IMap<Integer, Integer> map = (IMap<Integer, Integer>) node.<Integer, Integer>getMap(mapName);
final QueryCache<Integer, Integer> queryCache = map.getQueryCache(queryCacheName, Predicates.sql("this > 20"), true);
for (int i = 0; i < 30; i++) {
map.put(i, i);
}
HazelcastInstance node2 = instanceFactory.newHazelcastInstance(config);
IMap<Integer, Integer> map2 = node2.getMap(mapName);
for (int i = 200; i < 220; i++) {
map2.put(i, i);
}
HazelcastInstance node3 = instanceFactory.newHazelcastInstance(config);
IMap<Integer, Integer> map3 = node3.getMap(mapName);
for (int i = 350; i < 357; i++) {
map3.put(i, i);
}
node3.shutdown();
for (int i = 220; i < 227; i++) {
map2.put(i, i);
}
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(43, queryCache.size());
}
});
}
}
| 36.877551 | 125 | 0.68991 |
1ddec250e16dc006fe4704d3e7c5dcdbddaaea32 | 1,784 | /*
* #!
* Ontopoly Editor
* #-
* Copyright (C) 2001 - 2013 The Ontopia Project
* #-
* 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 ontopoly;
import org.apache.wicket.protocol.http.WebRequestCycleProcessor;
import org.apache.wicket.request.IRequestCycleProcessor;
import ontopoly.model.Topic;
public class SampleOntopolyApplication extends OntopolyApplication {
@Override
protected IRequestCycleProcessor newRequestCycleProcessor() {
// NOTE: don't generate absolute URLs
return new WebRequestCycleProcessor();
}
@Override
protected OntopolyAccessStrategy newAccessStrategy() {
return new OntopolyAccessStrategy() {
@Override
public User authenticate(String username, String password) {
// let users in if their password is the same as the username
if (username != null && password != null && username.equals(password)) {
return new User(username, false);
} else {
return null;
}
}
@Override
public Privilege getPrivilege(User user, Topic topic) {
// protect the ontology
if (topic.isOntologyTopic() || topic.isSystemTopic() || topic.isFieldDefinition() || topic.isTopicMap()) {
return Privilege.READ_ONLY;
} else {
return Privilege.EDIT;
}
}
};
}
}
| 29.733333 | 110 | 0.713004 |
6add99e3d375643b5c58dadbbdb46d7f591e88bd | 2,225 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.proschedule.core.calendar.model;
import java.util.List;
import java.util.Date;
import com.proschedule.util.date.DateUtil;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Maycon Bordin
*/
public class CalendarTest {
private Calendar calendar;
public CalendarTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
calendar = new Calendar();
calendar.setYear(2010);
}
@After
public void tearDown() {
}
/**
* Test of generateDaysOfYear method, of class Calendar.
*/
@Test
public void testGenerateDaysOfYear() throws Exception {
System.out.println("generateDaysOfYear");
try {
calendar.generateDaysOfYear(8.0, false);
for ( Day d : calendar.getDays() ) {
System.out.println( "Dia: " + d.getDate() + "\n" );
}
} catch ( Exception e ) {
fail( "Erro em generateDaysOfYear: " + e.getMessage() );
}
}
@Test
public void testGetDay() throws Exception {
System.out.println("getDay");
Calendar c = new Calendar();
c.setYear(2010);
c.generateDaysOfYear(8.0, true);
Date date = DateUtil.formatDate("10/10/2010");
Day day = c.getDay( date );
if ( day == null ) {
fail("O dia está nulo.");
} else {
System.out.println( "DIA: " + day.getDate() );
}
}
@Test
public void testGetDaysPerMonth() throws Exception {
System.out.println("getDaysPerMonth");
Calendar c = new Calendar();
c.setYear(2010);
c.generateDaysOfYear(8.0, true);
List<Day> list = c.getDaysPerMonth( 6 );
for ( Day day : list ) {
System.out.println( day.getDate() );
}
}
} | 22.474747 | 68 | 0.583371 |
57fc8ba0a7867cd666d9a15cfa99e25513269bfb | 8,170 | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Test;
public class DeprecationStatusTest {
private static final DateTimeFormatter TIMESTAMP_FORMATTER = ISODateTimeFormat.dateTime();
private static final Long DELETED_MILLIS = 1453293540000L;
private static final Long DEPRECATED_MILLIS = 1453293420000L;
private static final Long OBSOLETE_MILLIS = 1453293480000L;
private static final String DELETED = TIMESTAMP_FORMATTER.print(DELETED_MILLIS);
private static final String DEPRECATED = TIMESTAMP_FORMATTER.print(DEPRECATED_MILLIS);
private static final String OBSOLETE = TIMESTAMP_FORMATTER.print(OBSOLETE_MILLIS);
private static final DiskTypeId DISK_TYPE_ID = DiskTypeId.of("project", "zone", "diskType");
private static final MachineTypeId MACHINE_TYPE_ID =
MachineTypeId.of("project", "zone", "machineType");
private static final DeprecationStatus.Status STATUS = DeprecationStatus.Status.DELETED;
private static final DeprecationStatus<DiskTypeId> DISK_TYPE_STATUS =
DeprecationStatus.<DiskTypeId>builder(STATUS)
.replacement(DISK_TYPE_ID)
.deprecated(DEPRECATED)
.obsolete(OBSOLETE)
.deleted(DELETED)
.build();
private static final DeprecationStatus<DiskTypeId> DISK_TYPE_STATUS_MILLIS =
DeprecationStatus.<DiskTypeId>builder(STATUS)
.replacement(DISK_TYPE_ID)
.deprecated(DEPRECATED_MILLIS)
.obsolete(OBSOLETE_MILLIS)
.deleted(DELETED_MILLIS)
.build();
private static final DeprecationStatus<MachineTypeId> MACHINE_TYPE_STATUS =
DeprecationStatus.builder(STATUS, MACHINE_TYPE_ID)
.deprecated(DEPRECATED)
.obsolete(OBSOLETE)
.deleted(DELETED)
.build();
@Test
public void testBuilder() {
compareDeprecationStatus(DISK_TYPE_STATUS, DISK_TYPE_STATUS_MILLIS);
assertEquals(DELETED, DISK_TYPE_STATUS.deleted());
assertEquals(DEPRECATED, DISK_TYPE_STATUS.deprecated());
assertEquals(OBSOLETE, DISK_TYPE_STATUS.obsolete());
assertEquals(DISK_TYPE_ID, DISK_TYPE_STATUS.replacement());
assertEquals(DEPRECATED_MILLIS, DISK_TYPE_STATUS.deprecatedMillis());
assertEquals(DELETED_MILLIS, DISK_TYPE_STATUS.deletedMillis());
assertEquals(OBSOLETE_MILLIS, DISK_TYPE_STATUS.obsoleteMillis());
assertEquals(STATUS, DISK_TYPE_STATUS.status());
assertEquals(DELETED, DISK_TYPE_STATUS_MILLIS.deleted());
assertEquals(DEPRECATED, DISK_TYPE_STATUS_MILLIS.deprecated());
assertEquals(OBSOLETE, DISK_TYPE_STATUS_MILLIS.obsolete());
assertEquals(DISK_TYPE_ID, DISK_TYPE_STATUS_MILLIS.replacement());
assertEquals(DEPRECATED_MILLIS, DISK_TYPE_STATUS_MILLIS.deprecatedMillis());
assertEquals(DELETED_MILLIS, DISK_TYPE_STATUS_MILLIS.deletedMillis());
assertEquals(OBSOLETE_MILLIS, DISK_TYPE_STATUS_MILLIS.obsoleteMillis());
assertEquals(STATUS, DISK_TYPE_STATUS.status());
assertEquals(DELETED, MACHINE_TYPE_STATUS.deleted());
assertEquals(DEPRECATED, MACHINE_TYPE_STATUS.deprecated());
assertEquals(OBSOLETE, MACHINE_TYPE_STATUS.obsolete());
assertEquals(DEPRECATED_MILLIS, MACHINE_TYPE_STATUS.deprecatedMillis());
assertEquals(DELETED_MILLIS, MACHINE_TYPE_STATUS.deletedMillis());
assertEquals(OBSOLETE_MILLIS, MACHINE_TYPE_STATUS.obsoleteMillis());
assertEquals(MACHINE_TYPE_ID, MACHINE_TYPE_STATUS.replacement());
assertEquals(STATUS, MACHINE_TYPE_STATUS.status());
}
@Test
public void testGettersIllegalArgument() {
DeprecationStatus<MachineTypeId> deprecationStatus =
DeprecationStatus.builder(STATUS, MACHINE_TYPE_ID)
.deprecated("deprecated")
.obsolete("obsolete")
.deleted("delete")
.build();
assertEquals("deprecated", deprecationStatus.deprecated());
try {
deprecationStatus.deprecatedMillis();
fail("Expected IllegalArgumentException");
} catch (IllegalStateException ex) {
// never reached
}
assertEquals("obsolete", deprecationStatus.obsolete());
try {
deprecationStatus.obsoleteMillis();
fail("Expected IllegalArgumentException");
} catch (IllegalStateException ex) {
// never reached
}
assertEquals("delete", deprecationStatus.deleted());
try {
deprecationStatus.deletedMillis();
fail("Expected IllegalArgumentException");
} catch (IllegalStateException ex) {
// never reached
}
}
@Test
public void testToBuilder() {
compareDeprecationStatus(DISK_TYPE_STATUS, DISK_TYPE_STATUS.toBuilder().build());
compareDeprecationStatus(MACHINE_TYPE_STATUS, MACHINE_TYPE_STATUS.toBuilder().build());
DeprecationStatus<DiskTypeId> deprecationStatus = DISK_TYPE_STATUS.toBuilder()
.deleted(DEPRECATED)
.build();
assertEquals(DEPRECATED, deprecationStatus.deleted());
deprecationStatus = deprecationStatus.toBuilder().deleted(DELETED).build();
compareDeprecationStatus(DISK_TYPE_STATUS, deprecationStatus);
}
@Test
public void testToBuilderIncomplete() {
DeprecationStatus<DiskTypeId> diskStatus = DeprecationStatus.of(STATUS, DISK_TYPE_ID);
assertEquals(diskStatus, diskStatus.toBuilder().build());
}
@Test
public void testOf() {
DeprecationStatus<DiskTypeId> diskStatus = DeprecationStatus.of(STATUS, DISK_TYPE_ID);
assertNull(diskStatus.deleted());
assertNull(diskStatus.deprecated());
assertNull(diskStatus.obsolete());
assertEquals(DISK_TYPE_ID, diskStatus.replacement());
assertEquals(STATUS, diskStatus.status());
}
@Test
public void testToAndFromPb() {
DeprecationStatus<DiskTypeId> diskStatus =
DeprecationStatus.fromPb(DISK_TYPE_STATUS.toPb(), DiskTypeId.FROM_URL_FUNCTION);
compareDeprecationStatus(DISK_TYPE_STATUS, diskStatus);
DeprecationStatus<MachineTypeId> machineStatus =
DeprecationStatus.fromPb(MACHINE_TYPE_STATUS.toPb(), MachineTypeId.FROM_URL_FUNCTION);
compareDeprecationStatus(MACHINE_TYPE_STATUS, machineStatus);
diskStatus = DeprecationStatus.builder(STATUS, DISK_TYPE_ID).deprecated(DEPRECATED).build();
assertEquals(diskStatus,
DeprecationStatus.fromPb(diskStatus.toPb(), DiskTypeId.FROM_URL_FUNCTION));
machineStatus =
DeprecationStatus.builder(STATUS, MACHINE_TYPE_ID).deprecated(DEPRECATED).build();
assertEquals(machineStatus,
DeprecationStatus.fromPb(machineStatus.toPb(), MachineTypeId.FROM_URL_FUNCTION));
diskStatus = DeprecationStatus.of(STATUS, DISK_TYPE_ID);
assertEquals(diskStatus,
DeprecationStatus.fromPb(diskStatus.toPb(), DiskTypeId.FROM_URL_FUNCTION));
}
private void compareDeprecationStatus(DeprecationStatus expected, DeprecationStatus value) {
assertEquals(expected, value);
assertEquals(expected.deleted(), value.deleted());
assertEquals(expected.deprecated(), value.deprecated());
assertEquals(expected.obsolete(), value.obsolete());
assertEquals(expected.deletedMillis(), value.deletedMillis());
assertEquals(expected.deprecatedMillis(), value.deprecatedMillis());
assertEquals(expected.obsoleteMillis(), value.obsoleteMillis());
assertEquals(expected.replacement(), value.replacement());
assertEquals(expected.status(), value.status());
assertEquals(expected.hashCode(), value.hashCode());
}
}
| 44.89011 | 96 | 0.753611 |
dcff46cd7691bcd8e574ba1270060bba592eb812 | 23,626 | /**
* Copyright 2015 Confluent 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 io.confluent.connect.hdfs;
import io.confluent.connect.hdfs.file.FileInfo;
import io.confluent.connect.hdfs.file.FileService;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.errors.IllegalWorkerStateException;
import org.apache.kafka.connect.errors.SchemaProjectorException;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTaskContext;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import io.confluent.connect.avro.AvroData;
import io.confluent.connect.hdfs.errors.HiveMetaStoreException;
import io.confluent.connect.hdfs.hive.HiveMetaStore;
import io.confluent.connect.hdfs.hive.HiveUtil;
import io.confluent.connect.hdfs.partitioner.Partitioner;
import io.confluent.connect.hdfs.schema.Compatibility;
import io.confluent.connect.hdfs.schema.SchemaUtils;
import io.confluent.connect.hdfs.storage.Storage;
import io.confluent.connect.hdfs.wal.WAL;
public class TopicPartitionWriter {
private static final Logger log = LoggerFactory.getLogger(TopicPartitionWriter.class);
private WAL wal;
private Map<String, String> tempFiles;
private Map<String, RecordWriter<SinkRecord>> writers;
private FileService<SinkRecord> fileService;
private TopicPartition tp;
private Partitioner partitioner;
private String url;
private String topicsDir;
private State state;
private Queue<SinkRecord> buffer;
private boolean recovered;
private Storage storage;
private SinkTaskContext context;
private int recordCounter;
private int flushSize;
private long rotateIntervalMs;
private long lastRotate;
private long rotateScheduleIntervalMs;
private long nextScheduledRotate;
private RecordWriterProvider writerProvider;
private Configuration conf;
private AvroData avroData;
private Set<String> appended;
private long offset;
private boolean sawInvalidOffset;
private Map<String, Long> startOffsets;
private Map<String, Long> offsets;
private long timeoutMs;
private long failureTime;
private Compatibility compatibility;
private Schema currentSchema;
private HdfsSinkConnectorConfig connectorConfig;
private String extension;
private final String zeroPadOffsetFormat;
private DateTimeZone timeZone;
private final boolean hiveIntegration;
private String hiveDatabase;
private HiveMetaStore hiveMetaStore;
private SchemaFileReader schemaFileReader;
private HiveUtil hive;
private ExecutorService executorService;
private Queue<Future<Void>> hiveUpdateFutures;
private Set<String> hivePartitions;
public TopicPartitionWriter(
TopicPartition tp,
Storage storage,
RecordWriterProvider writerProvider,
Partitioner partitioner,
HdfsSinkConnectorConfig connectorConfig,
SinkTaskContext context,
AvroData avroData) {
this(tp, storage, writerProvider, partitioner, connectorConfig, context, avroData, null, null, null, null, null);
}
public TopicPartitionWriter(
TopicPartition tp,
Storage storage,
RecordWriterProvider writerProvider,
Partitioner partitioner,
HdfsSinkConnectorConfig connectorConfig,
SinkTaskContext context,
AvroData avroData,
HiveMetaStore hiveMetaStore,
HiveUtil hive,
SchemaFileReader schemaFileReader,
ExecutorService executorService,
Queue<Future<Void>> hiveUpdateFutures) {
this.tp = tp;
this.connectorConfig = connectorConfig;
this.context = context;
this.avroData = avroData;
this.storage = storage;
this.writerProvider = writerProvider;
this.partitioner = partitioner;
this.fileService = writerProvider.getFileService();
this.url = storage.url();
this.conf = storage.conf();
this.schemaFileReader = schemaFileReader;
topicsDir = connectorConfig.getString(HdfsSinkConnectorConfig.TOPICS_DIR_CONFIG);
flushSize = connectorConfig.getInt(HdfsSinkConnectorConfig.FLUSH_SIZE_CONFIG);
rotateIntervalMs = connectorConfig.getLong(HdfsSinkConnectorConfig.ROTATE_INTERVAL_MS_CONFIG);
rotateScheduleIntervalMs = connectorConfig.getLong(HdfsSinkConnectorConfig.ROTATE_SCHEDULE_INTERVAL_MS_CONFIG);
timeoutMs = connectorConfig.getLong(HdfsSinkConnectorConfig.RETRY_BACKOFF_CONFIG);
compatibility = SchemaUtils.getCompatibility(
connectorConfig.getString(HdfsSinkConnectorConfig.SCHEMA_COMPATIBILITY_CONFIG));
String logsDir = connectorConfig.getString(HdfsSinkConnectorConfig.LOGS_DIR_CONFIG);
wal = storage.wal(logsDir, tp);
buffer = new LinkedList<>();
writers = new HashMap<>();
tempFiles = new HashMap<>();
appended = new HashSet<>();
startOffsets = new HashMap<>();
offsets = new HashMap<>();
state = State.RECOVERY_STARTED;
failureTime = -1L;
offset = -1L;
sawInvalidOffset = false;
extension = writerProvider.getExtension();
zeroPadOffsetFormat
= "%0" +
connectorConfig.getInt(HdfsSinkConnectorConfig.FILENAME_OFFSET_ZERO_PAD_WIDTH_CONFIG) +
"d";
hiveIntegration = connectorConfig.getBoolean(HdfsSinkConnectorConfig.HIVE_INTEGRATION_CONFIG);
if (hiveIntegration) {
hiveDatabase = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_DATABASE_CONFIG);
this.hiveMetaStore = hiveMetaStore;
this.hive = hive;
this.executorService = executorService;
this.hiveUpdateFutures = hiveUpdateFutures;
hivePartitions = new HashSet<>();
}
if(rotateScheduleIntervalMs > 0) {
timeZone = DateTimeZone.forID(connectorConfig.getString(HdfsSinkConnectorConfig.TIMEZONE_CONFIG));
}
// Initialize rotation timers
updateRotationTimers();
}
private enum State {
RECOVERY_STARTED,
RECOVERY_PARTITION_PAUSED,
WAL_APPLIED,
WAL_TRUNCATED,
OFFSET_RESET,
WRITE_STARTED,
WRITE_PARTITION_PAUSED,
SHOULD_ROTATE,
TEMP_FILE_CLOSED,
WAL_APPENDED,
FILE_COMMITTED;
private static State[] vals = values();
public State next() {
return vals[(this.ordinal() + 1) % vals.length];
}
}
@SuppressWarnings("fallthrough")
public boolean recover() {
try {
switch (state) {
case RECOVERY_STARTED:
log.info("Started recovery for topic partition {}", tp);
pause();
nextState();
case RECOVERY_PARTITION_PAUSED:
applyWAL();
nextState();
case WAL_APPLIED:
truncateWAL();
nextState();
case WAL_TRUNCATED:
resetOffsets();
nextState();
case OFFSET_RESET:
resume();
nextState();
log.info("Finished recovery for topic partition {}", tp);
break;
default:
log.error("{} is not a valid state to perform recovery for topic partition {}.", state, tp);
}
} catch (ConnectException e) {
log.error("Recovery failed at state {}", state, e);
setRetryTimeout(timeoutMs);
return false;
}
return true;
}
private void updateRotationTimers() {
lastRotate = System.currentTimeMillis();
if(log.isDebugEnabled() && rotateIntervalMs > 0) {
log.debug("Update last rotation timer. Next rotation for {} will be in {}ms", tp, rotateIntervalMs);
}
if (rotateScheduleIntervalMs > 0) {
nextScheduledRotate = DateTimeUtils.getNextTimeAdjustedByDay(lastRotate, rotateScheduleIntervalMs, timeZone);
if (log.isDebugEnabled()) {
log.debug("Update scheduled rotation timer. Next rotation for {} will be at {}", tp, new DateTime(nextScheduledRotate).withZone(timeZone).toString());
}
}
}
@SuppressWarnings("fallthrough")
public void write() {
long now = System.currentTimeMillis();
if (failureTime > 0 && now - failureTime < timeoutMs) {
return;
}
if (state.compareTo(State.WRITE_STARTED) < 0) {
boolean success = recover();
if (!success) {
return;
}
updateRotationTimers();
}
while(!buffer.isEmpty()) {
try {
switch (state) {
case WRITE_STARTED:
pause();
nextState();
case WRITE_PARTITION_PAUSED:
if (currentSchema == null) {
if (compatibility != Compatibility.NONE && offset != -1) {
String topicDir = fileService.topicDirectory(url, topicsDir, tp.topic());
FileStatus fileStatusWithMaxOffset = fileService.fileStatusWithMaxOffset(storage, new Path(topicDir), p -> {
FileInfo fileInfo = fileService.getFileInfo(p.getName());
return fileInfo != null && fileInfo.getTopic().equals(tp.topic()) && fileInfo.getPartition() == tp.partition();
});
if (fileStatusWithMaxOffset != null) {
currentSchema = schemaFileReader.getSchema(conf, fileStatusWithMaxOffset.getPath());
}
}
}
SinkRecord record = buffer.peek();
Schema valueSchema = record.valueSchema();
if (SchemaUtils.shouldChangeSchema(valueSchema, currentSchema, compatibility)) {
currentSchema = valueSchema;
if (hiveIntegration) {
createHiveTable();
alterHiveSchema();
}
if (recordCounter > 0) {
nextState();
} else {
break;
}
} else {
SinkRecord projectedRecord = SchemaUtils.project(record, currentSchema, compatibility);
writeRecord(projectedRecord);
buffer.poll();
if (shouldRotate(now)) {
log.info("Starting commit and rotation for topic partition {} with start offsets {}"
+ " and end offsets {}", tp, startOffsets, offsets);
nextState();
// Fall through and try to rotate immediately
} else {
break;
}
}
case SHOULD_ROTATE:
updateRotationTimers();
closeTempFile();
nextState();
case TEMP_FILE_CLOSED:
appendToWAL();
nextState();
case WAL_APPENDED:
commitFile();
nextState();
case FILE_COMMITTED:
setState(State.WRITE_PARTITION_PAUSED);
break;
default:
log.error("{} is not a valid state to write record for topic partition {}.", state, tp);
}
} catch (SchemaProjectorException | IllegalWorkerStateException | HiveMetaStoreException e ) {
throw new RuntimeException(e);
} catch (IOException | ConnectException e) {
log.error("Exception on topic partition {}: ", tp, e);
failureTime = System.currentTimeMillis();
setRetryTimeout(timeoutMs);
break;
}
}
if (buffer.isEmpty()) {
// committing files after waiting for rotateIntervalMs time but less than flush.size records available
if (recordCounter > 0 && shouldRotate(now)) {
log.info("committing files after waiting for rotateIntervalMs time but less than flush.size records available.");
updateRotationTimers();
try {
closeTempFile();
appendToWAL();
commitFile();
} catch (IOException e) {
log.error("Exception on topic partition {}: ", tp, e);
failureTime = System.currentTimeMillis();
setRetryTimeout(timeoutMs);
}
}
resume();
state = State.WRITE_STARTED;
}
}
public void close() throws ConnectException {
log.debug("Closing TopicPartitionWriter {}", tp);
List<Exception> exceptions = new ArrayList<>();
for (String encodedPartition : tempFiles.keySet()) {
try {
if (writers.containsKey(encodedPartition)) {
log.debug("Discarding in progress tempfile {} for {} {}",
tempFiles.get(encodedPartition), tp, encodedPartition);
closeTempFile(encodedPartition);
deleteTempFile(encodedPartition);
}
} catch (IOException e) {
log.error("Error discarding temp file {} for {} {} when closing TopicPartitionWriter:",
tempFiles.get(encodedPartition), tp, encodedPartition, e);
}
}
writers.clear();
try {
wal.close();
} catch (ConnectException e) {
log.error("Error closing {}.", wal.getLogFile(), e);
exceptions.add(e);
}
startOffsets.clear();
offsets.clear();
if (exceptions.size() != 0) {
StringBuilder sb = new StringBuilder();
for (Exception exception: exceptions) {
sb.append(exception.getMessage());
sb.append("\n");
}
throw new ConnectException("Error closing writer: " + sb.toString());
}
}
public void buffer(SinkRecord sinkRecord) {
buffer.add(sinkRecord);
}
public long offset() {
return offset;
}
public Map<String, RecordWriter<SinkRecord>> getWriters() {
return writers;
}
public Map<String, String> getTempFiles() {
return tempFiles;
}
public String getExtension() {
return writerProvider.getExtension();
}
private String getDirectory(String encodedPartition) {
return partitioner.generatePartitionedPath(tp.topic(), encodedPartition);
}
private void nextState() {
state = state.next();
}
private void setState(State state) {
this.state = state;
}
private boolean shouldRotate(long now) {
boolean periodicRotation = rotateIntervalMs > 0 && now - lastRotate >= rotateIntervalMs;
boolean scheduledRotation = rotateScheduleIntervalMs > 0 && now >= nextScheduledRotate;
boolean messageSizeRotation = recordCounter >= flushSize;
return periodicRotation || scheduledRotation || messageSizeRotation;
}
private void readOffset() throws ConnectException {
try {
String path = fileService.topicDirectory(url, topicsDir, tp.topic());
FileStatus fileStatusWithMaxOffset = fileService.fileStatusWithMaxOffset(storage, new Path(path), p -> {
FileInfo fileInfo = fileService.getFileInfo(p.getName());
return fileInfo != null && fileInfo.getTopic().equals(tp.topic()) && fileInfo.getPartition() == tp.partition();
});
if (fileStatusWithMaxOffset != null) {
offset = fileService.extractOffset(fileStatusWithMaxOffset.getPath().getName()) + 1;
}
} catch (IOException e) {
throw new ConnectException(e);
}
}
private void pause() {
context.pause(tp);
}
private void resume() {
context.resume(tp);
}
private RecordWriter<SinkRecord> getWriter(SinkRecord record, String encodedPartition)
throws ConnectException {
try {
if (writers.containsKey(encodedPartition)) {
return writers.get(encodedPartition);
}
String tempFile = getTempFile(encodedPartition);
RecordWriter<SinkRecord> writer = writerProvider.getRecordWriter(conf, tempFile, record, avroData);
writers.put(encodedPartition, writer);
if (hiveIntegration && !hivePartitions.contains(encodedPartition)) {
addHivePartition(encodedPartition);
hivePartitions.add(encodedPartition);
}
return writer;
} catch (IOException e) {
throw new ConnectException(e);
}
}
private String getTempFile(String encodedPartition) {
String tempFile;
if (tempFiles.containsKey(encodedPartition)) {
tempFile = tempFiles.get(encodedPartition);
} else {
String directory = HdfsSinkConnectorConstants.TEMPFILE_DIRECTORY + getDirectory(encodedPartition);
tempFile = fileService.tempFileName(url, topicsDir, directory, extension);
tempFiles.put(encodedPartition, tempFile);
}
return tempFile;
}
private void applyWAL() throws ConnectException {
if (!recovered) {
wal.apply();
}
}
private void truncateWAL() throws ConnectException {
if (!recovered) {
wal.truncate();
}
}
private void resetOffsets() throws ConnectException {
if (!recovered) {
readOffset();
// Note that we must *always* request that we seek to an offset here. Currently the framework will still commit
// Kafka offsets even though we track our own (see KAFKA-3462), which can result in accidentally using that offset
// if one was committed but no files were rolled to their final location in HDFS (i.e. some data was accepted,
// written to a tempfile, but then that tempfile was discarded). To protect against this, even if we just want
// to start at offset 0 or reset to the earliest offset, we specify that explicitly to forcibly override any
// committed offsets.
long seekOffset = offset > 0 ? offset : 0;
log.debug("Resetting offset for {} to {}", tp, seekOffset);
context.offset(tp, seekOffset);
recovered = true;
}
}
private void writeRecord(SinkRecord record) throws IOException {
long expectedOffset = offset + recordCounter;
if (offset == -1) {
offset = record.kafkaOffset();
} else if (record.kafkaOffset() != expectedOffset) {
// Currently it's possible to see stale data with the wrong offset after a rebalance when you
// rewind, which we do since we manage our own offsets. See KAFKA-2894.
if (!sawInvalidOffset) {
log.info(
"Ignoring stale out-of-order record in {}-{}. Has offset {} instead of expected offset {}",
record.topic(), record.kafkaPartition(), record.kafkaOffset(), expectedOffset);
}
sawInvalidOffset = true;
return;
}
if (sawInvalidOffset) {
log.info(
"Recovered from stale out-of-order records in {}-{} with offset {}",
record.topic(), record.kafkaPartition(), expectedOffset);
sawInvalidOffset = false;
}
String encodedPartition = partitioner.encodePartition(record);
RecordWriter<SinkRecord> writer = getWriter(record, encodedPartition);
writer.write(record);
fileService.process(record, encodedPartition);
if (!startOffsets.containsKey(encodedPartition)) {
startOffsets.put(encodedPartition, record.kafkaOffset());
offsets.put(encodedPartition, record.kafkaOffset());
} else {
offsets.put(encodedPartition, record.kafkaOffset());
}
recordCounter++;
}
private void closeTempFile(String encodedPartition) throws IOException {
if (writers.containsKey(encodedPartition)) {
RecordWriter<SinkRecord> writer = writers.get(encodedPartition);
writer.close();
writers.remove(encodedPartition);
}
}
private void closeTempFile() throws IOException {
for (String encodedPartition: tempFiles.keySet()) {
closeTempFile(encodedPartition);
}
}
private void appendToWAL(String encodedPartition) throws IOException {
String tempFile = tempFiles.get(encodedPartition);
if (appended.contains(tempFile)) {
return;
}
if (!startOffsets.containsKey(encodedPartition)) {
return;
}
long startOffset = startOffsets.get(encodedPartition);
long endOffset = offsets.get(encodedPartition);
String directory = getDirectory(encodedPartition);
String committedFile = fileService.committedFileName(url, topicsDir, directory, tp,
startOffset, endOffset, encodedPartition, extension, zeroPadOffsetFormat);
wal.append(tempFile, committedFile);
appended.add(tempFile);
}
private void appendToWAL() throws IOException {
beginAppend();
for (String encodedPartition: tempFiles.keySet()) {
appendToWAL(encodedPartition);
}
endAppend();
}
private void beginAppend() throws IOException {
if (!appended.contains(WAL.beginMarker)) {
wal.append(WAL.beginMarker, "");
}
}
private void endAppend() throws IOException {
if (!appended.contains(WAL.endMarker)) {
wal.append(WAL.endMarker, "");
}
}
private void commitFile() throws IOException {
appended.clear();
for (String encodedPartition: tempFiles.keySet()) {
commitFile(encodedPartition);
}
}
private void commitFile(String encodedPartiton) throws IOException {
if (!startOffsets.containsKey(encodedPartiton)) {
return;
}
long startOffset = startOffsets.get(encodedPartiton);
long endOffset = offsets.get(encodedPartiton);
String tempFile = tempFiles.get(encodedPartiton);
String directory = getDirectory(encodedPartiton);
String committedFile = fileService.committedFileName(url, topicsDir, directory, tp,
startOffset, endOffset, encodedPartiton, extension, zeroPadOffsetFormat);
String directoryName = fileService.directoryName(url, topicsDir, directory);
if (!storage.exists(directoryName)) {
storage.mkdirs(directoryName);
}
storage.commit(tempFile, committedFile);
fileService.reset(encodedPartiton);
startOffsets.remove(encodedPartiton);
offset = offset + recordCounter;
recordCounter = 0;
log.info("Committed {} for {}", committedFile, tp);
}
private void deleteTempFile(String encodedPartiton) throws IOException {
storage.delete(tempFiles.get(encodedPartiton));
}
private void setRetryTimeout(long timeoutMs) {
context.timeout(timeoutMs);
}
private void createHiveTable() {
Future<Void> future = executorService.submit(new Callable<Void>() {
@Override
public Void call() throws HiveMetaStoreException {
hive.createTable(hiveDatabase, tp.topic(), currentSchema, partitioner);
return null;
}
});
hiveUpdateFutures.add(future);
}
private void alterHiveSchema() {
Future<Void> future = executorService.submit(new Callable<Void>() {
@Override
public Void call() throws HiveMetaStoreException {
hive.alterSchema(hiveDatabase, tp.topic(), currentSchema);
return null;
}
});
hiveUpdateFutures.add(future);
}
private void addHivePartition(final String location) {
Future<Void> future = executorService.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
hiveMetaStore.addPartition(hiveDatabase, tp.topic(), location);
return null;
}
});
hiveUpdateFutures.add(future);
}
}
| 34.795287 | 158 | 0.677347 |
0b16cefa617356d6b5ad7ba8b17268b13a1737c7 | 16,490 | package greenerLawn.androidthings.GreenerHub;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import com.google.android.things.pio.Gpio;
import com.google.android.things.pio.PeripheralManagerService;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import android.widget.Switch;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final String deviceID = "pi3";
private static final String serial = "pi1Password";
private static final int availZones = 8;
private static final int ONE_SECOND = 1000;
private static final int ONE_MINUTE = 60 * ONE_SECOND;
private static final int ONE_HOUR = 60 * ONE_MINUTE;
private static final int ONE_DAY = 24 * ONE_HOUR;
private static List<Zone> zoneList = new ArrayList<Zone>();
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference deviceDBRef;
private final List<String> LEDS= new ArrayList<String>(Arrays.asList("BCM4", "BCM17", "BCM27", "BCM22", "BCM12", "BCM23", "BCM24", "BCM25"));
List <Gpio> LedGPIO;
private Handler mHandler = new Handler();
private Gpio mLedGpio4,mLedGpio17,mLedGpio27,mLedGpio22,mLedGpio12,mLedGpio23,mLedGpio24,mLedGpio25;
private Switch switch1, switch2, switch3, switch4, switch5, switch6, switch7, switch8;
private List<Switch> switchList;
private GreenHub hub = new GreenHub(serial, availZones);
private Schedules mCurrentSchedule = null;
private TimeZone tz = TimeZone.getTimeZone("Canada/Mountain");
private Calendar calendar = Calendar.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupGPIO();
zoneSetup();
setContentView(R.layout.activity_main);
// if (isNetworkAvailable()){
// Log.e(TAG, "onCreate: Connected");
// Intent wifi = new Intent(this, WiFi_activity.class);
// startActivity(wifi);
// }
setSwitches();
// SETUP DB
DatabaseReference myRef = database.getReference("greennerHubs").child(deviceID);
eventHandler(myRef);
// TODO activity to connect to wifi
// TODO authenticate PI to restore firebase security
// TODO update pie on boot or resume previous programming
initialLightsOn();
calendar.setTimeZone(tz);
int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
Log.d("SOMETHING", "current day is "+currentDayOfWeek);
setFirstSchedule(currentDayOfWeek);
}
private void setSwitches() {
switch1 = (Switch) findViewById(R.id.switch1);
switch2 = (Switch) findViewById(R.id.switch2);
switch3 = (Switch) findViewById(R.id.switch3);
switch4 = (Switch) findViewById(R.id.switch4);
switch5 = (Switch) findViewById(R.id.switch5);
switch6 = (Switch) findViewById(R.id.switch6);
switch7 = (Switch) findViewById(R.id.switch7);
switch8 = (Switch) findViewById(R.id.switch8);
}
private void setupGPIO() {
try{
PeripheralManagerService service = new PeripheralManagerService();
mLedGpio4 = service.openGpio(LEDS.get(0));
mLedGpio17 = service.openGpio(LEDS.get(1));
mLedGpio27 = service.openGpio(LEDS.get(2));
mLedGpio22 = service.openGpio(LEDS.get(3));
mLedGpio12 = service.openGpio(LEDS.get(4));
mLedGpio23 = service.openGpio(LEDS.get(5));
mLedGpio24 = service.openGpio(LEDS.get(6));
mLedGpio25 = service.openGpio(LEDS.get(7));
mLedGpio4.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mLedGpio17.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mLedGpio27.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mLedGpio22.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mLedGpio12.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mLedGpio23.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mLedGpio24.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mLedGpio25.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void zoneSetup() {
for (int i = 0; i<availZones; i++){
zoneList.add(new Zone());
zoneList.get(i).setZoneNumber("" + (i+1) );
}
}
private void eventHandler(final DatabaseReference myRef) {
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//iterate
if (!dataSnapshot.exists()){
// SETUP THE DEVICE FOR THE FIRST TIME
Log.e("SOMETHING", "onDataChange: DEVICE DOESN'T EXIST");
myRef.setValue(hub);
for (Zone zone: zoneList){
String key = myRef.child("zones").push().getKey();
zone.setZoneId(key);
myRef.child("zones").child(key).setValue(zone);
}
hub.setZoneList(zoneList);
}
hub = dataSnapshot.getValue(GreenHub.class);
Log.e("PORTS", "HUBPORTS: " + hub.getPorts());
myRef.child("zones").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.d("BROADCASTRECIEVED", "onReceive: Setting up reciever part 1");
String port = dataSnapshot.getValue(Zone.class).getZoneNumber();
boolean iszOnOff= dataSnapshot.getValue(Zone.class).iszOnOff();
toggleLED(port, iszOnOff );
if(!iszOnOff){
setFirstSchedule(calendar.get(Calendar.DAY_OF_WEEK));
}
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
myRef.child("schedules").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//
// Schedules temp = dataSnapshot.getValue(Schedules.class);
// if(mCurrentSchedule == null) {
// mCurrentSchedule = temp;
// } else if (mCurrentSchedule.getDay() == temp.getDay()){}
calendar.setTimeZone(tz);
setFirstSchedule(calendar.get(Calendar.DAY_OF_WEEK));
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// String zoneGUID = dataSnapshot.getValue(Schedules.class).getzGUID();
// setNextSchedule(zoneGUID);
calendar.setTimeZone(tz);
setFirstSchedule(calendar.get(Calendar.DAY_OF_WEEK));
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
calendar.setTimeZone(tz);
setFirstSchedule(calendar.get(Calendar.DAY_OF_WEEK));
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
private void setNextSchedule(Schedules currentSchedule){
calendar.setTimeZone(tz);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, SprinklerReceiver.class);
intent.setAction("greenerLawn.androidthings.GreenerHub");
intent.putExtra("zoneId", currentSchedule.getzGUID());
intent.putExtra("duration", currentSchedule.getDuration());
intent.putExtra("startTime", currentSchedule.getStartTime());
intent.putExtra("endTime", currentSchedule.getEndTime());
intent.putExtra("zoneOn", true);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
//Cancel any alarms that are happening right now.
alarmManager.cancel(pendingIntent);
long currentTime = System.currentTimeMillis();
long startTime;
long dayDifference;
long currentTimeInMili = getCurrentTimeInMili();
Log.d("CURRENT HOUR", "currentTimeinMili: "+currentTimeInMili);
if (calendar.get(Calendar.DAY_OF_WEEK) == mCurrentSchedule.getDay() && mCurrentSchedule.getStartTime() > currentTimeInMili){
startTime = mCurrentSchedule.getStartTime() - currentTimeInMili;
Log.d("START TIME TODAY", "startTime of current schedue: "+startTime);
} else {
long dayOfTheWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfTheWeek > mCurrentSchedule.getDay()) {
dayDifference = (7-dayOfTheWeek + mCurrentSchedule.getDay()) * ONE_DAY;
} else {
long tempTime = mCurrentSchedule.getDay() - dayOfTheWeek;
if (tempTime == 0) {
tempTime = 7;
}
dayDifference = tempTime * ONE_DAY;
}
startTime = dayDifference + (mCurrentSchedule.getStartTime() - currentTimeInMili);
Log.d("START TIME NOT TODAY", "startTime of current schedue: "+startTime);
}
Log.d("BROADCASTRECIEVED", "onReceive: Setting up reciever");
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
currentTime + startTime,
pendingIntent);
}
private void setFirstSchedule(final int currentDayOfWeek){
calendar.setTimeZone(tz);
DatabaseReference scheduleRef = database.getReference("greennerHubs/"+deviceID+"/schedules");
Query q = scheduleRef.orderByChild("day").equalTo(currentDayOfWeek);
q.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
boolean changed = false;
int actualDay = calendar.get(Calendar.DAY_OF_WEEK);
for(DataSnapshot schedule : dataSnapshot.getChildren()){
Schedules temp = schedule.getValue(Schedules.class);
if(mCurrentSchedule == null && !temp.isPausedByIDC()) {
mCurrentSchedule = temp;
changed = true;
} else if (temp.getDay() != actualDay){
if (temp.getStartTime() < mCurrentSchedule.getStartTime() && !temp.isPausedByIDC()) {
mCurrentSchedule = temp;
changed = true;
}
} else if (temp.getStartTime() > getCurrentTimeInMili() ){
if (!temp.isPausedByIDC() && temp.getStartTime() < mCurrentSchedule.getStartTime() || mCurrentSchedule.getStartTime() < getCurrentTimeInMili() ){
mCurrentSchedule = temp;
changed = true;
}
}
}
if(changed){
setNextSchedule(mCurrentSchedule);
}
} else {
int nextDayOfWeek = currentDayOfWeek;
if(nextDayOfWeek >= Calendar.SATURDAY) {
nextDayOfWeek = 0;
}
//@TODO this is gonna cause problems if no schedule, need to come up with better solution
nextDayOfWeek = nextDayOfWeek +1;
setFirstSchedule(nextDayOfWeek);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void initialLightsOn(){
DatabaseReference zoneRef = database.getReference("greennerHubs/"+deviceID+"zones");
zoneRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Zone z = dataSnapshot.getValue(Zone.class);
zoneList.add(z);
toggleLED(z.getZoneNumber(), z.iszOnOff());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private long getCurrentTimeInMili(){
long hour = calendar.get(Calendar.HOUR_OF_DAY);
long minute = calendar.get(Calendar.MINUTE);
hour = hour * ONE_HOUR;
minute = minute * ONE_MINUTE;
long currentTimeOfDay = hour + minute;
return currentTimeOfDay;
}
private void toggleLED(String zoneNumber, boolean ledStateToSet) {
LedGPIO = new ArrayList<Gpio>(Arrays.asList( mLedGpio4, mLedGpio17,mLedGpio27,mLedGpio22,mLedGpio12,mLedGpio23,mLedGpio24,mLedGpio25));
switchList = new ArrayList<>(Arrays.asList(switch1, switch2, switch3, switch4, switch5, switch6, switch7, switch8));
LedGPIO.get((Integer.parseInt(zoneNumber))-1);
switchList.get((Integer.parseInt(zoneNumber))-1).setChecked(ledStateToSet);
Log.e(TAG, "ZONES: " + zoneNumber + " is " + ledStateToSet);
if (LedGPIO.get((Integer.parseInt(zoneNumber))-1) == null) {
Log.e(TAG, "LED VALUE IS NULL FOR " + zoneNumber);
return;
}
try {
// Toggle the GPIO state
LedGPIO.get((Integer.parseInt(zoneNumber))-1).setValue(ledStateToSet);
Log.e(TAG, "State set to " + LedGPIO.get((Integer.parseInt(zoneNumber))-1).getValue());
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// mHandler.removeCallbacks(mBlinkRunnable);
// Log.i(TAG, "Closing LED GPIO pin");
for (int i = 0; i < LedGPIO.size(); i++) {
try {
LedGPIO.get(i).close();
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
} finally {
for (int j = 0; j < LedGPIO.size(); j++) {
try {
LedGPIO.get(i).setValue(false);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
} | 42.282051 | 173 | 0.597514 |
a60f24725601b8c471659f85f03f3b5aa52fc173 | 9,186 | package com.sanju.youtubedata.service;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTubeRequestInitializer;
import com.google.api.services.youtube.model.*;
import com.sanju.youtubedata.entity.CrawlingInfo;
import com.sanju.youtubedata.entity.YouTubeVideoInfo;
import com.sanju.youtubedata.entity.YoutubeChannelInfo;
import com.sanju.youtubedata.entity.YoutubeVideoStatistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
@Service
public class YoutubeApiServiceImpl implements YoutubeApiService {
@Autowired
private Environment env;
private static final long NUMBER_OF_VIDEOS_RETURNED = 50;
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
private YouTube youtube;
private long count = 0;
@Autowired
YoutubeVideoInfoService youtubeVideoInfoService;
@Autowired
YoutubeVideoStatService youtubeVideoStatService;
@Autowired
YoutubeChannelService youtubeChannelService;
@Autowired
CrawlingInfoService crawlingInfoService;
@Override
public String crawlYoutubeVideoInfo(String keyword,long pageToCrawl) {
getYoutubeVideoList(keyword,pageToCrawl);
return "Youtube video information is loading...";
}
@Transactional
@Async("threadPoolTaskExecutor")
public List<Object> getYoutubeVideoList(String queryTerm,long pageToCrawl) {
try {
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}})
.setApplicationName("YoutubeVideoInfo")
.setYouTubeRequestInitializer(new YouTubeRequestInitializer(env.getProperty("youtube.apikey")))
.build();
YouTube.Search.List search = youtube.search().list("id,snippet");
search.setQ(queryTerm);
search.setType("video");
search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
for (int i = 0; i < pageToCrawl; i++) {
String pageToken = null;
CrawlingInfo crawlingInfo = crawlingInfoService.getBySearchKey(queryTerm);
if (crawlingInfo != null && crawlingInfo.getNextPageToken() != null) {
pageToken = crawlingInfo.getNextPageToken();
count = crawlingInfo.getTotalCount();
crawlingInfo.setCurrentPageToken(pageToken);
} else if (crawlingInfo == null) {
crawlingInfo = new CrawlingInfo();
count = 0;
crawlingInfo.setSearchKey(queryTerm);
crawlingInfo.setCurrentPageToken(null);
}
if (pageToken != null) {
search.setPageToken(pageToken);
}
SearchListResponse searchResponse = search.execute();
List<SearchResult> searchResultList = searchResponse.getItems();
if (searchResultList != null) {
extractAndSave(searchResultList.iterator(), queryTerm);
}
crawlingInfo.setNextPageToken(searchResponse.getNextPageToken());
crawlingInfoService.update(crawlingInfo);
System.out.println("Next Page token : " + searchResponse.getNextPageToken());
}
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
private void extractAndSave(Iterator<SearchResult> iteratorSearchResults, String query) throws IOException {
if (!iteratorSearchResults.hasNext()) {
System.out.println(" There aren't any results for your query.");
}
while (iteratorSearchResults.hasNext()) {
SearchResult singleVideo = iteratorSearchResults.next();
System.out.println("Video number = " + count + " Inserting video Information " + singleVideo.getId().getVideoId());
count++;
YouTubeVideoInfo youTubeVideoInfo = youtubeVideoInfoService.getByVideoId(singleVideo.getId().getVideoId());
if (youTubeVideoInfo == null) {
youTubeVideoInfo = new YouTubeVideoInfo();
ResourceId rId = singleVideo.getId();
youTubeVideoInfo.setKeyword(query);
youTubeVideoInfo.setDescription(singleVideo.getSnippet().getDescription());
youTubeVideoInfo.setPublishedDate(new Date(singleVideo.getSnippet().getPublishedAt().getValue()));
if (rId.getKind().equals("youtube#video")) {
Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();
youTubeVideoInfo.setVideoId(rId.getVideoId());
youTubeVideoInfo.setTitle(singleVideo.getSnippet().getTitle());
youTubeVideoInfo.setThumbnailUrl(thumbnail.getUrl());
youTubeVideoInfo.setChannelInfo(getChannelDetailsById(singleVideo.getSnippet().getChannelId()));
youTubeVideoInfo.setVideoStatistics(getVideosStatistics(rId.getVideoId()));
}
youtubeVideoInfoService.save(youTubeVideoInfo);
} else {
System.out.println("Video Already exists... ");
}
}
}
private YoutubeChannelInfo getChannelDetailsById(String channelId) throws IOException {
YouTube.Channels.List channels = youtube.channels().list("snippet, statistics");
YoutubeChannelInfo youtubeChannelInfo = new YoutubeChannelInfo();
youtubeChannelInfo.setChannelId(channelId);
channels.setId(channelId);
ChannelListResponse channelResponse = channels.execute();
Channel c = channelResponse.getItems().get(0);
youtubeChannelInfo.setName(c.getSnippet().getTitle());
youtubeChannelInfo.setSubscriptionCount(c.getStatistics().getSubscriberCount().longValue());
YoutubeChannelInfo channelInfo = youtubeChannelService.getByChannelId(channelId);
if (channelInfo == null) {
youtubeChannelService.save(youtubeChannelInfo);
} else {
return channelInfo;
}
return youtubeChannelInfo;
}
public YoutubeVideoStatistics getVideosStatistics(String id) throws IOException {
YouTube.Videos.List list = youtube.videos().list("statistics");
list.setId(id);
Video v = list.execute().getItems().get(0);
YoutubeVideoStatistics statistics = new YoutubeVideoStatistics();
statistics.setVideoId(id);
statistics.setLikeCount(v.getStatistics().getLikeCount() !=null ? v.getStatistics().getLikeCount().longValue():0);
statistics.setDislikeCount(v.getStatistics().getDislikeCount() != null ? v.getStatistics().getDislikeCount().longValue():0);
statistics.setFavouriteCount(v.getStatistics().getFavoriteCount() != null ? v.getStatistics().getFavoriteCount().longValue():0);
statistics.setCommentCount(v.getStatistics().getCommentCount() != null ? v.getStatistics().getCommentCount().longValue() : 0);
statistics.setViewCount(v.getStatistics().getViewCount() != null ? v.getStatistics().getViewCount().longValue() : 0);
youtubeVideoStatService.save(statistics);
return statistics;
}
public YouTubeVideoInfo getCoontentDetails(String id, YouTubeVideoInfo youTubeVideoInfo) throws IOException {
YouTube.Videos.List list = youtube.videos().list("contentDetails");
list.setId(id);
Video v = list.execute().getItems().get(0);
youTubeVideoInfo.setVideoDefinition(v.getContentDetails().getDefinition());
youTubeVideoInfo.setVideoCaption(v.getContentDetails().getCaption());
youTubeVideoInfo.setVideoprojection(v.getContentDetails().getProjection());
youTubeVideoInfo.setCountryRestricted(v.getContentDetails().getCountryRestriction().toPrettyString());
return youTubeVideoInfo;
}
} | 40.826667 | 136 | 0.674069 |
7320f1eff9392751400661c4586ef49162ecd02c | 207 |
public class ExercicioSeis {
public static void main(String[] args) {
int[] v = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };
for(int i = 0; i < v.length; i++) {
System.out.println(v[i]);
}
}
}
| 17.25 | 54 | 0.541063 |
a04e79d3cad56e931be14a372288964ce6620aa7 | 619 | package jp.spring.boot.algolearn.teacher.form;
import java.util.List;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 先生用コースForm(course form for teacher).
* @author tejc999999
*/
@Data
@NoArgsConstructor
public class CourseForm {
/**
* コースID(course id).
*/
private String id;
/**
* コース名(course name).
*/
private String name;
/**
* 所属クラスIDリスト(affiliated class list).
*/
private List<String> classCheckedList;
/**
* 所属ユーザIDリスト(affiliated user list).
*/
private List<String> userCheckedList;
}
| 17.194444 | 47 | 0.599354 |
2b4f25b11f07571205ae8029538abe43bd7e1e70 | 248 | /*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.instrumentation.iface;
public interface SampleSuperInterfaceObject {
int getOtherNumber();
}
| 16.533333 | 64 | 0.721774 |
d497efeb92d3db354dba9e451cad554dfc543af1 | 793 | package io.kyberorg.yalsee.redis.pubsub;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Service;
/**
* Service that sends messages to Yalsee Application Channel in Redis aka Publisher.
*/
@RequiredArgsConstructor
@Service
public class RedisMessageSender {
private final RedisTemplate<String, YalseeMessage> redisTemplate;
private final ChannelTopic topic;
/**
* Sends {@link YalseeMessage} to our channel in Redis.
*
* @param message valid {@link YalseeMessage} to send.
*/
public void sendMessage(final YalseeMessage message) {
redisTemplate.convertAndSend(topic.getTopic(), message);
}
}
| 29.37037 | 84 | 0.757881 |
571d57a3bafba8d1b3ea9ffba1cef4a8cd910e27 | 2,258 | package at.sms.business.sdk.http.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import at.sms.business.api.domain.sms.SmsSendResponse;
import at.sms.business.sdk.client.util.DeleteUnderscoreAtTheBeginning;
import at.sms.business.sdk.client.util.StatusCodes;
import at.sms.business.sdk.exception.ApiException;
import at.sms.business.sdk.http.ResponseHandler;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Is responsible for parsing and evaluating the response when user sends an
* SmsSendRequest.
*
* @author Sebastian Wilhelm
*
*/
public class SendSmsResponseHandler implements ResponseHandler<SmsSendResponse> {
Logger logger = LoggerFactory.getLogger(this.getClass());
private ApiException responseException = null;
private SmsSendResponse reponseRessource = null;
/**
* Returns the response if it was set. If a exception was set, the
* exception will be thrown.
* @return SmsSendResponse The ressource if the server returned an success-status-code(2000,2001,2002).
* @throws ApiException Will be thrown if the server returned an status-code which indicates an error.
*/
@Override
public SmsSendResponse getResponse() throws ApiException {
if (responseException != null)
throw responseException;
else
return reponseRessource;
}
/**
* Parses and evaluates the response of the SendSmsRequest
*
* @param stringResponse
* The response of the request.
*/
@Override
public void process(String stringResponse) {
GsonBuilder builder = new GsonBuilder();
builder.setFieldNamingStrategy(new DeleteUnderscoreAtTheBeginning());
builder.setPrettyPrinting();
Gson gson = builder.create();
SmsSendResponse response = gson.fromJson(stringResponse,
SmsSendResponse.class);
switch (response.getStatusCode()) {
case StatusCodes.PARAMETER_MISSING:
responseException = new ApiException(response
.getStatusMessage(), response
.getStatusCode());
break;
case StatusCodes.OK:
case StatusCodes.OK_QUEUED:
case StatusCodes.OK_TEST:
this.reponseRessource = response;
break;
default:
responseException = new ApiException(response
.getStatusMessage(), response
.getStatusCode());
break;
}
}
}
| 25.659091 | 104 | 0.751993 |
2ebd2ffc3e6229218ba91cf9e2c106c07c0c4614 | 1,697 | package Application.Controllers;
import Application.Helpers.Quiz;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
import java.net.URL;
import java.util.ResourceBundle;
/**
* The controller for the 'Quiz Start Screen', where the user selects the difficulty of the quiz.
* @author Group 25:
* - Martin Tiangco, mtia116
* - Yuansheng Zhang, yzhb120
*/
public class Quiz_Start_ScreenController extends Controller implements Initializable {
@FXML private Button _mainMenuButton;
@FXML private Button _startButton;
@FXML private ComboBox _difficulty;
@FXML private String[] _difficultyLevels = {"Easy", "Medium", "Hard"};
private Quiz _quiz;
@Override
public void initialize(URL location, ResourceBundle resources) {
_difficulty.getItems().removeAll(_difficulty.getItems());
_difficulty.getItems().addAll(_difficultyLevels);
_difficulty.getSelectionModel().select(_difficultyLevels[0]);
}
/**
* Creating a new Quiz object and setting its difficulty based on the user's choice
* Load the Quiz Screen
*/
public void handleStart() {
_quiz = new Quiz();
_quiz.setDifficulty(_difficulty.getValue().toString());
Controller controller = loadScreen("Quiz", "/Application/fxml/Quiz_Screen.fxml","");
((Quiz_ScreenController)(controller)).Start();
Stage stage = (Stage)_startButton.getScene().getWindow();
stage.close();
}
/**
* Handles functionality to go back to main menu
*/
public void handleBack() {
Stage stage = (Stage) _mainMenuButton.getScene().getWindow();
stage.close();
}
public Quiz getQuiz() {
return _quiz;
}
}
| 29.258621 | 97 | 0.740719 |
02961562b22b0b836468a7ffd9203946b8ba62ab | 8,554 | /*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.benchmarks.common.providers.dmn;
import org.drools.benchmarks.common.DMNProvider;
public class DecisionTablesDMNProvider implements DMNProvider {
@Override
public String getDMN() {
return getDMN(1);
}
@Override
public String getDMN(int numberOfElements) {
final StringBuilder dmnBuilder = new StringBuilder();
dmnBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
dmnBuilder.append("<definitions id=\"decision-table-id\" name=\"decision-table-name\"\n");
dmnBuilder.append(" namespace=\"https://github.com/kiegroup/kie-dmn\"\n");
dmnBuilder.append("xmlns=\"http://www.omg.org/spec/DMN/20180521/MODEL/\" ");
dmnBuilder.append("xmlns:triso=\"http://www.trisotech.com/2015/triso/modeling\" ");
dmnBuilder.append("xmlns:dmndi=\"http://www.omg.org/spec/DMN/20180521/DMNDI/\" ");
dmnBuilder.append("xmlns:di=\"http://www.omg.org/spec/DMN/20180521/DI/\" ");
dmnBuilder.append("xmlns:dc=\"http://www.omg.org/spec/DMN/20180521/DC/\" ");
dmnBuilder.append("xmlns:trisodmn=\"http://www.trisotech.com/2016/triso/dmn\" ");
dmnBuilder.append("xmlns:feel=\"http://www.omg.org/spec/DMN/20180521/FEEL/\" ");
dmnBuilder.append("xmlns:tc=\"http://www.omg.org/spec/DMN/20160719/testcase\" ");
dmnBuilder.append("xmlns:drools=\"http://www.drools.org/kie/dmn/1.1\" ");
dmnBuilder.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
dmnBuilder.append("xmlns:rss=\"http://purl.org/rss/2.0/\" ");
dmnBuilder.append(" > \n");
for (int i = 0; i < numberOfElements; i++) {
dmnBuilder.append(" <!-- " + i + " -->\n");
dmnBuilder.append(" <inputData id=\"leftInput_" + i + "\" name=\"leftInput_" + i + "\">\n");
dmnBuilder.append(" <variable name=\"leftInput_" + i + "\" id=\"leftInput_" + i + "var\" typeRef=\"string\"/>\n");
dmnBuilder.append(" </inputData>\n");
dmnBuilder.append(" <inputData id=\"rightInput_" + i + "\" name=\"rightInput_" + i + "\">\n");
dmnBuilder.append(" <variable name=\"rightInput_" + i + "\" id=\"rightInput_" + i + "var\" typeRef=\"string\"/>\n");
dmnBuilder.append(" </inputData>\n");
dmnBuilder.append(" <decision id=\"myDecision_" + i + "\" name=\"myDecision_" + i + "\">\n");
dmnBuilder.append(" <variable name=\"myDecision_" + i + "\" id=\"myDecision_" + i + "var\" typeRef=\"string\"/>\n");
dmnBuilder.append(" <informationRequirement >\n");
dmnBuilder.append(" <requiredInput href=\"#leftInput_" + i + "\"/>\n");
dmnBuilder.append(" </informationRequirement>\n");
dmnBuilder.append(" <informationRequirement >\n");
dmnBuilder.append(" <requiredInput href=\"#rightInput_" + i + "\"/>\n");
dmnBuilder.append(" </informationRequirement>\n");
dmnBuilder.append(" <decisionTable hitPolicy=\"UNIQUE\" outputLabel=\"myDecision_" + i + "\" typeRef=\"string\">\n");
dmnBuilder.append(" <input >\n");
dmnBuilder.append(" <inputExpression typeRef=\"string\">\n");
dmnBuilder.append(" <text>leftInput_" + i + "</text>\n");
dmnBuilder.append(" </inputExpression>\n");
dmnBuilder.append(" </input>\n");
dmnBuilder.append(" <input >\n");
dmnBuilder.append(" <inputExpression typeRef=\"string\">\n");
dmnBuilder.append(" <text>rightInput_" + i + "</text>\n");
dmnBuilder.append(" </inputExpression>\n");
dmnBuilder.append(" </input>\n");
dmnBuilder.append(" <output />\n");
dmnBuilder.append(" <annotation name=\"Description\"/>\n");
dmnBuilder.append(" <rule >\n");
dmnBuilder.append(" <inputEntry >\n");
dmnBuilder.append(" <text>\"a\"</text>\n");
dmnBuilder.append(" </inputEntry>\n");
dmnBuilder.append(" <inputEntry >\n");
dmnBuilder.append(" <text>-</text>\n");
dmnBuilder.append(" </inputEntry>\n");
dmnBuilder.append(" <outputEntry >\n");
dmnBuilder.append(" <text>\"left A\"</text>\n");
dmnBuilder.append(" </outputEntry>\n");
dmnBuilder.append(" <annotationEntry>\n");
dmnBuilder.append(" <text/>\n");
dmnBuilder.append(" </annotationEntry>\n");
dmnBuilder.append(" </rule>\n");
dmnBuilder.append(" <rule >\n");
dmnBuilder.append(" <inputEntry >\n");
dmnBuilder.append(" <text>-</text>\n");
dmnBuilder.append(" </inputEntry>\n");
dmnBuilder.append(" <inputEntry >\n");
dmnBuilder.append(" <text>\"a\"</text>\n");
dmnBuilder.append(" </inputEntry>\n");
dmnBuilder.append(" <outputEntry >\n");
dmnBuilder.append(" <text>\"right A\"</text>\n");
dmnBuilder.append(" </outputEntry>\n");
dmnBuilder.append(" <annotationEntry>\n");
dmnBuilder.append(" <text/>\n");
dmnBuilder.append(" </annotationEntry>\n");
dmnBuilder.append(" </rule>\n");
dmnBuilder.append(" <rule >\n");
dmnBuilder.append(" <inputEntry >\n");
dmnBuilder.append(" <text>not(\"a\")</text>\n");
dmnBuilder.append(" </inputEntry>\n");
dmnBuilder.append(" <inputEntry >\n");
dmnBuilder.append(" <text>not(\"a\")</text>\n");
dmnBuilder.append(" </inputEntry>\n");
dmnBuilder.append(" <outputEntry >\n");
dmnBuilder.append(" <text>\"A not found\"</text>\n");
dmnBuilder.append(" </outputEntry>\n");
dmnBuilder.append(" <annotationEntry>\n");
dmnBuilder.append(" <text/>\n");
dmnBuilder.append(" </annotationEntry>\n");
dmnBuilder.append(" </rule>\n");
dmnBuilder.append(" </decisionTable>\n");
dmnBuilder.append(" </decision>\n");
dmnBuilder.append(" <decision id=\"layer_myDecision_" + i + "\" name=\"layer_myDecision_" + i + "\">\n");
dmnBuilder.append(" <variable name=\"layer_myDecision_" + i + "\" id=\"layer_myDecision_" + i + "var\" typeRef=\"string\"/>\n");
dmnBuilder.append(" <informationRequirement >\n");
dmnBuilder.append(" <requiredDecision href=\"#myDecision_" + i + "\"/>\n");
dmnBuilder.append(" </informationRequirement>\n");
dmnBuilder.append(" <literalExpression typeRef=\"string\" >\n");
dmnBuilder.append(" <text>\"decision was: \" + myDecision_" + i + "</text>\n");
dmnBuilder.append(" </literalExpression>\n");
dmnBuilder.append(" </decision>");
}
dmnBuilder.append("</definitions>");
return dmnBuilder.toString();
}
}
| 61.1 | 147 | 0.509002 |
6d4524097a90322c16f2b46cf0eef6b948da36e6 | 21,651 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Igor Bukanov
* David P. Caldwell <inonit@inonit.com>
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.xmlimpl;
import java.io.Serializable;
import org.mozilla.javascript.*;
import org.mozilla.javascript.xml.*;
public final class XMLLibImpl extends XMLLib implements Serializable {
// TODO Document that this only works with JDK 1.5 or backport its
// features to earlier versions
private static final long serialVersionUID = 1L;
//
// EXPERIMENTAL Java interface
//
/**
This experimental interface is undocumented.
*/
public static org.w3c.dom.Node toDomNode(Object xmlObject) {
// Could return DocumentFragment for XMLList
// Probably a single node for XMLList with one element
if (xmlObject instanceof XML) {
return ((XML)xmlObject).toDomNode();
} else {
throw new IllegalArgumentException("xmlObject is not an XML object in JavaScript.");
}
}
public static void init(Context cx, Scriptable scope, boolean sealed) {
XMLLibImpl lib = new XMLLibImpl(scope);
XMLLib bound = lib.bindToScope(scope);
if (bound == lib) {
lib.exportToScope(sealed);
}
}
private Scriptable globalScope;
private XML xmlPrototype;
private XMLList xmlListPrototype;
private Namespace namespacePrototype;
private QName qnamePrototype;
private XmlProcessor options = new XmlProcessor();
private XMLLibImpl(Scriptable globalScope) {
this.globalScope = globalScope;
}
/** @deprecated */
QName qnamePrototype() {
return qnamePrototype;
}
/** @deprecated */
Scriptable globalScope() {
return globalScope;
}
XmlProcessor getProcessor() {
return options;
}
private void exportToScope(boolean sealed) {
xmlPrototype = newXML(XmlNode.createText(options, ""));
xmlListPrototype = newXMLList();
namespacePrototype = Namespace.create(this.globalScope, null, XmlNode.Namespace.GLOBAL);
qnamePrototype = QName.create(this, this.globalScope, null, XmlNode.QName.create(XmlNode.Namespace.create(""), ""));
xmlPrototype.exportAsJSClass(sealed);
xmlListPrototype.exportAsJSClass(sealed);
namespacePrototype.exportAsJSClass(sealed);
qnamePrototype.exportAsJSClass(sealed);
}
/** @deprecated */
XMLName toAttributeName(Context cx, Object nameValue) {
if (nameValue instanceof XMLName) {
// TODO Will this always be an XMLName of type attribute name?
return (XMLName)nameValue;
} else if (nameValue instanceof QName) {
return XMLName.create( ((QName)nameValue).getDelegate(), true, false );
} else if (nameValue instanceof Boolean
|| nameValue instanceof Number
|| nameValue == Undefined.instance
|| nameValue == null) {
throw badXMLName(nameValue);
} else {
// TODO Not 100% sure that putting these in global namespace is the right thing to do
String localName = null;
if (nameValue instanceof String) {
localName = (String)nameValue;
} else {
localName = ScriptRuntime.toString(nameValue);
}
if (localName != null && localName.equals("*")) localName = null;
return XMLName.create(XmlNode.QName.create(XmlNode.Namespace.create(""), localName), true, false);
}
}
private static RuntimeException badXMLName(Object value)
{
String msg;
if (value instanceof Number) {
msg = "Can not construct XML name from number: ";
} else if (value instanceof Boolean) {
msg = "Can not construct XML name from boolean: ";
} else if (value == Undefined.instance || value == null) {
msg = "Can not construct XML name from ";
} else {
throw new IllegalArgumentException(value.toString());
}
return ScriptRuntime.typeError(msg+ScriptRuntime.toString(value));
}
XMLName toXMLNameFromString(Context cx, String name) {
return XMLName.create( getDefaultNamespaceURI(cx), name );
}
/** @deprecated */
XMLName toXMLName(Context cx, Object nameValue) {
XMLName result;
if (nameValue instanceof XMLName) {
result = (XMLName)nameValue;
} else if (nameValue instanceof QName) {
QName qname = (QName)nameValue;
result = XMLName.formProperty(qname.uri(), qname.localName());
} else if (nameValue instanceof String) {
result = toXMLNameFromString(cx, (String)nameValue);
} else if (nameValue instanceof Boolean
|| nameValue instanceof Number
|| nameValue == Undefined.instance
|| nameValue == null) {
throw badXMLName(nameValue);
} else {
String name = ScriptRuntime.toString(nameValue);
result = toXMLNameFromString(cx, name);
}
return result;
}
/**
* If value represents Uint32 index, make it available through
* ScriptRuntime.lastUint32Result(cx) and return null.
* Otherwise return the same value as toXMLName(cx, value).
*/
XMLName toXMLNameOrIndex(Context cx, Object value)
{
XMLName result;
if (value instanceof XMLName) {
result = (XMLName)value;
} else if (value instanceof String) {
String str = (String)value;
long test = ScriptRuntime.testUint32String(str);
if (test >= 0) {
ScriptRuntime.storeUint32Result(cx, test);
result = null;
} else {
result = toXMLNameFromString(cx, str);
}
} else if (value instanceof Number) {
double d = ((Number)value).doubleValue();
long l = (long)d;
if (l == d && 0 <= l && l <= 0xFFFFFFFFL) {
ScriptRuntime.storeUint32Result(cx, l);
result = null;
} else {
throw badXMLName(value);
}
} else if (value instanceof QName) {
QName qname = (QName)value;
String uri = qname.uri();
boolean number = false;
result = null;
if (uri != null && uri.length() == 0) {
// Only in this case qname.toString() can resemble uint32
long test = ScriptRuntime.testUint32String(uri);
if (test >= 0) {
ScriptRuntime.storeUint32Result(cx, test);
number = true;
}
}
if (!number) {
result = XMLName.formProperty(uri, qname.localName());
}
} else if (value instanceof Boolean
|| value == Undefined.instance
|| value == null)
{
throw badXMLName(value);
} else {
String str = ScriptRuntime.toString(value);
long test = ScriptRuntime.testUint32String(str);
if (test >= 0) {
ScriptRuntime.storeUint32Result(cx, test);
result = null;
} else {
result = toXMLNameFromString(cx, str);
}
}
return result;
}
Object addXMLObjects(Context cx, XMLObject obj1, XMLObject obj2)
{
XMLList listToAdd = newXMLList();
if (obj1 instanceof XMLList) {
XMLList list1 = (XMLList)obj1;
if (list1.length() == 1) {
listToAdd.addToList(list1.item(0));
} else {
// Might be xmlFragment + xmlFragment + xmlFragment + ...;
// then the result will be an XMLList which we want to be an
// rValue and allow it to be assigned to an lvalue.
listToAdd = newXMLListFrom(obj1);
}
} else {
listToAdd.addToList(obj1);
}
if (obj2 instanceof XMLList) {
XMLList list2 = (XMLList)obj2;
for (int i = 0; i < list2.length(); i++) {
listToAdd.addToList(list2.item(i));
}
} else if (obj2 instanceof XML) {
listToAdd.addToList(obj2);
}
return listToAdd;
}
private Ref xmlPrimaryReference(Context cx, XMLName xmlName, Scriptable scope) {
XMLObjectImpl xmlObj;
XMLObjectImpl firstXml = null;
for (;;) {
// XML object can only present on scope chain as a wrapper
// of XMLWithScope
if (scope instanceof XMLWithScope) {
xmlObj = (XMLObjectImpl)scope.getPrototype();
if (xmlObj.hasXMLProperty(xmlName)) {
break;
}
if (firstXml == null) {
firstXml = xmlObj;
}
}
scope = scope.getParentScope();
if (scope == null) {
xmlObj = firstXml;
break;
}
}
// xmlObj == null corresponds to undefined as the target of
// the reference
if (xmlObj != null) {
xmlName.initXMLObject(xmlObj);
}
return xmlName;
}
Namespace castToNamespace(Context cx, Object namespaceObj) {
return this.namespacePrototype.castToNamespace(namespaceObj);
}
private String getDefaultNamespaceURI(Context cx) {
return getDefaultNamespace(cx).uri();
}
Namespace newNamespace(String uri) {
return this.namespacePrototype.newNamespace(uri);
}
Namespace getDefaultNamespace(Context cx) {
if (cx == null) {
cx = Context.getCurrentContext();
if (cx == null) {
return namespacePrototype;
}
}
Object ns = ScriptRuntime.searchDefaultNamespace(cx);
if (ns == null) {
return namespacePrototype;
} else {
if (ns instanceof Namespace) {
return (Namespace)ns;
} else {
// TODO Clarify or remove the following comment
// Should not happen but for now it could
// due to bad searchDefaultNamespace implementation.
return namespacePrototype;
}
}
}
Namespace[] createNamespaces(XmlNode.Namespace[] declarations) {
Namespace[] rv = new Namespace[declarations.length];
for (int i=0; i<declarations.length; i++) {
rv[i] = this.namespacePrototype.newNamespace(declarations[i].getPrefix(), declarations[i].getUri());
}
return rv;
}
// See ECMA357 13.3.2
QName constructQName(Context cx, Object namespace, Object name) {
return this.qnamePrototype.constructQName(this, cx, namespace, name);
}
QName newQName(String uri, String localName, String prefix) {
return this.qnamePrototype.newQName(this, uri, localName, prefix);
}
QName constructQName(Context cx, Object nameValue) {
// return constructQName(cx, Undefined.instance, nameValue);
return this.qnamePrototype.constructQName(this, cx, nameValue);
}
QName castToQName(Context cx, Object qnameValue) {
return this.qnamePrototype.castToQName(this, cx, qnameValue);
}
QName newQName(XmlNode.QName qname) {
return QName.create(this, this.globalScope, this.qnamePrototype, qname);
}
XML newXML(XmlNode node) {
return new XML(this, this.globalScope, this.xmlPrototype, node);
}
/**
@deprecated I believe this can be replaced by ecmaToXml below.
*/
final XML newXMLFromJs(Object inputObject) {
String frag;
if (inputObject == null || inputObject == Undefined.instance) {
frag = "";
} else if (inputObject instanceof XMLObjectImpl) {
// todo: faster way for XMLObjects?
frag = ((XMLObjectImpl) inputObject).toXMLString();
} else {
frag = ScriptRuntime.toString(inputObject);
}
if (frag.trim().startsWith("<>")) {
throw ScriptRuntime.typeError("Invalid use of XML object anonymous tags <></>.");
}
if (frag.indexOf("<") == -1) {
// Solo text node
return newXML(XmlNode.createText(options, frag));
}
return parse(frag);
}
private XML parse(String frag) {
try {
return newXML(XmlNode.createElement(options, getDefaultNamespaceURI(Context.getCurrentContext()), frag));
} catch (org.xml.sax.SAXException e) {
throw ScriptRuntime.typeError("Cannot parse XML: " + e.getMessage());
}
}
final XML ecmaToXml(Object object) {
// See ECMA357 10.3
if (object == null || object == Undefined.instance) throw ScriptRuntime.typeError("Cannot convert " + object + " to XML");
if (object instanceof XML) return (XML)object;
if (object instanceof XMLList) {
XMLList list = (XMLList)object;
if (list.getXML() != null) {
return list.getXML();
} else {
throw ScriptRuntime.typeError("Cannot convert list of >1 element to XML");
}
}
// TODO Technically we should fail on anything except a String, Number or Boolean
// See ECMA357 10.3
// Extension: if object is a DOM node, use that to construct the XML
// object.
if (object instanceof Wrapper) {
object = ((Wrapper) object).unwrap();
}
if (object instanceof org.w3c.dom.Node) {
org.w3c.dom.Node node = (org.w3c.dom.Node) object;
return newXML(XmlNode.createElementFromNode(node));
}
// Instead we just blindly cast to a String and let them convert anything.
String s = ScriptRuntime.toString(object);
// TODO Could this get any uglier?
if (s.length() > 0 && s.charAt(0) == '<') {
return parse(s);
} else {
return newXML(XmlNode.createText(options, s));
}
}
final XML newTextElementXML(XmlNode reference, XmlNode.QName qname, String value) {
return newXML(XmlNode.newElementWithText(options, reference, qname, value));
}
XMLList newXMLList() {
return new XMLList(this, this.globalScope, this.xmlListPrototype);
}
final XMLList newXMLListFrom(Object inputObject) {
XMLList rv = newXMLList();
if (inputObject == null || inputObject instanceof Undefined) {
return rv;
} else if (inputObject instanceof XML) {
XML xml = (XML) inputObject;
rv.getNodeList().add(xml);
return rv;
} else if (inputObject instanceof XMLList) {
XMLList xmll = (XMLList) inputObject;
rv.getNodeList().add(xmll.getNodeList());
return rv;
} else {
String frag = ScriptRuntime.toString(inputObject).trim();
if (!frag.startsWith("<>")) {
frag = "<>" + frag + "</>";
}
frag = "<fragment>" + frag.substring(2);
if (!frag.endsWith("</>")) {
throw ScriptRuntime.typeError("XML with anonymous tag missing end anonymous tag");
}
frag = frag.substring(0, frag.length() - 3) + "</fragment>";
XML orgXML = newXMLFromJs(frag);
// Now orphan the children and add them to our XMLList.
XMLList children = orgXML.children();
for (int i = 0; i < children.getNodeList().length(); i++) {
// Copy here is so that they'll be orphaned (parent() will be undefined)
rv.getNodeList().add(((XML) children.item(i).copy()));
}
return rv;
}
}
XmlNode.QName toNodeQName(Context cx, Object namespaceValue, Object nameValue) {
// This is duplication of constructQName(cx, namespaceValue, nameValue)
// but for XMLName
String localName;
if (nameValue instanceof QName) {
QName qname = (QName)nameValue;
localName = qname.localName();
} else {
localName = ScriptRuntime.toString(nameValue);
}
XmlNode.Namespace ns;
if (namespaceValue == Undefined.instance) {
if ("*".equals(localName)) {
ns = null;
} else {
ns = getDefaultNamespace(cx).getDelegate();
}
} else if (namespaceValue == null) {
ns = null;
} else if (namespaceValue instanceof Namespace) {
ns = ((Namespace)namespaceValue).getDelegate();
} else {
ns = this.namespacePrototype.constructNamespace(namespaceValue).getDelegate();
}
if (localName != null && localName.equals("*")) localName = null;
return XmlNode.QName.create(ns, localName);
}
XmlNode.QName toNodeQName(Context cx, String name, boolean attribute) {
XmlNode.Namespace defaultNamespace = getDefaultNamespace(cx).getDelegate();
if (name != null && name.equals("*")) {
return XmlNode.QName.create(null, null);
} else {
if (attribute) {
return XmlNode.QName.create(XmlNode.Namespace.GLOBAL, name);
} else {
return XmlNode.QName.create(defaultNamespace, name);
}
}
}
/**
@deprecated Too general; this should be split into overloaded methods.
Is that possible?
*/
XmlNode.QName toNodeQName(Context cx, Object nameValue, boolean attribute) {
if (nameValue instanceof XMLName) {
return ((XMLName)nameValue).toQname();
} else if (nameValue instanceof QName) {
QName qname = (QName)nameValue;
return qname.getDelegate();
} else if (
nameValue instanceof Boolean
|| nameValue instanceof Number
|| nameValue == Undefined.instance
|| nameValue == null
) {
throw badXMLName(nameValue);
} else {
String local = null;
if (nameValue instanceof String) {
local = (String)nameValue;
} else {
local = ScriptRuntime.toString(nameValue);
}
return toNodeQName(cx, local, attribute);
}
}
//
// Override methods from XMLLib
//
public boolean isXMLName(Context _cx, Object nameObj) {
return XMLName.accept(nameObj);
}
public Object toDefaultXmlNamespace(Context cx, Object uriValue) {
return this.namespacePrototype.constructNamespace(uriValue);
}
public String escapeTextValue(Object o) {
return options.escapeTextValue(o);
}
public String escapeAttributeValue(Object o) {
return options.escapeAttributeValue(o);
}
public Ref nameRef(Context cx, Object name, Scriptable scope, int memberTypeFlags) {
if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) == 0) {
// should only be called foir cases like @name or @[expr]
throw Kit.codeBug();
}
XMLName xmlName = toAttributeName(cx, name);
return xmlPrimaryReference(cx, xmlName, scope);
}
public Ref nameRef(Context cx, Object namespace, Object name, Scriptable scope, int memberTypeFlags) {
XMLName xmlName = XMLName.create(toNodeQName(cx, namespace, name), false, false);
// No idea what is coming in from the parser in this case; is it detecting the "@"?
if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0) {
if (!xmlName.isAttributeName()) {
xmlName.setAttributeName();
}
}
return xmlPrimaryReference(cx, xmlName, scope);
}
}
| 35.668863 | 130 | 0.583437 |
32729b506deef168a123fc329923889ddc1e88ec | 350 | package cn.com.tsjx.common.config.file.protocol;
/**
* @author <a href="mailto:wangyuxuan@dangdang.com">Yuxuan Wang</a>
*
*/
public final class ProtocolNames {
public static String FILE = "file";
public static String CLASSPATH = "classpath";
public static String HTTP = "http";
public static String HTTPS = "https";
}
| 20.588235 | 68 | 0.668571 |
271d6c31494eee8a4eb3718fb86afba9389a190b | 261 | package com.google.sampling.experiential.dao;
import java.sql.SQLException;
import com.google.sampling.experiential.server.PacoId;
public interface CSExternStringInputDao {
PacoId getTextAndCreate(String label, boolean createOption) throws SQLException;
}
| 26.1 | 82 | 0.835249 |
34a53755b6470e182c7644de2f34b803f47c1f8c | 1,036 | package models;
public class CellErrorJSON implements Comparable<CellErrorJSON> {
private String column = "";
private String row = "";
private String error = "";
public CellErrorJSON(final String column, final String row, final String error) {
this.column = column;
this.row = row;
this.error = error;
}
public String getColumn() {
return column;
}
public String getRow() {
return row;
}
// public String getErrorName() {
// return CellError.values()[Integer.parseInt(error) - 1].getSingularErrorName();
// }
//
// public String getErrorDescription(){
//
// return CellError.values()[Integer.parseInt(error)-1].getErrorDescription();
// }
@Override
public int compareTo(final CellErrorJSON e) {
final int thisCol = Integer.parseInt(this.column);
final int theirCol = Integer.parseInt(e.getColumn());
// int thisRow = Integer.parseInt(this.row);
// int theirRow =
//
if(thisCol < theirCol){
return -1;
}else if(thisCol > theirCol){
return 1;
}else{
return 0;
}
}
}
| 21.583333 | 82 | 0.67471 |
9324bbda88cdbdc52e9333892595145e545792d9 | 973 | package com.nr.agent.instrumentation.r2dbc;
import com.newrelic.api.agent.Trace;
import io.r2dbc.spi.Connection;
import reactor.core.publisher.Mono;
public class R2dbcTestUtils {
@Trace(dispatcher = true)
public static void basicRequests(Connection connection) {
Mono.from(connection.createStatement("INSERT INTO USERS(id, first_name, last_name, age) VALUES(1, 'Max', 'Power', 30)").execute()).block();
Mono.from(connection.createStatement("SELECT * FROM USERS WHERE last_name='Power'").execute()).block();
Mono.from(connection.createStatement("UPDATE USERS SET age = 36 WHERE last_name = 'Power'").execute()).block();
Mono.from(connection.createStatement("SELECT * FROM USERS WHERE last_name='Power'").execute()).block();
Mono.from(connection.createStatement("DELETE FROM USERS WHERE last_name = 'Power'").execute()).block();
Mono.from(connection.createStatement("SELECT * FROM USERS").execute()).block();
}
}
| 54.055556 | 147 | 0.716341 |
2f6a291c82e9e5f144fd34ab8e0122c9189d9a9f | 1,151 | package com.ofdbox.core.xmlobj.signature;
import com.ofdbox.core.xmlobj.adapter.StBoxAdapter;
import com.ofdbox.core.xmlobj.adapter.StRefIdAdapter;
import com.ofdbox.core.xmlobj.st.ST_RefID;
import com.ofdbox.core.xmlobj.st.ST_Box;
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@Data
@XmlAccessorType(value = XmlAccessType.FIELD)
public class NStampAnnot {
@NotBlank
@XmlAttribute(name = "ID")
private String id;
@NotNull
@Valid
@XmlJavaTypeAdapter(value = StRefIdAdapter.class)
@XmlAttribute(name = "PageRef")
private ST_RefID pageRef;
@NotNull
@Valid
@XmlJavaTypeAdapter(value = StBoxAdapter.class)
@XmlAttribute(name = "Boundary")
private ST_Box boundary;
@Valid
@XmlJavaTypeAdapter(value = StBoxAdapter.class)
@XmlAttribute(name = "Clip")
private ST_Box clip;
}
| 27.404762 | 61 | 0.765421 |
81ec83938b585311fbb29f3e422c1b61e4dc0364 | 297 | package net.violet.probes;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.OpenDataException;
public interface CacheProbeMBean {
CompositeData getCacheMapSizesStats() throws OpenDataException;
CompositeData getCachePulseStats() throws OpenDataException;
}
| 24.75 | 64 | 0.851852 |
8213540793ca88cbb42646a391706b58f148adc7 | 948 | package ai.giskard.repository;
import lombok.NonNull;
import org.mapstruct.Named;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
/**
* A standard JpaRepository interface that helps Mapstruct to find an ID-to-T
* mapper method
*/
@NoRepositoryBean
public interface MappableJpaRepository<T, I> extends JpaRepository<T, I> {
/**
* The only goal of overriding getOne method is to mark it by @org.mapstruct.Named
* this will allow to solve Mapstruct ambiguity between getById and getOne
* methods when Mapstruct is looking for a I->T mapping
*/
@Override
@Named("_noop_")
@SuppressWarnings("all")
T getOne(I id);
@Override
@Named("_noop_")
@NonNull
T getById(@NonNull I id);
default T findOneByNullableId(I id) {
if (id == null) {
return null;
}
return getById(id);
}
}
| 26.333333 | 86 | 0.683544 |
a43d403f67f4d8c551a5c1e1d3f67924d2b385af | 2,334 | package com.rbkmoney.dark.api.service;
import com.rbkmoney.damsel.domain.Blocked;
import com.rbkmoney.damsel.domain.PartyStatus;
import com.rbkmoney.damsel.payment_processing.InternalUser;
import com.rbkmoney.damsel.payment_processing.PartyManagementSrv;
import com.rbkmoney.damsel.payment_processing.UserInfo;
import com.rbkmoney.damsel.payment_processing.UserType;
import com.rbkmoney.dark.api.exceptions.client.ForbiddenException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import static com.rbkmoney.dark.api.util.ExceptionUtils.darkApi5xxException;
@Service
@Slf4j
@RequiredArgsConstructor
@SuppressWarnings("ParameterName")
public class PartyManagementService {
private final PartyManagementSrv.Iface partyManagementClient;
private final KeycloakService keycloakService;
private final UserInfo userInfo = new UserInfo("dark-api", UserType.internal_user(new InternalUser()));
public void checkStatus() {
checkStatus(null, keycloakService.getPartyId());
}
public void checkStatus(String xRequestId) {
checkStatus(xRequestId, keycloakService.getPartyId());
}
private void checkStatus(String xRequestId, String partyId) {
log.info("Trying to get request on party-management service for party-status, xRequestId='{}', partyId='{}'",
xRequestId, partyId);
PartyStatus status = getPartyStatus(xRequestId, partyId);
if (status.getBlocking().isSetBlocked()) {
Blocked blocked = status.getBlocking().getBlocked();
throw new ForbiddenException(
String.format("Party is blocked xRequestId=%s, since=%s, reason=%s",
xRequestId, blocked.getSince(), blocked.getReason())
);
}
log.info(
"Request has been got on party-management service, party-status=unblocked, " +
"xRequestId='{}', partyId='{}'", xRequestId, partyId);
}
private PartyStatus getPartyStatus(String xRequestId, String partyId) {
try {
return partyManagementClient.getStatus(userInfo, partyId);
} catch (Exception ex) {
throw darkApi5xxException("party-management", "getStatus", xRequestId, ex);
}
}
}
| 37.645161 | 117 | 0.705227 |
6a5e0388ff7ec3807ffc46cec5a3e5c3fc5c8bf9 | 3,099 | /*
* [New BSD License]
* Copyright (c) 2011-2012, Brackit Project Team <info@brackit.org>
* 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 Brackit Project Team 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 org.brackit.server.tx.locking.util;
import org.brackit.server.node.XTCdeweyID;
import org.brackit.server.tx.locking.LockName;
import org.brackit.server.tx.locking.services.EdgeLockService.Edge;
public class DeweyIDLockNameBuilder implements LockNameBuilder {
class DeweyIDLockName implements LockName {
private final String name;
public DeweyIDLockName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
return ((o instanceof DeweyIDLockName) && (((DeweyIDLockName) o).name
.equals(name)));
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return this.name;
}
}
@Override
public LockName edgeLockName(XTCdeweyID deweyID, Edge edge, String name) {
return new DeweyIDLockName(deweyID.toString() + "@" + edge + "=" + name);
}
@Override
public LockName[] edgeLockNamePath(XTCdeweyID deweyID, Edge edge,
String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public LockName nodeLockName(XTCdeweyID deweyID) {
return new DeweyIDLockName(deweyID.toString());
}
@Override
public LockName[] nodeLockNamePath(XTCdeweyID deweyID) {
LockName[] lockNames = new LockName[deweyID.getLevel() - 1];
for (int i = lockNames.length - 1; i >= 0; i--) {
lockNames[i] = new DeweyIDLockName(deweyID.toString());
deweyID = deweyID.getParent();
}
return lockNames;
}
}
| 35.215909 | 83 | 0.736689 |
5d5638de8361a93af16622ec94ee9037d0ef7173 | 15,103 | package com.zebra.windevmobilemxwrapper;
// Android / Java imports
import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import java.io.StringReader;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.symbol.emdk.EMDKBase;
import com.symbol.emdk.EMDKException;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.ProfileManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.EMDKManager.EMDKListener;
import com.symbol.emdk.EMDKManager.StatusListener;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
public class WindevMobileMXFacade {
public interface IAppelProcedureWL
{
void appelProcedureWLSS(String param1, String param2);
void appelProcedureWLSSS(String param1, String param2, String param3);
void appelProcedureWLSSSS(String param1, String param2, String param3, String param4);
}
public interface IActivityRetriever
{
Activity getActivity();
}
public class ErrorHolder
{
// Provides the error type for characteristic-error
public String sErrorType = "";
// Provides the parm name for parm-error
public String sParmName = "";
// Provides error description
public String sErrorDescription = "";
}
// Membres
private String TAG = "WindevMobileMXFacade";
// Interface pour executer les procedures WL
// Cet objet doit être implémenté dans la collection de procedures WL
private IAppelProcedureWL mAppelProcedureWL = null;
// Interface pour récupérer l'activité courante de l'application
// Cet objet doit être implémenté dans la collection de procédures WL
private IActivityRetriever mActivityRetriever = null;
// Procedure WL appelée en cas d'erreur
private String msErrorCallback = "";
// Procedure WL appelée en cas de succès
private String msSuccesCallback = "";
// Le contenu du profil
private String msProfileData = "";
//Declare a variable to store ProfileManager object
private ProfileManager mProfileManager = null;
//Declare a variable to store EMDKManager object
private EMDKManager mEMDKManager = null;
// An ArrayList that will contains errors if we find some
private ArrayList<ErrorHolder> mErrors = new ArrayList<>();
// Provides full error description string
public String msErrorString = "";
// Status Listener implementation (ensure that we retrieve the profile manager asynchronously
StatusListener mStatusListener = new StatusListener() {
@Override
public void onStatus(EMDKManager.StatusData statusData, EMDKBase emdkBase) {
if(statusData.getResult() == EMDKResults.STATUS_CODE.SUCCESS)
{
mProfileManager = (ProfileManager)emdkBase;
if(msSuccesCallback != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSS(msSuccesCallback, "Profile Manager récupéré avec succès");
}
}
}
else
{
String errorMessage = "Erreur lors de la récupération du profile manager: " + getResultCode(statusData.getResult());
logMessage(errorMessage);
if(msErrorCallback != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSSS(msErrorCallback, "Exception lors de la récupération du profile manager: ", getResultCode(statusData.getResult()));
}
}
}
}
};
// EMDKListener implementation
EMDKListener mEMDKListener = new EMDKListener() {
@Override
public void onOpened(EMDKManager emdkManager) {
mEMDKManager = emdkManager;
if(mProfileManager == null)
{
try {
emdkManager.getInstanceAsync(EMDKManager.FEATURE_TYPE.PROFILE, mStatusListener);
} catch (EMDKException e) {
if(msErrorCallback != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSSS(msErrorCallback, "Exception lors de la récupération du profile manager: ", e.getMessage());
}
}
logMessage("Erreur lors de la récupération du profile manager: " + e.getMessage());
}
}
else
{
if(msSuccesCallback != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSS(msSuccesCallback, "Profile Manager déjà initialisé");
}
}
}
}
@Override
public void onClosed() {
if(mProfileManager != null)
{
mProfileManager = null;
}
//This callback will be issued when the EMDK closes unexpectedly.
if (mEMDKManager != null) {
mEMDKManager.release();
mEMDKManager = null;
}
}
};
public WindevMobileMXFacade(IAppelProcedureWL aAppelProcedureWLInterface, IActivityRetriever aActivityRetrieverInterface)
{
mAppelProcedureWL = aAppelProcedureWLInterface;
mActivityRetriever = aActivityRetrieverInterface;
}
private Activity getActivity()
{
if(mActivityRetriever != null)
{
return mActivityRetriever.getActivity();
}
return null;
}
private void logMessage(String message)
{
Log.d(TAG, message);
}
private String getResultCode(EMDKResults.STATUS_CODE aStatusCode)
{
switch (aStatusCode)
{
case FAILURE:
return "FAILURE";
case NULL_POINTER:
return "NULL_POINTER";
case EMPTY_PROFILENAME:
return "EMPTY_PROFILENAME";
case EMDK_NOT_OPENED:
return "EMDK_NOT_OPENED";
case CHECK_XML:
return "CHECK_XML";
case PREVIOUS_REQUEST_IN_PROGRESS:
return "PREVIOUS_REQUEST_IN_PROGRESS";
case PROCESSING:
return "PROCESSING";
case NO_DATA_LISTENER:
return "NO_DATA_LISTENER";
case FEATURE_NOT_READY_TO_USE:
return "FEATURE_NOT_READY_TO_USE";
case FEATURE_NOT_SUPPORTED:
return "FEATURE_NOT_SUPPORTED";
case UNKNOWN:
default:
return "UNKNOWN";
}
}
public void initialize(final String aCallbackSucces, final String aCallbackError)
{
msErrorCallback = aCallbackError;
msSuccesCallback = aCallbackSucces;
if(mEMDKManager == null)
{
EMDKResults results = null;
try
{
//The EMDKManager object will be created and returned in the callback.
results = EMDKManager.getEMDKManager(getActivity().getApplicationContext(), mEMDKListener);
}
catch(Exception e)
{
if(msErrorCallback != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSSS(msErrorCallback, "Erreur lors de la recupération de l'EMDKManager", e.getMessage());
}
}
e.printStackTrace();
return;
}
//Check the return status of EMDKManager object creation.
if(results.statusCode == EMDKResults.STATUS_CODE.SUCCESS) {
logMessage("La récupération de l'EMDKManager a été un succès");
}else {
logMessage("Erreur lors de la récupération de l'EMDKManager");
}
}
else
{
// On simule l'ouverture de l'EMDKManager
mEMDKListener.onOpened(mEMDKManager);
}
}
public void release()
{
//Clean up the objects created by EMDK manager
if (mProfileManager != null)
mProfileManager = null;
if (mEMDKManager != null) {
mEMDKManager.release();
mEMDKManager = null;
}
}
public void execute(final String fsMxProfile, final String fsProfileName, final String fsCallbackSucces, final String fsCallbackErreur)
{
String[] params = new String[1];
params[0] = fsMxProfile;
EMDKResults results = mProfileManager.processProfile(fsProfileName, ProfileManager.PROFILE_FLAG.SET, params);
//Check the return status of processProfile
if(results.statusCode == EMDKResults.STATUS_CODE.CHECK_XML) {
// Get XML response as a String
String statusXMLResponse = results.getStatusString();
try {
// Empty Error Holder Array List if it already exists
mErrors.clear();
// Create instance of XML Pull Parser to parse the response
XmlPullParser parser = Xml.newPullParser();
// Provide the string response to the String Reader that reads
// for the parser
parser.setInput(new StringReader(statusXMLResponse));
// Call method to parse the response
parseXML(parser);
if ( mErrors.size() == 0 ) {
logMessage("Le profil a été exécuté avec succès");
logMessage("Profil: " + msProfileData);
if(fsCallbackSucces != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSS(fsCallbackSucces,fsMxProfile);
}
}
}
else {
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
String erreursJSon = gson.toJson(mErrors);
logMessage("Profile update failed:\n" + "Erreur lors de l'execution du profil: \n" + erreursJSon + "\nProfil:\n" + fsMxProfile);
if(fsCallbackErreur != "")
{
if(mAppelProcedureWL != null)
{
mAppelProcedureWL.appelProcedureWLSSSS(fsCallbackErreur, fsMxProfile, "Erreur lors de l'execution du profil", erreursJSon);
}
}
}
} catch (XmlPullParserException e) {
if(fsCallbackErreur != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSSSS(fsCallbackErreur, fsMxProfile, "Exception lors de l'analyse des résultats du profile manager", e.getMessage());
}
}
logMessage(e.getMessage());
}
}
else if(results.statusCode == EMDKResults.STATUS_CODE.SUCCESS)
{
logMessage("Le profil a été executé avec succès");
logMessage("Profil: " + msProfileData);
if(fsCallbackSucces != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSS(fsCallbackSucces, fsMxProfile);
}
}
}
else
{
if(fsCallbackErreur != "")
{
if(mAppelProcedureWL != null) {
mAppelProcedureWL.appelProcedureWLSSSS(fsCallbackErreur, fsMxProfile, "Erreur lors de l'execution du profil", getResultCode(results.statusCode));
}
}
logMessage("Profile update failed." + getResultCode(results.statusCode) + "\nProfil:\n" + fsMxProfile);
}
}
// Method to parse the XML response using XML Pull Parser
private void parseXML(XmlPullParser myParser) {
int event;
try {
// Retrieve error details if parm-error/characteristic-error in the response XML
event = myParser.getEventType();
// An object that will store a temporary error holder if an error characteristic is found
ErrorHolder tempErrorHolder = null;
logMessage("XML document");
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
logMessage("XML Element:<" + myParser.getText()+">");
if (name.equals("characteristic-error"))
{
if(tempErrorHolder == null)
tempErrorHolder = new ErrorHolder();
tempErrorHolder.sErrorType = myParser.getAttributeValue(null, "type");
if(tempErrorHolder.sParmName != null && TextUtils.isEmpty(tempErrorHolder.sParmName) == false)
{
msErrorString += "Nom: " + tempErrorHolder.sParmName + "\nType: " + tempErrorHolder.sErrorType + "\nDescription: " + tempErrorHolder.sErrorDescription + ")";
mErrors.add(tempErrorHolder);
tempErrorHolder = null;
}
}
else if (name.equals("parm-error"))
{
if(tempErrorHolder == null)
tempErrorHolder = new ErrorHolder();
tempErrorHolder.sParmName = myParser.getAttributeValue(null, "name");
tempErrorHolder.sErrorDescription = myParser.getAttributeValue(null, "desc");
if(tempErrorHolder.sErrorType != null && TextUtils.isEmpty(tempErrorHolder.sErrorType) == false)
{
msErrorString += "Nom: " + tempErrorHolder.sParmName + "\nType: " + tempErrorHolder.sErrorType + "\nDescription: " + tempErrorHolder.sErrorDescription + ")";
mErrors.add(tempErrorHolder);
tempErrorHolder = null;
}
}
break;
case XmlPullParser.END_TAG:
logMessage("XML Element:<//" + myParser.getText()+">");
break;
}
event = myParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 36.836585 | 189 | 0.552605 |
c2a73f87c248171cb5f7e85e5b960eb72a314c31 | 1,671 | package com.orangetalents.proposta.novaproposta;
import java.math.BigDecimal;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import com.orangetalents.proposta.compartilhada.utils.EncryptEDecrypt;
import com.orangetalents.proposta.compartilhada.validacoes.CpfOrCnpjValue;
import com.orangetalents.proposta.compartilhada.validacoes.UniqueValue;
import com.orangetalents.proposta.novaproposta.endereco.EnderecoRequest;
public class PropostaRequest {
@NotBlank
private String nome;
@NotBlank
@Email
private String email;
@NotBlank
@CpfOrCnpjValue
@UniqueValue(domainClass = Proposta.class, fieldName = "documento")
private String documento;
@NotNull
private EnderecoRequest endereco;
@Positive
@NotNull
private BigDecimal salario;
public PropostaRequest(String nome, String email, String documento, EnderecoRequest endereco,
BigDecimal salario) {
this.nome = nome;
this.email = email;
this.documento = documento;
this.endereco = endereco;
this.salario = salario;
}
public Proposta toModel(EncryptEDecrypt encryptEDecrypt) {
this.documento = encryptEDecrypt.encrypt(documento);
return new Proposta(nome, email, documento, endereco.toModel(), salario);
}
public String getNome() {
return this.nome;
}
public String getEmail() {
return this.email;
}
public String getDocumento() {
return documento;
}
public EnderecoRequest getEndereco() {
return endereco;
}
public BigDecimal getSalario() {
return this.salario;
}
}
| 23.535211 | 96 | 0.758827 |
350d8b0bcc777ba92485ae58cd5400b86f912771 | 253 | package net.lacnic.elections.exception;
public class OperationNotPermittedException extends Exception {
private static final long serialVersionUID = 8041401889653642928L;
public OperationNotPermittedException(String error) {
super(error);
}
}
| 19.461538 | 67 | 0.814229 |
4f9a1972c23bc2de96981461aef45f1556e3fb97 | 4,405 | /*
* (C) Copyright 2009 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Florent Guillaume
*/
package org.nuxeo.runtime.datasource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.runtime.datasource.PooledDataSourceRegistry.PooledDataSource;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import org.nuxeo.runtime.test.runner.TransactionalConfig;
import org.nuxeo.runtime.test.runner.TransactionalFeature;
import org.nuxeo.runtime.transaction.TransactionHelper;
@RunWith(FeaturesRunner.class)
@TransactionalConfig(autoStart = false)
@Features(TransactionalFeature.class)
public class TestDataSourceComponent {
private static final String COUNT_SQL = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.SESSIONS";
@Test
public void testJNDIName() throws Exception {
assertEquals("java:comp/env/jdbc/foo", DataSourceHelper.getDataSourceJNDIName("foo"));
}
protected static void checkDataSourceOk(String name, boolean autocommit) throws Exception {
DataSource ds = DataSourceHelper.getDataSource(name);
Connection conn = ds.getConnection();
assertEquals(autocommit, conn.getAutoCommit());
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT 123");
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(123, rs.getInt(1));
st.close();
conn.close();
}
@Test
@Deploy("org.nuxeo.runtime.datasource:datasource-contrib.xml")
public void testNonXANoTM() throws Exception {
checkDataSourceOk("foo", true);
checkDataSourceOk("alias", true);
}
@Test
@Deploy("org.nuxeo.runtime.datasource:datasource-contrib.xml")
public void testNonXA() throws Exception {
checkDataSourceOk("foo", true);
checkDataSourceOk("alias", true);
}
@Test
@Deploy("org.nuxeo.runtime.datasource:datasource-contrib.xml")
public void testNonShared() throws Exception {
PooledDataSource ds = (PooledDataSource) DataSourceHelper.getDataSource("foo");
TransactionHelper.startTransaction();
try (Connection c1 = ds.getConnection()) {
int n1 = countPhysicalConnections(c1);
try (Connection c2 = ds.getConnection(false)) {
int n2 = countPhysicalConnections(c2);
assertEquals(n1, n2);
}
try (Connection c2 = ds.getConnection(true)) {
int n2 = countPhysicalConnections(c2);
assertEquals(n1 + 1, n2);
}
} finally {
TransactionHelper.commitOrRollbackTransaction();
}
}
public int countPhysicalConnections(Connection conn) throws SQLException {
Statement st = conn.createStatement();
try {
ResultSet rs = st.executeQuery(COUNT_SQL);
rs.next();
return rs.getInt(1);
} finally {
st.close();
}
}
@Test
@Deploy("org.nuxeo.runtime.datasource:xadatasource-contrib.xml")
public void testXANoTx() throws Exception {
checkDataSourceOk("foo", true);
}
@Test
@Deploy("org.nuxeo.runtime.datasource:xadatasource-contrib.xml")
public void testXA() throws Exception {
TransactionHelper.startTransaction();
try {
checkDataSourceOk("foo", false);
} finally {
TransactionHelper.commitOrRollbackTransaction();
}
}
}
| 33.625954 | 95 | 0.681952 |
ee1416e6905032e57c5c6ae71e4729c4c8fc3759 | 3,575 | package org.zstack.image;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.image.ImageArchitecture;
import org.zstack.header.longjob.LongJobMessageData;
import org.zstack.header.message.NeedReplyMessage;
import java.util.List;
/**
* Created by Camile on 2/5/18.
* copy by APIAddImageMsg
*/
public class AddImageLongJobData extends LongJobMessageData {
private String resourceUuid;
private String name;
private String description;
private String url;
private String mediaType;
private String guestOsType;
private boolean system;
private String format;
private String platform;
private List<String> backupStorageUuids;
private String type;
private String architecture = ImageArchitecture.x86_64.toString();
private SessionInventory session;
private List<String> systemTags;
private List<String> userTags;
private boolean virtio;
public AddImageLongJobData(NeedReplyMessage msg) {
super(msg);
}
public String getResourceUuid() {
return resourceUuid;
}
public void setResourceUuid(String resourceUuid) {
this.resourceUuid = resourceUuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMediaType() {
return mediaType;
}
public void setMediaType(String mediaType) {
this.mediaType = mediaType;
}
public String getGuestOsType() {
return guestOsType;
}
public void setGuestOsType(String guestOsType) {
this.guestOsType = guestOsType;
}
public boolean isSystem() {
return system;
}
public void setSystem(boolean system) {
this.system = system;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getArchitecture() {
return architecture;
}
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
public List<String> getBackupStorageUuids() {
return backupStorageUuids;
}
public void setBackupStorageUuids(List<String> backupStorageUuids) {
this.backupStorageUuids = backupStorageUuids;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public SessionInventory getSession() {
return session;
}
public void setSession(SessionInventory session) {
this.session = session;
}
public List<String> getSystemTags() {
return systemTags;
}
public void setSystemTags(List<String> systemTags) {
this.systemTags = systemTags;
}
public List<String> getUserTags() {
return userTags;
}
public void setUserTags(List<String> userTags) {
this.userTags = userTags;
}
public boolean isVirtio() {
return virtio;
}
public void setVirtio(boolean virtio) {
this.virtio = virtio;
}
}
| 21.536145 | 72 | 0.64979 |
d9752620329b7acff56d79d00548b5e49e3a9bc0 | 2,737 | package com.hope.mall.mallproduct.controller;
import java.util.Arrays;
import java.util.Map;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.hope.mall.mallproduct.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.hope.mall.mallproduct.entity.AttrGroupEntity;
import com.hope.mall.mallproduct.service.AttrGroupService;
import com.hope.common.utils.PageUtils;
import com.hope.common.utils.R;
/**
* 属性分组
*
* @author chenyurong
* @email yr_chen001@163.com
* @date 2020-09-04 17:48:53
*/
@RestController
@RequestMapping("mallproduct/attrgroup")
public class AttrGroupController {
@Autowired
private AttrGroupService attrGroupService;
@Autowired
CategoryService categoryService;
/**
* 列表
*/
@RequestMapping("/list/{catelogId}")
//@RequiresPermissions("mallproduct:attrgroup:list")
public R list(@RequestParam Map<String, Object> params,
@PathVariable("catelogId") long catelogId){
// PageUtils page = attrGroupService.queryPage(params);
PageUtils page = attrGroupService.queryPage(params, catelogId);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{attrGroupId}")
//@RequiresPermissions("mallproduct:attrgroup:info")
public R info(@PathVariable("attrGroupId") Long attrGroupId){
AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);
Long catelogId = attrGroup.getCatelogId();
Long[] path = categoryService.findCatelogPath(catelogId);
attrGroup.setCatelogPath(path);
return R.ok().put("attrGroup", attrGroup);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("mallproduct:attrgroup:save")
public R save(@RequestBody AttrGroupEntity attrGroup){
attrGroupService.save(attrGroup);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("mallproduct:attrgroup:update")
public R update(@RequestBody AttrGroupEntity attrGroup){
attrGroupService.updateById(attrGroup);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("mallproduct:attrgroup:delete")
public R delete(@RequestBody Long[] attrGroupIds){
attrGroupService.removeByIds(Arrays.asList(attrGroupIds));
return R.ok();
}
}
| 27.09901 | 71 | 0.710267 |
9d70fbbd07629641342f3ac096defb0a81762e93 | 1,993 | // Author: mszal@google.com (Michael Szal)
package com.google.libwebm.mkvmuxer;
import com.google.libwebm.Common;
public class Tracks extends Common {
public enum Type {
None,
kVideo,
kAudio
};
public static final String kVorbisCodecId = "A_VORBIS";
public static final String kVp8CodecId = "V_VP8";
public Tracks() {
nativePointer = newTracks();
}
public boolean addTrack(Track track, int number) {
return AddTrack(nativePointer, track.getNativePointer(), number);
}
public Track getTrackByIndex(int index) {
long pointer = GetTrackByIndex(nativePointer, index);
return Track.newTrack(pointer);
}
public Track getTrackByNumber(long trackNumber) {
long pointer = GetTrackByNumber(nativePointer, trackNumber);
return Track.newTrack(pointer);
}
public int trackEntriesSize() {
return trackEntriesSize(nativePointer);
}
public boolean trackIsAudio(long trackNumber) {
return TrackIsAudio(nativePointer, trackNumber);
}
public boolean trackIsVideo(long trackNumber) {
return TrackIsVideo(nativePointer, trackNumber);
}
public boolean write(IMkvWriter writer) {
return Write(nativePointer, writer.getNativePointer());
}
protected Tracks(long nativePointer) {
super(nativePointer);
}
@Override
protected void deleteObject() {
deleteTracks(nativePointer);
}
private static native boolean AddTrack(long jTracks, long jTrack, int number);
private static native void deleteTracks(long jTracks);
private static native long GetTrackByIndex(long jTracks, int idx);
private static native long GetTrackByNumber(long jTracks, long track_number);
private static native long newTracks();
private static native int trackEntriesSize(long jTracks);
private static native boolean TrackIsAudio(long jTracks, long track_number);
private static native boolean TrackIsVideo(long jTracks, long track_number);
private static native boolean Write(long jTracks, long jWriter);
}
| 28.070423 | 80 | 0.74862 |
dc14f248f35bd6c165293bd5c3e6e683b1e01f73 | 1,474 | package mage.cards.v;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.DiesTriggeredAbility;
import mage.abilities.effects.common.counter.AddCountersTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.counters.CounterType;
import mage.filter.FilterPermanent;
import mage.filter.common.FilterControlledPermanent;
import mage.target.TargetPermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class VenerableKnight extends CardImpl {
private static final FilterPermanent filter = new FilterControlledPermanent(SubType.KNIGHT);
public VenerableKnight(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.KNIGHT);
this.power = new MageInt(2);
this.toughness = new MageInt(1);
// When Venerable Knight dies, put a +1/+1 counter on target Knight you control.
Ability ability = new DiesTriggeredAbility(new AddCountersTargetEffect(CounterType.P1P1.createInstance()));
ability.addTarget(new TargetPermanent(filter));
this.addAbility(ability);
}
private VenerableKnight(final VenerableKnight card) {
super(card);
}
@Override
public VenerableKnight copy() {
return new VenerableKnight(this);
}
}
| 30.708333 | 115 | 0.738806 |
c5e3a12b81ccccab7ffac8fd150593cd41d91507 | 637 | package com.boot.saas.mapper;
import com.boot.saas.domain.MysqlAccount;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* MysqlAccount
*
* @author lizhifu
* @date 2020/12/22
*/
public interface MysqlAccountMapper {
/**
* 查询
* @param id
* @return
*/
@Select("select * from mysql_account where id = #{id}")
MysqlAccount selectById(@Param("id") Integer id);
/**
* 查询
* @param tenant
* @return
*/
@Select("select * from mysql_account where tenant = #{tenant}")
MysqlAccount selectByTenant(@Param("tenant") String tenant);
}
| 21.233333 | 67 | 0.642072 |
76e2c0e0d08011b939e8454934dc4a3ac12eead7 | 2,114 |
package com.commercetools.api.models.message;
import java.time.*;
import java.util.*;
import java.util.function.Function;
import javax.validation.Valid;
import com.commercetools.api.models.customer_group.CustomerGroupReference;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.*;
import io.vrap.rmf.base.client.utils.Generated;
@Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen")
@JsonDeserialize(as = OrderCustomerGroupSetMessagePayloadImpl.class)
public interface OrderCustomerGroupSetMessagePayload extends MessagePayload {
String ORDER_CUSTOMER_GROUP_SET = "OrderCustomerGroupSet";
@Valid
@JsonProperty("customerGroup")
public CustomerGroupReference getCustomerGroup();
@Valid
@JsonProperty("oldCustomerGroup")
public CustomerGroupReference getOldCustomerGroup();
public void setCustomerGroup(final CustomerGroupReference customerGroup);
public void setOldCustomerGroup(final CustomerGroupReference oldCustomerGroup);
public static OrderCustomerGroupSetMessagePayload of() {
return new OrderCustomerGroupSetMessagePayloadImpl();
}
public static OrderCustomerGroupSetMessagePayload of(final OrderCustomerGroupSetMessagePayload template) {
OrderCustomerGroupSetMessagePayloadImpl instance = new OrderCustomerGroupSetMessagePayloadImpl();
instance.setCustomerGroup(template.getCustomerGroup());
instance.setOldCustomerGroup(template.getOldCustomerGroup());
return instance;
}
public static OrderCustomerGroupSetMessagePayloadBuilder builder() {
return OrderCustomerGroupSetMessagePayloadBuilder.of();
}
public static OrderCustomerGroupSetMessagePayloadBuilder builder(
final OrderCustomerGroupSetMessagePayload template) {
return OrderCustomerGroupSetMessagePayloadBuilder.of(template);
}
default <T> T withOrderCustomerGroupSetMessagePayload(Function<OrderCustomerGroupSetMessagePayload, T> helper) {
return helper.apply(this);
}
}
| 36.448276 | 120 | 0.790445 |
4add9944b74f4336c1510bef5517daf3d6581ac6 | 3,308 | /*$$
* Copyright (c) 1999, Trustees of the University of Chicago
* 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 University of Chicago 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 TRUSTEES 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 uchicago.src.sim.engine;
import uchicago.src.sim.gui.MediaProducer;
public class MovieScheduler {
private MediaProducer producer;
private BasicAction frameCapture;
private BasicAction cleanUp;
private String fileName;
class FrameCapture extends BasicAction {
String fileName;
boolean nameSet = false;
public FrameCapture(String fname) {
fileName = fname;
}
public void execute() {
// if (!nameSet) {
// producer.setMovieName(fileName, MediaProducer.QUICK_TIME);
// nameSet = true;
// }
producer.addMovieFrame();
}
}
public MovieScheduler(String fileName, MediaProducer producer) {
this.producer = producer;
frameCapture = new FrameCapture(fileName);
this.fileName = fileName;
cleanUp = new BasicAction() {
public void execute() {
MovieScheduler.this.producer.closeMovie();
}
};
}
private void initProducer() {
producer.setMovieName(fileName, MediaProducer.QUICK_TIME);
}
public void scheduleAtPauseAndEnd(Schedule schedule) {
initProducer();
schedule.scheduleActionAtPause(frameCapture);
schedule.scheduleActionAtEnd(frameCapture);
schedule.scheduleActionAtEnd(cleanUp);
}
public void scheduleAtInterval(Schedule schedule, int interval) {
initProducer();
schedule.scheduleActionAtInterval(interval, frameCapture, Schedule.LAST);
schedule.scheduleActionAtEnd(cleanUp);
}
public void scheduleAtEveryTick(Schedule schedule) {
initProducer();
schedule.scheduleActionAt(0, frameCapture, Schedule.LAST);
schedule.scheduleActionAtInterval(1, frameCapture, Schedule.LAST);
schedule.scheduleActionAtEnd(cleanUp);
}
}
| 34.103093 | 79 | 0.740931 |
7fb3cca280bd0ed612e65f83e9259e5a7af8d434 | 8,327 | /*
* Copyright 2017 Austin Lehman
*
* 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.cali;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import com.cali.types.CaliBool;
import com.cali.types.CaliDouble;
import com.cali.types.CaliException;
import com.cali.types.CaliInt;
import com.cali.types.CaliList;
import com.cali.types.CaliMap;
import com.cali.types.CaliNull;
import com.cali.types.CaliString;
import com.cali.types.CaliType;
/**
* Default implementation of the security manager. This can be extended
* to implement custom security manager functionality or properties. This
* object is provided in the cali environment as secman object.
* @author Austin Lehman
*/
public class SecurityManagerImpl implements SecurityManagerInt {
/**
* Holds the properties for the security manager.
*/
protected ConcurrentHashMap<String, Object> props = new ConcurrentHashMap<String, Object>();
/**
* Default constructor adds the standard properties.
*/
public SecurityManagerImpl() {
/*
* Security manager itself.
*/
// instantiate - can new instances be created from this one? This
// normally applies to ones instantiated from within cali and are blocked
// in CSecurityManager sub-class constructor.
this.props.put("securitymanager.instantiate", true);
// getProp
this.props.put("securitymanager.property.get", true);
// keySet/getMap
this.props.put("securitymanager.property.list", true);
// setProp
this.props.put("securitymanager.property.set", false);
/*
* System information view. See com.cali.stdlib.CSys.java.
*/
this.props.put("os.info.view", false);
this.props.put("java.info.view", false);
this.props.put("java.home.view", false);
this.props.put("java.classpath.view", false);
this.props.put("cali.info.view", false);
this.props.put("cali.path.view", false);
this.props.put("current.path.view", false);
this.props.put("home.path.view", false);
this.props.put("user.name.view", false);
/*
* Reflection actions. See com.cali.stdlib.CReflect.java.
*/
this.props.put("reflect.eval.string", false);
this.props.put("reflect.eval.file", false);
this.props.put("reflect.include.module", false);
/*
* Calidoc actions. See com.cali.stdlib.CLang.java.
*/
this.props.put("calidoc.file.getJson", false);
this.props.put("calidoc.class.getJson", false);
}
/**
* Java get property.
*/
@Override
public Object getProperty(String PropName) {
return this.props.get(PropName);
}
/**
* Cali getProperty. This method will get the property, match it to a
* standard CaliType and return it. If property
* securitymanager.property.get is set to false this method will
* throw a security exception.
*/
@Override
public CaliType getProp(Environment env, ArrayList<CaliType> args) {
if ((Boolean)this.getProperty("securitymanager.property.get")) {
String PropName = ((CaliString)args.get(0)).getValueString();
Object obj = this.props.get(PropName);
if (obj == null) {
return new CaliNull();
} else if (obj instanceof Boolean) {
return new CaliBool((Boolean)obj);
} else if (obj instanceof Long) {
return new CaliInt((Long)obj);
} else if (obj instanceof Double) {
return new CaliDouble((Double)obj);
} else if (obj instanceof String) {
return new CaliString((String)obj);
} else {
return new CaliString(obj.toString());
}
} else {
return new CaliException("securitymanager.getProp(): Security exception, action 'securitymanager.property.get' not permitted.");
}
}
/**
* Gets the key set of the properties as a list of strings.
*/
@Override
public CaliType keySet(Environment env, ArrayList<CaliType> args) {
if ((Boolean)this.getProperty("securitymanager.property.list")) {
CaliList cl = new CaliList();
for (String key : this.props.keySet()) {
cl.add(new CaliString(key));
}
return cl;
} else {
return new CaliException("securitymanager.keySet(): Security exception, action 'securitymanager.property.list' not permitted.");
}
}
/**
* Gets a cali map of the security manager properties and their values.
*/
@Override
public CaliType getMap(Environment env, ArrayList<CaliType> args) {
if ((Boolean)this.getProperty("securitymanager.property.list")) {
CaliMap cm = new CaliMap();
for (String key : this.props.keySet()) {
Object tobj = this.props.get(key);
if (tobj == null) {
cm.put(key, new CaliNull());
} else if (tobj instanceof Boolean) {
cm.put(key, new CaliBool((Boolean)tobj));
} else if (tobj instanceof Long) {
cm.put(key, new CaliInt((Long)tobj));
} else if (tobj instanceof Double) {
cm.put(key, new CaliDouble((Double)tobj));
} else if (tobj instanceof String) {
cm.put(key, new CaliString((String)tobj));
} else {
return new CaliException("securitymanager.getMap(): Expecting simpel type (bool, int, double, string, null) but found '" + tobj.getClass().getName() + "' instead for key '" + key + "'.");
}
}
return cm;
} else {
return new CaliException("securitymanager.getMap(): Security exception, action 'securitymanager.property.list' not permitted.");
}
}
/**
* Cali setProp. This method provides the ability
* to set the property of a security manager property pair. If property
* securitymanager.property.set is set to false this method will
* throw a security exception.
*/
@Override
public CaliType setProp(Environment env, ArrayList<CaliType> args) {
if ((Boolean)this.getProperty("securitymanager.property.set")) {
String key = ((CaliString)args.get(0)).getValueString();
CaliType ct = args.get(1);
Object val = null;
if (ct instanceof CaliBool) {
val = ((CaliBool)ct).getValue();
} else if (ct instanceof CaliString) {
val = ((CaliString)ct).getValueString();
} else if (ct instanceof CaliInt) {
val = ((CaliInt)ct).getValue();
} else if (ct instanceof CaliDouble) {
val = ((CaliDouble)ct).getValue();
} else if (ct instanceof CaliNull) {
val = null;
} else {
return new CaliException("securitymanager.setProp(): Expecting simpel type (bool, int, double, string, null) but found '" + ct.getClass().getName() + "' instead.");
}
this.props.put(key, val);
return env.getClassInstance();
} else {
return new CaliException("securitymanager.getProp(): Security exception, action 'securitymanager.property.set' not permitted.");
}
}
/**
* Cali setMap. This method provides the ability
* to set a whole map of key-val pairs. If property
* securitymanager.property.set is set to false this method will
* throw a security exception.
*/
@Override
public CaliType setMap(Environment env, ArrayList<CaliType> args) {
if ((Boolean)this.getProperty("securitymanager.property.set")) {
CaliMap mp = (CaliMap)args.get(0);
for (String key : mp.getValue().keySet()) {
CaliType ct = mp.getValue().get(key);
Object val = null;
if (ct instanceof CaliBool) {
val = ((CaliBool)ct).getValue();
} else if (ct instanceof CaliString) {
val = ((CaliString)ct).getValueString();
} else if (ct instanceof CaliInt) {
val = ((CaliInt)ct).getValue();
} else if (ct instanceof CaliDouble) {
val = ((CaliDouble)ct).getValue();
} else if (ct instanceof CaliNull) {
val = null;
} else {
return new CaliException("securitymanager.setMap(): Expecting simpel type (bool, int, double, string, null) but found '" + ct.getClass().getName() + "' instead.");
}
this.props.put(key, val);
}
return env.getClassInstance();
} else {
return new CaliException("securitymanager.getProp(): Security exception, action 'securitymanager.property.set' not permitted.");
}
}
}
| 34.127049 | 192 | 0.688603 |
e6e2e00125c174b515d00679df39b51df9aae311 | 2,362 | package com.amsavarthan.hify.feature_ai.utils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class RecentsDatabase extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Recents.db";
public static final String DATABASE_TABLE_NAME="queries";
public static final String COLUMN_ID="id";
public static final String COLUMN_QUERY="search_query";
private HashMap hp;
public RecentsDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table queries "+"(id integer primary key, search_query text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS queries");
onCreate(db);
}
public boolean insertQuery(String query){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("search_query",query);
db.insert("queries",null,contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db=this.getReadableDatabase();
Cursor res=db.rawQuery("select * from queries where id="+id+"",null);
return res;
}
public Integer deleteQuery(Integer id){
SQLiteDatabase db=this.getWritableDatabase();
return db.delete("queries","id = ? ",new String[]{Integer.toString(id)});
}
public List<String> getAllQueries(){
List<String> list=new ArrayList<String>();
SQLiteDatabase db=this.getReadableDatabase();
Cursor res=db.rawQuery("select * from queries",null);
res.moveToFirst();
while(!res.isAfterLast()){
list.add(res.getString(res.getColumnIndex(COLUMN_QUERY)));
res.moveToNext();
}
return list;
}
public boolean clear() {
SQLiteDatabase db=this.getWritableDatabase();
db.execSQL("delete from "+ DATABASE_TABLE_NAME);
return true;
}
}
| 29.525 | 90 | 0.684589 |
5a499ee0d7f26242555bdc333ab4c7db2995336a | 444 | package com.neu.his.cloud.zuul.service.sms;
import com.neu.his.cloud.zuul.model.SmsPermission;
import com.neu.his.cloud.zuul.model.SmsStaff;
import java.util.List;
/**
* @author Zain
* @title: SmsRoleService
* @projectName his-cloud
* @description: TODO
* @date 2019/6/17 14:20
*/
public interface SmsRoleService {
/**
* 描述:根据角色Id查询角色的权限
* <p>author: 赵煜
*/
List<SmsPermission> getPermissionList(Long roleId);
}
| 19.304348 | 55 | 0.691441 |
46db86bb1d9a3a061cf229f48e451d709d0f0733 | 465 | package org.getopentest.selenium;
import org.getopentest.selenium.core.SeleniumTestAction;
public class ActionsPerform extends SeleniumTestAction {
@Override
public void run() {
this.waitForAsyncCallsToFinish();
try {
SeleniumTestAction.getActionsInstance().perform();
} catch (Exception ex) {
throw ex;
} finally {
SeleniumTestAction.discardActionsObject();
}
}
}
| 23.25 | 62 | 0.630108 |
d6542af3a64eff194fb8637c4d3a6d1e546e79d3 | 7,398 | package com.netopyr.wurmloch.integration;
import com.netopyr.wurmloch.crdt.ORSet;
import com.netopyr.wurmloch.store.CrdtStore;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
public class LocalORSetTest {
private CrdtStore replica2;
private CrdtStore replica3;
private ORSet<String> orSet1;
private ORSet<String> orSet2;
private ORSet<String> orSet3;
@SuppressWarnings("unchecked")
@BeforeMethod
public void setUp() {
final String ID = "TestORSet";
final CrdtStore replica1 = new CrdtStore("ID_1");
replica2 = new CrdtStore("ID_2");
replica3 = new CrdtStore("ID_3");
replica1.connect(replica2);
replica2.connect(replica3);
orSet1 = replica1.createORSet(ID);
orSet2 = replica2.<String>findORSet(ID).get();
orSet3 = replica3.<String>findORSet(ID).get();
}
@Test
public void shouldSynchronizeSingleAdd() {
// given:
final String element = "Hello World";
replica2.disconnect(replica3);
// when:
orSet1.add(element);
// then:
assertThat(orSet1, contains(element));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, empty());
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, contains(element));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, equalTo(orSet1));
}
@Test
public void shouldSynchronizeSingleDelete() {
// given:
final String element = "Hello World";
orSet1.add(element);
replica2.disconnect(replica3);
// when:
orSet1.remove(element);
// then:
assertThat(orSet1, empty());
assertThat(orSet2, empty());
assertThat(orSet3, contains(element));
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, empty());
assertThat(orSet2, empty());
assertThat(orSet3, empty());
}
@Test
public void shouldSynchronizeConcurrentAddsOfSameElement() {
// given:
final String element = "Hello World";
replica2.disconnect(replica3);
// when:
orSet1.add(element);
orSet3.add(element);
// then:
assertThat(orSet1, contains(element));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, equalTo(orSet1));
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, contains(element));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, equalTo(orSet1));
}
@Test
public void shouldSynchronizeConcurrentAddsOfDifferentElements() {
// given:
final String element1 = "Hello World";
final String element2 = "Good Bye";
replica2.disconnect(replica3);
// when:
orSet1.add(element1);
orSet3.add(element2);
// then:
assertThat(orSet1, contains(element1));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, contains(element2));
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, contains(element1, element2));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, equalTo(orSet1));
}
@Test
public void shouldSynchronizeConcurrentDeletesOfSameElement() {
// given:
final String element = "Hello World";
orSet1.add(element);
replica2.disconnect(replica3);
// when:
orSet1.remove(element);
orSet3.remove(element);
// then:
assertThat(orSet1, empty());
assertThat(orSet2, empty());
assertThat(orSet3, empty());
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, empty());
assertThat(orSet2, empty());
assertThat(orSet3, empty());
}
@Test
public void shouldSynchronizeConcurrentDeletesOfDifferentElements() {
// given:
final String element1 = "Hello World";
final String element2 = "Good Bye";
orSet1.add(element1);
orSet1.add(element2);
replica2.disconnect(replica3);
// when:
orSet1.remove(element1);
orSet3.remove(element2);
// then:
assertThat(orSet1, contains(element2));
assertThat(orSet2, equalTo(orSet2));
assertThat(orSet3, contains(element1));
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, empty());
assertThat(orSet2, empty());
assertThat(orSet3, empty());
}
@Test
public void shouldSynchronizeConcurrentAddAndDeleteDifferentElements() {
// given:
final String element1 = "Hello World";
final String element2 = "Good Bye";
orSet1.add(element1);
replica2.disconnect(replica3);
// when:
orSet1.remove(element1);
orSet3.add(element2);
// then:
assertThat(orSet1, empty());
assertThat(orSet2, empty());
assertThat(orSet3, contains(element1, element2));
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, contains(element2));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, equalTo(orSet1));
// when:
replica2.disconnect(replica3);
orSet1.add(element1);
orSet3.remove(element2);
// then:
assertThat(orSet1, contains(element1, element2));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, empty());
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, contains(element1));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, equalTo(orSet1));
}
@Test
public void shouldSynchronizeConcurrentAddAndDeleteSameElement() {
// given:
final String element = "Hello World";
replica2.disconnect(replica3);
orSet1.add(element);
// when:
orSet1.remove(element);
orSet3.add(element);
// then:
assertThat(orSet1, empty());
assertThat(orSet2, empty());
assertThat(orSet3, contains(element));
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, contains(element));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, equalTo(orSet1));
// when:
replica2.disconnect(replica3);
orSet1.remove(element);
// then:
assertThat(orSet1, empty());
assertThat(orSet2, empty());
assertThat(orSet3, contains(element));
// when:
orSet1.add(element);
orSet3.remove(element);
// then:
assertThat(orSet1, contains(element));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, empty());
// when:
replica2.connect(replica3);
// then:
assertThat(orSet1, contains(element));
assertThat(orSet2, equalTo(orSet1));
assertThat(orSet3, equalTo(orSet1));
}
}
| 26.234043 | 76 | 0.595431 |
63dc0aadb5e1875f86a973f0e16cecc972de2130 | 14,012 | package com.github.pmoerenhout.atcommander.module.telit.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import com.github.pmoerenhout.atcommander.AtResponse;
import com.github.pmoerenhout.atcommander.basic.commands.BaseResponse;
import com.github.pmoerenhout.atcommander.basic.commands.Response;
import com.github.pmoerenhout.atcommander.basic.exceptions.ParseException;
import com.github.pmoerenhout.atcommander.common.Util;
import com.github.pmoerenhout.atcommander.module.telit.types.ActiveSet;
public class ReadNetworkStatusResponse extends BaseResponse implements Response {
// #RFSTS: "204 04",1001,-80,00DE,01,5,19,10,2,9878,"204007930002270","vodafone NL",1,2
// #RFSTS: ,1001,-77,00DE,01,5,19,10,2,9878,"204007930002270","",0,2
// #RFSTS: "204 08",14,-83,0CBC,00,5,19,10,,BEE9,"204007930002270","NL KPN",0,2
// #RFSTS: "204 16",848,-89,03F8,,0,19,29,,14BB,"204007930002270","T-Mobile NL",0,3
// #RFSTS:"204 08",14,-80,0CBC,00,5,19,11,,BEE9,"204000090192154","NL KPN",0,2
// #RFSTS:"000 00",-1,-47,FFFF,FF,255,19,27,,FFFF,"204086527040379","NL KPN",1,2
// #RFSTS: ,32767,-47,,,19,27,,,"204000090288415","",0,2
private static final Pattern PATTERN = Pattern.compile(
"^\\#RFSTS:[ ]?\"([0-9 ]*)\",([-\\d]*),([-\\d]*),([-.A-Z0-9]*),([-.A-F0-9]*),([\\d]*),([\\d]*),([\\d]*),([ \\d]*),([0-9A-FX]*),\"([1-9][0-9]*)\",\"([a-zA-Z0-9-\\(\\)\\* ]*)\",([\\d]*),([\\d]*)$");
private static final Pattern PATTERN2 = Pattern.compile(
"^\\#RFSTS:[ ]?(),([-\\d]*),([-\\d]*),([-.A-Z0-9]*),([-.A-F0-9]*),([\\d]*),([\\d]*),([\\d]*),([\\d]*),([0-9A-FX]*),\"([1-9][0-9]*)\",\"([a-zA-Z0-9-\\(\\)\\* ]*)\",([\\d]*),([\\d]*)$");
private String line;
private String plmn;
private Integer arfcn;
private Integer rssi;
private String locationAreaCode;
private String routingAreaCode;
private Integer txPower;
private Integer mobilityManagementState;
private Integer radioResourceState;
private Integer networkOperatorMode;
private String cellId;
private String imsi;
private String operatorName;
private Integer serviceDomain;
private Integer activeBand;
private Integer uarfcn;
private Float psc;
private Float ecio;
private Integer rscp;
private Integer drx;
private Integer blockErrorRate;
private Integer numberOfActiveSet;
private List<ActiveSet> activeSets = new ArrayList<>();
public ReadNetworkStatusResponse(final AtResponse s) {
parseSolicited(s);
}
public void parseSolicited(final AtResponse response) {
final List<String> informationalText = response.getInformationalText();
if (informationalText.size() == 1) {
line = informationalText.get(0);
final String[] tokens = StringUtils.splitPreserveAllTokens(StringUtils.substringAfter(line, "#RFSTS:"), COMMA);
final int tokensLength = tokens.length;
// LOG.info("'{}': Split count: {}", line, tokens.length);
// for (int i = 0; i < tokens.length; i++) {
// LOG.info("{}: -{}-", i, tokens[i]);
// }
if (tokensLength == 13) {
// GSM, incorrectly encoded
if (StringUtils.isNotBlank(tokens[0])) {
plmn = Util.removeQuotes(StringUtils.trim(tokens[0]));
}
arfcn = Integer.valueOf(tokens[1]);
rssi = Integer.valueOf(tokens[2]);
if (StringUtils.isNotBlank(tokens[3])) {
locationAreaCode = tokens[3];
}
if (StringUtils.isNotBlank(tokens[4])) {
routingAreaCode = tokens[4];
}
// Guess that it is the Tx Power which is missing
// txPower = Integer.parseInt(tokens[4]);
mobilityManagementState = Integer.valueOf(tokens[5]);
if (StringUtils.isNotBlank(tokens[6])) {
radioResourceState = Integer.valueOf(tokens[6]);
}
if (StringUtils.isNotBlank(tokens[7])) {
networkOperatorMode = Integer.valueOf(tokens[7]);
}
if (StringUtils.isNotBlank(tokens[8])) {
cellId = tokens[8];
}
imsi = Util.removeQuotes(tokens[9]);
if (StringUtils.isNotBlank(tokens[10])) {
String unquoted = Util.removeQuotes(tokens[10]);
if (StringUtils.isNotBlank(unquoted)) {
operatorName = unquoted;
}
}
serviceDomain = Integer.valueOf(tokens[11]);
activeBand = Integer.valueOf(tokens[12]);
return;
}
if (tokensLength == 14) {
// GSM
if (StringUtils.isNotBlank(tokens[0])) {
plmn = Util.removeQuotes(StringUtils.trim(tokens[0]));
}
if (StringUtils.isNotBlank(tokens[1])) {
arfcn = Integer.valueOf(tokens[1]);
}
if (StringUtils.isNotBlank(tokens[2])) {
rssi = Integer.valueOf(tokens[2]);
}
if (StringUtils.isNotBlank(tokens[3])) {
locationAreaCode = tokens[3];
}
if (StringUtils.isNotBlank(tokens[4])) {
routingAreaCode = tokens[4];
}
if (StringUtils.isNotBlank(tokens[5])) {
txPower = Integer.valueOf(tokens[5]);
}
if (StringUtils.isNotBlank(tokens[6])) {
mobilityManagementState = Integer.valueOf(tokens[6]);
}
if (StringUtils.isNotBlank(tokens[7])) {
radioResourceState = Integer.valueOf(tokens[7]);
}
if (StringUtils.isNotBlank(tokens[8])) {
networkOperatorMode = Integer.valueOf(tokens[8]);
}
if (StringUtils.isNotBlank(tokens[9])) {
cellId = tokens[9];
}
imsi = Util.removeQuotes(tokens[10]);
if (StringUtils.isNotBlank(tokens[11])) {
String unquoted = Util.removeQuotes(tokens[11]);
if (StringUtils.isNotBlank(unquoted)) {
operatorName = unquoted;
}
}
serviceDomain = Integer.valueOf(tokens[12]);
activeBand = Integer.valueOf(tokens[13]);
return;
}
if (tokensLength == 19 || tokensLength == 22 || tokensLength == 25 || tokensLength == 28 || tokensLength == 31 || tokensLength == 34 || tokensLength == 37) {
// WCDMA network
if (StringUtils.isNotBlank(tokens[0])) {
plmn = Util.removeQuotes(StringUtils.trim(tokens[0]));
}
if (StringUtils.isNotBlank(tokens[1])) {
uarfcn = Integer.valueOf(tokens[1]);
}
if (StringUtils.isNotBlank(tokens[2])) {
psc = Float.valueOf(tokens[2]);
}
if (StringUtils.isNotBlank(tokens[3])) {
ecio = Float.valueOf(tokens[3]);
}
if (StringUtils.isNotBlank(tokens[4])) {
rscp = Integer.valueOf(tokens[4]);
}
if (StringUtils.isNotBlank(tokens[5])) {
rssi = Integer.valueOf(tokens[5]);
}
if (StringUtils.isNotBlank(tokens[6])) {
locationAreaCode = tokens[6];
}
if (StringUtils.isNotBlank(tokens[7])) {
routingAreaCode = tokens[7];
}
if (StringUtils.isNotBlank(tokens[8])) {
txPower = Integer.valueOf(tokens[8]);
}
if (StringUtils.isNotBlank(tokens[9])) {
drx = Integer.valueOf(tokens[9]);
}
if (StringUtils.isNotBlank(tokens[10])) {
mobilityManagementState = Integer.valueOf(tokens[10]);
}
if (StringUtils.isNotBlank(tokens[11])) {
radioResourceState = Integer.valueOf(tokens[11]);
}
if (StringUtils.isNotBlank(tokens[12])) {
networkOperatorMode = Integer.valueOf(tokens[12]);
}
if (StringUtils.isNotBlank(tokens[13])) {
blockErrorRate = Integer.valueOf(tokens[13]);
}
if (StringUtils.isNotBlank(tokens[14])) {
cellId = tokens[14];
}
imsi = Util.removeQuotes(tokens[15]);
if (StringUtils.isNotBlank(tokens[16])) {
String unquoted = Util.removeQuotes(tokens[16]);
if (StringUtils.isNotBlank(unquoted)) {
operatorName = unquoted;
}
}
if (StringUtils.isNotBlank(tokens[17])) {
serviceDomain = Integer.valueOf(tokens[17]);
}
if (StringUtils.isNotBlank(tokens[18])) {
numberOfActiveSet = Integer.parseInt(tokens[18]);
}
for (int i = 0; i < numberOfActiveSet; i++) {
if (StringUtils.isNotBlank(tokens[19 + (i * 3)]) && StringUtils.isNotBlank(tokens[20 + (i * 3)]) && StringUtils.isNotBlank(tokens[21 + (i * 3)])) {
int p1 = Integer.parseInt(tokens[19 + (i * 3)]);
float p2 = Float.parseFloat(tokens[20 + (i * 3)]);
float p3 = Float.parseFloat(tokens[21 + (i * 3)]);
activeSets.add(new ActiveSet(p1, p2, p3));
} else {
throw new ParseException("Could not retrieve active set " + i + " from " + line);
}
}
return;
}
// (GSM network) #RFSTS:<PLMN>,<ARFCN>,<RSSI>,<LAC>,<RAC>,<TXPWR>,<MM>, <RR>,<NOM>,<CID>,<IMSI>,<NetNameAsc>,<SD>,<ABND>
// (WDMA network) #RFSTS:<PLMN>,[<UARFCN>],[<PSC>],[<Ec/Io>],[<RSCP>], [RSSI>],[<LAC>], [<RAC>],<TXPWR>,<DRX>,<MM>,<RRC>,<NOM>,<BLER>,<CID>,<IMSI>, <NetNameAsc>,<SD>,<nAST>[,<nUARFCN><nPSC>,<nEc/Io>]
final Matcher m = PATTERN.matcher(line);
if (m.find()) {
if (StringUtils.isNotBlank(m.group(1))) {
plmn = m.group(1);
}
if (StringUtils.isNotBlank(m.group(2))) {
arfcn = Integer.valueOf(m.group(2));
}
if (StringUtils.isNotBlank(m.group(3))) {
rssi = Integer.valueOf(m.group(3));
}
if (StringUtils.isNotBlank(m.group(4))) {
locationAreaCode = m.group(4);
}
if (StringUtils.isNotBlank(m.group(5))) {
routingAreaCode = m.group(5);
}
if (StringUtils.isNotBlank(m.group(6))) {
txPower = Integer.valueOf(m.group(6));
}
if (StringUtils.isNotBlank(m.group(7))) {
mobilityManagementState = Integer.valueOf(m.group(7));
}
if (StringUtils.isNotBlank(m.group(8))) {
radioResourceState = Integer.valueOf(m.group(8));
}
if (StringUtils.isNotBlank(m.group(9))) {
networkOperatorMode = Integer.valueOf(m.group(9));
}
if (StringUtils.isNotBlank(m.group(10))) {
cellId = m.group(10);
}
if (StringUtils.isNotBlank(m.group(11))) {
imsi = m.group(11);
}
if (StringUtils.isNotBlank(m.group(12))) {
operatorName = m.group(12);
}
if (StringUtils.isNotBlank(m.group(13))) {
serviceDomain = Integer.valueOf(m.group(13));
}
if (StringUtils.isNotBlank(m.group(14))) {
activeBand = Integer.valueOf(m.group(14));
}
return;
}
final Matcher m2 = PATTERN2.matcher(line);
if (m2.find()) {
if (StringUtils.isNotBlank(m2.group(1))) {
plmn = m2.group(1);
}
if (StringUtils.isNotBlank(m2.group(2))) {
arfcn = Integer.parseInt(m2.group(2));
}
if (StringUtils.isNotBlank(m2.group(3))) {
rssi = Integer.parseInt(m2.group(3));
}
if (StringUtils.isNotBlank(m2.group(4))) {
locationAreaCode = m2.group(4);
}
if (StringUtils.isNotBlank(m2.group(5))) {
routingAreaCode = m2.group(5);
}
if (StringUtils.isNotBlank(m2.group(6))) {
txPower = Integer.parseInt(m2.group(6));
}
if (StringUtils.isNotBlank(m2.group(7))) {
mobilityManagementState = Integer.parseInt(m2.group(7));
}
if (StringUtils.isNotBlank(m2.group(8))) {
radioResourceState = Integer.parseInt(m2.group(8));
}
if (StringUtils.isNotBlank(m2.group(9))) {
networkOperatorMode = Integer.parseInt(m2.group(9));
}
if (StringUtils.isNotBlank(m2.group(10))) {
cellId = m2.group(10);
}
if (StringUtils.isNotBlank(m2.group(11))) {
imsi = m2.group(11);
}
if (StringUtils.isNotBlank(m2.group(12))) {
operatorName = m2.group(12);
}
if (StringUtils.isNotBlank(m2.group(13))) {
serviceDomain = Integer.parseInt(m2.group(13));
}
if (StringUtils.isNotBlank(m2.group(14))) {
activeBand = Integer.parseInt(m2.group(14));
}
return;
}
throw createParseException(line);
} else {
throw createParseException(response);
}
}
public String getPlmn() {
return plmn;
}
public Integer getArfcn() {
return arfcn;
}
public Integer getRssi() {
return rssi;
}
public String getLocationAreaCode() {
return locationAreaCode;
}
public String getRoutingAreaCode() {
return routingAreaCode;
}
public Integer getTxPower() {
return txPower;
}
public Integer getMobilityManagementState() {
return mobilityManagementState;
}
public Integer getRadioResourceState() {
return radioResourceState;
}
public Integer getNetworkOperatorMode() {
return networkOperatorMode;
}
public String getCellId() {
return cellId;
}
public String getImsi() {
return imsi;
}
public String getOperatorName() {
return operatorName;
}
public Integer getServiceDomain() {
return serviceDomain;
}
public Integer getActiveBand() {
return activeBand;
}
public Integer getUarfcn() {
return uarfcn;
}
public Float getPsc() {
return psc;
}
public Float getEcio() {
return ecio;
}
public Integer getRscp() {
return rscp;
}
public Integer getDrx() {
return drx;
}
public Integer getBlockErrorRate() {
return blockErrorRate;
}
public Integer getNumberOfActiveSet() {
return numberOfActiveSet;
}
public List<ActiveSet> getActiveSets() {
return activeSets;
}
@Override
public String toString() {
return line;
}
}
| 33.361905 | 205 | 0.585641 |
b4602d664a3fa74e0b9c44b547f8aefabfca4b48 | 5,447 | /*
* Copyright 2002-2005 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 com.jmelzer.jitty.model;
import javax.persistence.*;
import java.io.Serializable;
/**
* Standard User entity with attributes such as name, password etc.
* <p>
* We also tie in to the security framework and implement
* the Acegi UserDetails interface so that Acegi can take care
* of Authentication and Authorization
*/
@Entity
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = -2388299912396255263L;
@Column(nullable = true)
byte[] avatar;
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
@JoinColumn(name = "TOURNAMENT_ID")
Tournament lastUsedTournament;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer type;
@Column(nullable = false, name = "loginname")
private String loginName;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String password;
@Column(nullable = true)
private String email;
@Column(nullable = true)
private String locale;
@Column(nullable = false)
private boolean locked = true;
// private Set<UserRole> roles = new LinkedHashSet<UserRole>();
public User() {
}
public User(String name, String password, String email) {
this.name = name;
this.password = password;
this.email = email;
}
public Tournament getLastUsedTournament() {
return lastUsedTournament;
}
public void setLastUsedTournament(Tournament lastUsedTournament) {
this.lastUsedTournament = lastUsedTournament;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int compareTo(User u) {
if (u == null) {
return 1;
}
if (u.name == null) {
if (name == null) {
return 0;
}
return 1;
}
if (name == null) {
return -1;
}
return name.compareTo(u.name);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
final User u = (User) o;
return u.getLoginName().equals(loginName);
}
@Override
public int hashCode() {
if (loginName == null) {
return 0;
}
return loginName.hashCode();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("User");
sb.append("{type=").append(type);
sb.append(", loginName='").append(loginName).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", password='").append(password).append('\'');
sb.append(", email='").append(email).append('\'');
sb.append(", locale='").append(locale).append('\'');
sb.append(", locked=").append(locked);
sb.append('}');
return sb.toString();
}
// @OneToMany(fetch = FetchType.EAGER)
// @JoinTable(name = "USER_TO_ROLES", joinColumns = @JoinColumn(name = "USER_ID"),
// inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
// public Set<UserRole> getRoles() {
// return roles;
// }
//
// public void setRoles(Set<UserRole> roles) {
// this.roles = roles;
// }
//
// public void addRole(UserRole userRole) {
// roles.add(userRole);
// }
// @Transient
// public boolean isAdmin() {
// for (UserRole role : roles) {
// if (role.getName().equals(UserRole.Roles.ROLE_ADMIN.name())) {
// return true;
// }
// }
// return false;
// }
}
| 25.101382 | 85 | 0.591518 |
bd72af1e4daa0ba7a4fdc7d34a3711ce8178d3c8 | 1,822 | package uk.gov.companieshouse.service.email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uk.gov.companieshouse.exception.EmailSendException;
import uk.gov.companieshouse.kafka.message.Message;
import uk.gov.companieshouse.kafka.producer.CHKafkaProducer;
import uk.gov.companieshouse.logging.Logger;
import uk.gov.companieshouse.mapper.email.EmailMapper;
import uk.gov.companieshouse.model.dto.email.EmailDocument;
import java.util.concurrent.ExecutionException;
@Service
public class EmailService {
private final EmailSerialiser emailSerialiser;
private final EmailMapper emailMapper;
private final CHKafkaProducer kafkaProducer;
private final Logger logger;
@Autowired
public EmailService(
EmailSerialiser emailSerialiser,
EmailMapper emailMapper,
CHKafkaProducer kafkaProducer,
Logger logger
) {
this.emailSerialiser = emailSerialiser;
this.emailMapper = emailMapper;
this.kafkaProducer = kafkaProducer;
this.logger = logger;
}
public <T> void sendMessage(EmailDocument<T> emailDocument) {
try {
byte[] serialisedEmailDocument = emailSerialiser.serialise(emailDocument);
Message message = emailMapper.mapToKafkaMessage(emailDocument, serialisedEmailDocument);
kafkaProducer.send(message);
} catch (ExecutionException e) {
logger.error("Error sending message to kafka", e);
throw new EmailSendException(e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Error - thread interrupted", e);
throw new EmailSendException(e.getMessage());
}
}
}
| 33.740741 | 100 | 0.712404 |
7c3c8e6b2bb5a6746a3ebfa97d4cb21e50314da6 | 2,926 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.batch.protocol.models;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Information used to connect to an NFS file system.
*/
public class NFSMountConfiguration {
/**
* The URI of the file system to mount.
*/
@JsonProperty(value = "source", required = true)
private String source;
/**
* The relative path on the compute node where the file system will be
* mounted.
* All file systems are mounted relative to the Batch mounts directory,
* accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable.
*/
@JsonProperty(value = "relativeMountPath", required = true)
private String relativeMountPath;
/**
* Additional command line options to pass to the mount command.
* These are 'net use' options in Windows and 'mount' options in Linux.
*/
@JsonProperty(value = "mountOptions")
private String mountOptions;
/**
* Get the source value.
*
* @return the source value
*/
public String source() {
return this.source;
}
/**
* Set the source value.
*
* @param source the source value to set
* @return the NFSMountConfiguration object itself.
*/
public NFSMountConfiguration withSource(String source) {
this.source = source;
return this;
}
/**
* Get all file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable.
*
* @return the relativeMountPath value
*/
public String relativeMountPath() {
return this.relativeMountPath;
}
/**
* Set all file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable.
*
* @param relativeMountPath the relativeMountPath value to set
* @return the NFSMountConfiguration object itself.
*/
public NFSMountConfiguration withRelativeMountPath(String relativeMountPath) {
this.relativeMountPath = relativeMountPath;
return this;
}
/**
* Get these are 'net use' options in Windows and 'mount' options in Linux.
*
* @return the mountOptions value
*/
public String mountOptions() {
return this.mountOptions;
}
/**
* Set these are 'net use' options in Windows and 'mount' options in Linux.
*
* @param mountOptions the mountOptions value to set
* @return the NFSMountConfiguration object itself.
*/
public NFSMountConfiguration withMountOptions(String mountOptions) {
this.mountOptions = mountOptions;
return this;
}
}
| 29.26 | 145 | 0.670882 |
6a9bb98813d9615c9071e1dad2e5ef8ad11102d5 | 17,360 | package org.cobbzilla.wizard.main;
import fr.opensagres.xdocreport.core.io.IOUtils;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.cobbzilla.util.daemon.ZillaRuntime;
import org.cobbzilla.util.handlebars.HandlebarsUtil;
import org.cobbzilla.util.http.HttpStatusCodes;
import org.cobbzilla.util.io.FileUtil;
import org.cobbzilla.util.javascript.JsEngine;
import org.cobbzilla.util.javascript.StandardJsEngine;
import org.cobbzilla.util.main.BaseMain;
import org.cobbzilla.wizard.auth.LoginRequest;
import org.cobbzilla.wizard.client.ApiClientBase;
import org.cobbzilla.wizard.client.script.*;
import org.cobbzilla.wizard.util.RestResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.apache.commons.io.IOUtils.copy;
import static org.apache.commons.io.IOUtils.copyLarge;
import static org.cobbzilla.util.collection.ArrayUtil.arrayToString;
import static org.cobbzilla.util.collection.ArrayUtil.slice;
import static org.cobbzilla.util.daemon.ZillaRuntime.*;
import static org.cobbzilla.util.io.FileUtil.abs;
import static org.cobbzilla.util.json.JsonUtil.json;
import static org.cobbzilla.util.reflect.ReflectionUtil.copy;
import static org.cobbzilla.util.string.StringUtil.urlEncode;
import static org.cobbzilla.util.system.Sleep.sleep;
import static org.cobbzilla.util.time.TimeUtil.DAY;
import static org.cobbzilla.util.time.TimeUtil.parseDuration;
import static org.cobbzilla.wizard.main.ScriptMainOptionsBase.*;
@Slf4j
public abstract class ScriptMainBase<OPT extends ScriptMainOptionsBase>
extends MainApiBase<OPT>
implements ApiScriptIncludeHandler {
@Override protected void run() throws Exception {
final OPT options = getOptions();
final ApiRunner runner = getApiRunner();
final File[] scripts = options.getScripts();
if (options.isCallInclude()) {
if (scripts.length != 1) {
die("When "+OPT_CALL_INCLUDE+"/"+LONGOPT_CALL_INCLUDE+" is used, exactly one script argument must be provided");
}
final ApiScript wrapper = new ApiScript()
.setInclude(abs(scripts[0]))
.setParams(options.getScriptVars());
runScript(getApiClient(), options, json(new ApiScript[]{wrapper}), runner);
} else if (options.hasScripts()) {
for (File f : scripts) {
if (f.exists()) {
final String script = FileUtil.toString(f);
if (options.hasScriptVars()) {
runScript(getApiClient(), options, script, runner);
} else {
runScript(runner, script);
}
} else {
out("SKIPPING (does not exist): "+abs(f));
}
}
} else {
runScript(runner, IOUtils.toString(System.in));
}
}
@Override protected Object buildLoginRequest(OPT options) {
return new LoginRequest(options.getAccount(), options.getPassword());
}
@Override protected void setSecondFactor(Object loginRequest, String token) { notSupported("setSecondFactor"); }
public static final String AFTER_SAVE_DOWNLOAD = "save-download-to-file";
public static final String SLEEP = "sleep";
public boolean clockAdjusted = false;
protected void runScript(ApiRunner runner, String script) throws Exception {
runScript(getApiClient(), getOptions(), script, runner);
}
public static void runScript(ApiClientBase api, ScriptMainOptionsBase options, String script, ApiRunner runner) throws Exception {
if (options.hasScriptVars()) {
script = HandlebarsUtil.apply(runner.getHandlebars(), script, options.getScriptVars(),
options.getParamStartDelim(), options.getParamEndDelim());
}
runner.run(script);
}
@Override public void cleanup () {
final ApiClientBase api = getApiClient();
if (api != null && clockAdjusted) {
try {
resetClock();
} catch (Exception e) {
err("cleanup: error resetting server clock: "+e);
}
}
}
protected ScriptListener getScriptListener() {
final OPT options = getOptions();
return new ScriptListener(getClass().getName(), options.isSkipAllChecks(), options.isIncludeMailbox()) {
public JsEngine jsEngine = getJsEngine();
public Long clockMockBeforeTemp = null;
@Override public void setCtxVars(Map<String, Object> ctx) {
setScriptContextVars(ctx);
}
@Override public void beforeScript(String before, Map<String, Object> ctx) throws Exception {
// ensure the environment is in the context, prefixed with "env."
for (Map.Entry<String, String> env : System.getenv().entrySet()) {
final String envKey = "env_" + env.getKey();
if (!ctx.containsKey(envKey)) {
ctx.put(envKey, env.getValue());
}
}
final ApiRunnerListener handler = options.getBeforeHandlerObject();
if (handler != null) {
handler.beforeScript(before, ctx);
} else {
if (empty(before)) return;
if (before.startsWith(SLEEP)) {
handleSleep(before);
} else {
commonScript(before, ctx);
}
}
}
@Override public void beforeCall(ApiScript script, Map<String, Object> ctx) {
final ApiRunnerListener handler = options.getBeforeHandlerObject();
if (handler != null) handler.beforeCall(script, ctx);
}
@Override public void afterScript(String after, Map<String, Object> ctx) throws Exception {
final ApiRunnerListener handler = options.getAfterHandlerObject();
if (handler != null) {
handler.afterScript(after, ctx);
} else {
if (empty(after)) return;
if (after.startsWith(SLEEP)) {
handleSleep(after);
} else if (after.startsWith(AFTER_SAVE_DOWNLOAD)) {
if (after.equals(AFTER_SAVE_DOWNLOAD)) {
saveFile(getOptions().getTempDir(), ctx);
} else {
final RestResponse response = (RestResponse) ctx.get(ApiRunner.CTX_RESPONSE);
final String savePath = after.substring(AFTER_SAVE_DOWNLOAD.length()).trim();
if (savePath.equals("-")) {
@Cleanup final ByteArrayInputStream in = getResponseStream(response);
copyLarge(in, System.out);
} else {
saveFile(response, new File(savePath));
}
}
} else {
commonScript(after, ctx);
}
}
}
public void commonScript(String after, Map<String, Object> ctx) throws Exception {
if (after.startsWith("run-java-method ")) {
// A way to run Java inside run after (which are run inside Java ...)
runJavaMethod(after);
} else if (after.startsWith("run-bean-method ")) {
runBeanMethod(after);
} else if (after.startsWith("mock-system-clock-start ")) {
mockSystemTime(after, ctx);
} else if (after.equals("mock-system-clock-end")) {
// Dingle end ends all the mock-system-clock-start that are set (as only the latest one is active).
resetClock();
} else if (after.startsWith("delay ")) {
sleep(parseDuration(after.split(" ")[1]), "Delay");
}
}
@Override public void afterCall(ApiScript script, Map<String, Object> ctx, RestResponse response) {
final ApiRunnerListener handler = options.getAfterHandlerObject();
if (handler != null) handler.afterCall(script, ctx, response);
}
protected void mockSystemTime(String scriptCmd, Map<String, Object> ctx) throws Exception {
// Note that in case more than one mock-system-clock-start exists (without any mock-system-clock-end), the
// latest one will be active.
if (scriptCmd.startsWith("temporal-mock-system-clock ")) clockMockBeforeTemp = getSystemTimeOffset();
final long offset = parseOffset(clockMockBeforeTemp, scriptCmd, ctx, jsEngine);
final long start = realNow();
final String timeEndpoint = getTimeEndpoint();
if (timeEndpoint == null) die("mockSystemTime: no time endpoint defined");
final RestResponse remoteTimeSetResponse = getApiClient().post(timeEndpoint, "\"=" + offset + "\"");
setSystemTimeOffset(offset + (realNow() - start) / 2); // try to keep clocks close, assuming roundtrip was even on both sides
out("mockSystemTime: now=" + new Date(now()) + ", remote=" + remoteTimeSetResponse.shortString());
clockAdjusted = true;
}
private void runJavaMethod(String script) throws Exception {
if (getDebugEndpoint() == null) die("runJavaMethod: no debug endpoint defined");
getApiClient().post(getDebugEndpoint()+"/run/java-method?script="+urlEncode(script), null);
}
private void runBeanMethod(String script) throws Exception {
if (getDebugEndpoint() == null) die("runJavaMethod: no debug endpoint defined");
getApiClient().post(getDebugEndpoint()+"/run/bean-method?script="+urlEncode(script), null);
}
};
}
protected void setScriptContextVars(Map<String, Object> ctx) {}
public static void handleSleep(String arg) {
final String duration = arg.substring(SLEEP.length() + 1);
final long sleepTime = parseDuration(duration);
log.info("handleSleep: sleeping for "+duration + "("+sleepTime+" ms)");
sleep(sleepTime);
}
public static long parseOffset(Long startingOffset, String scriptCmd, Map<String, Object> ctx, JsEngine jsEngine) {
final long startOffset = startingOffset == null ? getSystemTimeOffset() : startingOffset;
long offset;
final String[] args = scriptCmd.split(" ");
if (args[1].equals("set_days")) {
// Support adding days to the current system time this way.
offset = Long.parseLong(args[2]) * DAY;
} else if (args[1].equals("add_days")) {
// Support adding days to the current system time this way.
offset = startOffset + Long.parseLong(args[2]) * DAY;
} else if (args[1].equals("epoch")) {
final String code = arrayToString(slice(args, 2, args.length), " ", "null", false);
ctx.put("days", TimeUnit.DAYS.toMillis(1));
ctx.put("hours", TimeUnit.HOURS.toMillis(1));
ctx.put("minutes", TimeUnit.MINUTES.toMillis(1));
ctx.put("seconds", TimeUnit.SECONDS.toMillis(1));
offset = jsEngine.evaluateLong(code, ctx) - realNow();
} else {
// Support setting timestamp instead of the current system time.
offset = startOffset + Long.parseLong(args[1]) - realNow();
}
return offset;
}
protected String getDebugEndpoint() { return null; }
protected String getTimeEndpoint() { return null; }
protected JsEngine getJsEngine() { return new StandardJsEngine(); }
public void resetClock() throws Exception {
setSystemTimeOffset(0);
if (getTimeEndpoint() != null) getApiClient().delete(getTimeEndpoint());
clockAdjusted = false;
}
protected ApiRunner getApiRunner() {
final ApiClientBase api = getApiClient();
api.setCaptureHeaders(getOptions().isCaptureHeaders());
return new ApiRunner(api, getScriptListener()).setIncludeHandler(this); }
@Override public String include(String path) {
final OPT options = getOptions();
final String envInclude = getPathEnvVar() == null ? null : System.getenv(getPathEnvVar());
final File includeBase = options.hasIncludeBaseDir()
? options.getIncludeBaseDir() // use option if available
: !empty(envInclude)
? new File(envInclude) // otherwise use env var if available
: options.hasScripts()
? options.getScripts()[0].getParentFile() // otherwise use first script dir
: null;
return includeFile(path, includeBase);
}
public String getPathEnvVar() { return null; }
public static String includeFile(String path, File includeBase) {
if (path.startsWith("/")) {
final File absFile = new File(path);
return absFile.exists()
? FileUtil.toStringOrDie(absFile)
: ZillaRuntime.die("include: absolute path does not exist: "+path);
}
if (includeBase == null) return ZillaRuntime.die("include: include base directory could not be determined. use "+OPT_INCLUDE_BASEDIR+"/"+LONGOPT_INCLUDE_BASEDIR);
if (!includeBase.exists() || !includeBase.isDirectory()) return ZillaRuntime.die("include: include base directory does not exist or is not a directory: "+abs(includeBase));
final File includeFile = new File(abs(includeBase + File.separator + path + ".json"));
return includeFile.exists() && includeFile.canRead()
? FileUtil.toStringOrDie(includeFile)
: ZillaRuntime.die("include: include file does not exist or is unreadable: "+abs(includeFile));
}
public static void saveFile(File tempDir, Map<String, Object> ctx) throws Exception {
final RestResponse response = (RestResponse) ctx.get(ApiRunner.CTX_RESPONSE);
final String disposition = response.header("content-disposition");
if (empty(disposition)) ZillaRuntime.die("saveFile: no content-disposition header");
final String fileName = disposition.substring(disposition.indexOf("=")+1).replace("\"", "").replaceAll("\\s+", "_");
final File file = new File(tempDir, fileName);
saveFile(response, file);
}
public static void saveFile(RestResponse response, File file) throws IOException {
@Cleanup final FileOutputStream out = new FileOutputStream(file);
@Cleanup final ByteArrayInputStream in = getResponseStream(response);
copy(in, out);
out("saveFile: "+abs(file));
}
public static ByteArrayInputStream getResponseStream(RestResponse response) {
if (response.bytes != null) {
return new ByteArrayInputStream(response.bytes);
} else if (response.json != null) {
return new ByteArrayInputStream(response.json.getBytes());
} else {
return ZillaRuntime.die("saveFile: no data found in response.bytes nor response.json");
}
}
public static class ScriptListener extends ApiRunnerListenerBase {
private boolean skipAll;
private boolean includeMailbox;
public ScriptListener(String name, boolean skipAll, boolean includeMailbox) {
super(name);
this.skipAll = skipAll;
this.includeMailbox = includeMailbox;
}
public ScriptListener (ScriptListener other) { super(other.getName()); copy(this, other); }
@Override public void beforeCall(ApiScript script, Map<String, Object> ctx) { BaseMain.out(script.getComment()); }
@Override public void afterCall(ApiScript script, Map<String, Object> ctx, RestResponse response) { MainBase.out(response); }
@Override public boolean skipCheck(ApiScript script, ApiScriptResponseCheck check) {
return skipAll || ((!includeMailbox) && check.getCondition().contains("mailbox."));
}
@Override public void unexpectedResponse(ApiScript script, RestResponse restResponse) {
final String msg;
switch (restResponse.status) {
case HttpStatusCodes.UNPROCESSABLE_ENTITY:
msg = "Invalid: "+restResponse.json;
break;
case HttpStatusCodes.NOT_FOUND:
msg = "Not Found: "+restResponse.json;
break;
case HttpStatusCodes.FORBIDDEN:
msg = "Forbidden";
break;
default:
msg = "unexpectedResponse (script="+script+"): "+restResponse;
break;
}
out(msg);
log.error(msg);
}
}
}
| 46.417112 | 180 | 0.605012 |
303ee1eabde8c1539c385b7c0b41e05816db1c91 | 3,930 | /**
* Copyright (C) 2014 Karlsruhe Institute of Technology
*
* 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 edu.kit.dama.authorization.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.xml.bind.annotation.XmlTransient;
import org.eclipse.persistence.oxm.annotations.XmlNamedAttributeNode;
import org.eclipse.persistence.oxm.annotations.XmlNamedObjectGraph;
import org.eclipse.persistence.oxm.annotations.XmlNamedObjectGraphs;
/**
* This class
*
* @author pasic
*/
@XmlNamedObjectGraphs({
@XmlNamedObjectGraph(
name = "simple",
attributeNodes = {
@XmlNamedAttributeNode(value = "resourceId", subgraph = "default")
})
,
@XmlNamedObjectGraph(
name = "default",
attributeNodes = {
@XmlNamedAttributeNode(value = "resourceId", subgraph = "default")
,
@XmlNamedAttributeNode(value = "groupId", subgraph = "simple")
})})
public class ReferenceId implements IDefaultReferenceId, ISecurableResource {
private SecurableResourceId resourceId;
private GroupId groupId;
/**
* Default constructor. Only internally used.
*/
public ReferenceId() {
}
/**
* Create a new reference id for a resource belonging to a group.
*
* @param resourceId The id of the resource.
* @param groupId The id of the group.
*/
public ReferenceId(SecurableResourceId resourceId, GroupId groupId) {
this.resourceId = resourceId;
this.groupId = groupId;
}
@Override
public GroupId getGroupId() {
return groupId;
}
/**
* Set the value of groupId
*
* @param groupId new value of groupId
*/
public void setGroupId(GroupId groupId) {
this.groupId = groupId;
}
/**
* Get the value of resourceId
*
* @return the value of resourceId
*/
@Override
public SecurableResourceId getResourceId() {
return resourceId;
}
/**
* Set the value of resourceId
*
* @param resourceId new value of resourceId
*/
public void setResourceId(SecurableResourceId resourceId) {
this.resourceId = resourceId;
}
@Override
public final boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ReferenceId other = (ReferenceId) obj;
if (this.resourceId != other.resourceId && (this.resourceId == null || !this.resourceId.equals(other.resourceId))) {
return false;
}
if (this.groupId != other.groupId && (this.groupId == null || !this.groupId.equals(other.groupId))) {
return false;
}
return true;
}
@Override
public final int hashCode() {
int hash = 3;
hash = 29 * hash + (this.resourceId != null ? this.resourceId.hashCode() : 0);
hash = 29 * hash + (this.groupId != null ? this.groupId.hashCode() : 0);
return hash;
}
@Override
public final String toString() {
return "ReferenceId{" + "resourceId=" + resourceId + ", groupId=" + groupId + '}';
}
@Override
@XmlTransient
@JsonIgnore
public final SecurableResourceId getSecurableResourceId() {
return getResourceId();
}
}
| 28.897059 | 124 | 0.627226 |
9915a7cb2ab809e1a600fd9359e11222b027a1d3 | 962 | package br.com.cadastrousuarios.controller;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "LoginBean")
@ApplicationScoped
public class LoginBean {
public Usuario usuario;
private String mensagem;
public String verificaLogin() {
if (usuario.getNome().equalsIgnoreCase("deise") && (usuario.getSenha().equals("12345"))) {
return "pages/home?faces-redirect=true";
} else {
mensagem = "Usuário ou Senha Inválidos";
return "";
}
}
public String cadastrar(){
return "pages/cadastrar?faces-redirect=true";
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
}
| 18.5 | 92 | 0.714137 |
010b18c12af8484a7b858f6b26210c74e46ca9d0 | 4,745 | package io.gitbooks.abhirockzz.jwah.chat;
import io.gitbooks.abhirockzz.jwah.chat.eventbus.ChatEventBus;
import io.gitbooks.abhirockzz.jwah.chat.internal.NewJoineeMessageEncoder;
import io.gitbooks.abhirockzz.jwah.chat.internal.LogOutMessageEncoder;
import io.gitbooks.abhirockzz.jwah.chat.internal.ReplyEncoder;
import io.gitbooks.abhirockzz.jwah.chat.internal.ChatMessageDecoder;
import io.gitbooks.abhirockzz.jwah.chat.internal.DuplicateUserMessageEncoder;
import io.gitbooks.abhirockzz.jwah.chat.internal.WelcomeMessageEncoder;
import io.gitbooks.abhirockzz.jwah.chat.model.WelcomeMessage;
import io.gitbooks.abhirockzz.jwah.chat.model.ChatMessage;
import io.gitbooks.abhirockzz.jwah.chat.model.DuplicateUserNotification;
import io.gitbooks.abhirockzz.jwah.chat.model.LogOutNotification;
import io.gitbooks.abhirockzz.jwah.chat.model.NewJoineeNotification;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(
value = "/chat/{user}/",
encoders = {ReplyEncoder.class,
WelcomeMessageEncoder.class,
NewJoineeMessageEncoder.class,
LogOutMessageEncoder.class,
DuplicateUserMessageEncoder.class},
decoders = {ChatMessageDecoder.class}
)
public class ChatServer {
private static Set<String> USERS = null;
private static final List<Session> SESSIONS = new CopyOnWriteArrayList();
private String user;
private Session s;
private boolean dupUserDetected;
public static final String LOGOUT_MSG = "[logout]";
final static String NEW_JOINEE_NOTIFICATIONS_TOPIC_NAME = "new-joinee-notifications-topic";
final static String CHAT_TOPIC_NAME = "chat-msg-topic";
final static String LOGOUT_NOTIFICATIONS_TOPIC_NAME = "logout-notifications-topic";
final static String ALL_USERS_DISTRIBUTED_SET = "all-users";
public ChatServer() {
USERS = WebSocketServerManager.getInstance().getHazelcastInstance().getSet(ALL_USERS_DISTRIBUTED_SET);
}
public static List<Session> getSessions() {
return SESSIONS;
}
@OnOpen
public void userConnectedCallback(@PathParam("user") String user, Session s) {
if (USERS.contains(user)) {
try {
dupUserDetected = true;
s.getBasicRemote().sendObject(new DuplicateUserNotification(user));
s.close();
return;
} catch (Exception ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.s = s;
SESSIONS.add(s);
s.getUserProperties().put("user", user);
this.user = user;
USERS.add(user);
welcomeNewJoinee();
announceNewJoinee();
}
private void welcomeNewJoinee() {
try {
s.getBasicRemote().sendObject(new WelcomeMessage(this.user));
} catch (Exception ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void announceNewJoinee() {
ChatEventBus.getInstance().publishNewJoineeNotification(new NewJoineeNotification(user));
System.out.println("New Joineed notification placed on HZ Topic " + NEW_JOINEE_NOTIFICATIONS_TOPIC_NAME);
}
@OnMessage
public void msgReceived(ChatMessage msg, Session s) {
msg.from(user);
if (msg.getMsg().equals(LOGOUT_MSG)) {
try {
s.close();
return;
} catch (IOException ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
ChatEventBus.getInstance().publishChat(msg);
System.out.println("Chat Message placed on HZ Topic " + CHAT_TOPIC_NAME);
}
@OnClose
public void onCloseCallback() {
if (!dupUserDetected) {
USERS.remove(this.user);
SESSIONS.remove(s);
processLogout();
}
}
private void processLogout() {
try {
ChatEventBus.getInstance().publishLogoutNotification(new LogOutNotification(user));
} catch (Exception ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| 34.136691 | 114 | 0.660695 |
d7184296e00c2399a48002abaa0f861bd2e22701 | 20,206 | package de.renew.net;
import de.renew.database.Transaction;
import de.renew.database.TransactionSource;
import de.renew.engine.common.SimulatorEventLogger;
import de.renew.engine.common.StepIdentifier;
import de.renew.engine.events.TraceEvent;
import de.renew.engine.searcher.TriggerableCollection;
import de.renew.engine.searchqueue.SearchQueue;
import de.renew.engine.simulator.SimulationThreadPool;
import de.renew.expression.LocalVariable;
import de.renew.expression.VariableMapper;
import de.renew.net.event.PlaceEventListener;
import de.renew.net.event.PlaceEventListenerSet;
import de.renew.net.event.PlaceEventProducer;
import de.renew.unify.Impossible;
import de.renew.unify.Unify;
import de.renew.unify.Variable;
import de.renew.util.DelayedFieldOwner;
import de.renew.util.Lock;
import de.renew.util.RenewObjectInputStream;
import de.renew.util.RenewObjectOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
/**
* I will collect tokens for a single place instance. I also
* keep count of the number of tokens that are currently being tested.
*
* Whenever my marking is changed I will notify my triggerables.
*
* Anybody who needs to make sure that my marking does not change should
* lock on me. Synchronisation does not help!
*/
public abstract class PlaceInstance implements PlaceEventProducer, Serializable,
DelayedFieldOwner {
public static org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(PlaceInstance.class);
static final long serialVersionUID = 562364463914372791L;
protected NetInstance netInstance;
protected Place place;
/**
* Here we store tokens that constitute the initial marking.
* These tokens are computed in the constructor, but their
* insertion must be traced later on and maybe they must even
* be inserted into the place instance.
**/
protected List<Object> initTokens;
/**
* This flag denotes whether the initial tokens have been put
* into the place instance.
*/
protected boolean earlyTokens;
/**
* This field contains those objects that might have to be triggered once after
* a change to the current marking.
*
* It is not really transient, but as we want
* to cut down the serialization recursion depth, it
* is serialized manually.
**/
transient protected TriggerableCollection triggerables;
/**
* The order in which locks are requested is governed by
* this number, which is unique within a single simulation.
*
* lockOrder and lock were originally final, but to allow the
* creation of new values on deserialization the modifier
* had to be removed.
*/
public transient long lockOrder;
/**
* The lock that controls access to this place instance.
*/
public transient Lock lock;
/**
* The listeners that want to be informed about every update
* of the current marking.
**/
protected transient PlaceEventListenerSet listeners = new PlaceEventListenerSet();
/**
* Create a new place instance for a given net instance
* reflecting a certain place. If desired, the constructor
* will already calculate in the initial marking.
*
* @param netInstance the owning net instance
* @param place the semantic level place
* @param wantInitialTokens true, if initial marking should be calculated
*/
PlaceInstance(NetInstance netInstance, Place place,
boolean wantInitialTokens) throws Impossible {
this.netInstance = netInstance;
this.place = place;
lockOrder = de.renew.util.Orderer.getTicket();
lock = new Lock();
triggerables = new TriggerableCollection();
initTokenStorage();
// Copy the early token flag. Maybe this flag changes
// later on. (Well, it shouldn't, but let's be safe.)
earlyTokens = netInstance.getNet().earlyTokens;
// Let's calculate the initial bag of tokens.
initTokens = new ArrayList<Object>();
for (TokenSource tokenSource : place.inscriptions) {
VariableMapper mapper = new VariableMapper();
Variable thisVariable = mapper.map(new LocalVariable("this", false));
Unify.unify(thisVariable, netInstance, null);
Object token = tokenSource.createToken(mapper);
initTokens.add(token);
if (earlyTokens) {
// I am requested to insert the tokens now.
internallyInsertToken(token, SearchQueue.getTime(), false);
}
}
}
protected abstract void initTokenStorage();
public String toString() {
return netInstance.toString() + "." + place.toString();
}
public NetInstance getNetInstance() {
return netInstance;
}
public Place getPlace() {
return place;
}
// Access the triggerables. We do not lock the place instance during
// accesses to the triggerables contrary to earlier implementations.
// The triggerables have to take care of locking themselves.
public TriggerableCollection triggerables() {
return triggerables;
}
public void addPlaceEventListener(PlaceEventListener listener) {
listeners.addPlaceEventListener(listener);
}
public void removePlaceEventListener(PlaceEventListener listener) {
listeners.removePlaceEventListener(listener);
}
/**
* Returns the set of currently untested tokens.
*/
public abstract Set<Object> getDistinctTokens();
/**
* Returns the set of currently untested tokens.
* At least those tokens which are unifiable with pattern
* should be included.
*/
public abstract Set<Object> getDistinctTokens(Object pattern);
public abstract Set<Object> getDistinctTestableTokens();
public abstract Set<Object> getDistinctTestableTokens(Object pattern);
public abstract int getNumberOfTokens();
/**
* Return the number of tokens that are currently tested
* by a transition, but that reside in this place.
* We do not count multiple tests on a single token as
* multiple tokens.
*/
public abstract int getNumberOfTestedTokens();
public abstract boolean isEmpty();
abstract boolean containsToken(Object token);
public abstract int getTokenCount(Object token);
public abstract TimeSet getFreeTimeSet(Object token);
// Returns the delay until a set of untested tokens
// is available that matches the given delay times.
public abstract double computeEarliestTime(Object token, TimeSet times);
// Here consider only already tested tokens.
public abstract boolean containsTestedToken(Object token);
// Here we consider both kinds of tokens.
public abstract boolean containsTestableToken(Object token);
protected IDRegistry registry() {
return netInstance.getRegistry();
}
// Make sure a token keeps its ID. Only while the
// token is reserved or contained in the place
// it is guaranteed that it keeps its ID.
public void reserve(Object token) {
// Increase the number of registrations.
registry().reserve(token);
}
public String getTokenID(Object token) {
return registry().getID(token);
}
public void unreserve(Object token) {
// Decrease the number of registrations.
registry().unreserve(token);
}
// Try to remove the token. If no token is available at
// the given time, an exception is thrown.
public abstract double removeToken(Object token, double delay)
throws Impossible;
// Multiple tests on the same token do not remove
// the token multiple times. Instead, the token is
// removed once, and the number of removals is recorded
// by a multiple insertion into the bag of tested tokens.
public abstract double testToken(Object token) throws Impossible;
/**
* This method removes all tokens from the place and
* puts them into a vector that is provided as an argument.
* The method should be used when the simulator is at rest
* or at least the place is locked and no firings are
* testing tokens. Otherwise some tested token may not
* be removable.
*
* For each token, the original time stamp is recorded
* in a second vector. The same number of elements
* is added to each vector, one entry for each token in
* the place. Multiple identical tokens result in multiple
* identical elements in the vector.
*
* @param tokens vector where removed tokens will be placed
* or null, if the tokens should be discarded.
* @param timeStamps vector where time stamps will be placed
* or null, if the tokens should be discarded.
*/
public abstract void extractAllTokens(Vector<Object> tokens,
Vector<Double> timeStamps);
/**
* This method inserts a token into the place instance and
* and tries to assign the given ID to it. It is an error,
* if the token is already registered in the place
* instance with a different ID.
*
* This method should only be called when restoring a
* simulation state from a database. Only in that case
* there is any reason to assign a particular ID to a token.
*
* @param token the token to be inserted
* @param id the token's ID
* @param time the time stamp of the token
* @exception java.lang.RuntimeException if the object was already
* registered with a different ID
*/
public void insertTokenWithID(Object token, String id, double time) {
assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread";
lock.lock();
try {
registry().setAndReserveID(token, id);
internallyInsertToken(token, time, true);
} finally {
lock.unlock();
}
}
/**
* This method inserts tokens into the place instance with notifications
* and index updates, although it will not invoke the transaction
* mechanism.
*
* This method must be used with care. It should only be called
* in those cases where an invocation of the transaction
* mechanism would be absolutely inappropriate, e.g., within
* the transaction mechanims itself or if the transaction
* is called explicitly or if a net instance is restored
* from a database or if a previous token removal that did not reach the
* database is undone.
*
* This method will take care of locking the place instance
* automatically. It is however, allowed that the current thread
* has already locked it, if this is required due to
* deadlock prevention.
*
* @param token the token to be inserted
* @param time the time stamp of the token
* @param alreadyRegistered true, if the caller has already
* registered the new token at the IDRegistry.
*/
public abstract void internallyInsertToken(Object token, double time,
boolean alreadyRegistered);
/**
* This method records the effect of a token insertion
* in a transaction object. If automatic insertion is requested,
* then the token is actually inserted after the transaction has
* been committed.
*
* @param token the token to be inserted
* @param time the time stamp of the token
* @param automaticInsertion true, if the transaction should care about
* the insertion of the token.
*/
public void transactionInsertToken(Object token, double time,
boolean automaticInsertion) {
assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread";
Transaction transaction = TransactionSource.get();
try {
transaction.addToken(this, token, time, automaticInsertion);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
/**
* Insert a token into the place instance at a specified time.
* The token deposit is written to the currently active transaction.
* Only after that transaction has been committed, the token
* will occur in the place instance. If not transaction is active,
* the deposit takes place immediately.
*
* This is the standard method call that applications should
* use to get tokens into a net. It will not print trace messages,
* but it will ultimately notify the listeners and triggerables
* of the change.
*
* This method will take care of locking the place instance
* automatically. It is however, allowed that the current thread
* has already locked the place instance, if this is required
* due to deadlock prevention.
*
* @param token the token to be inserted
* @param time the time stamp of the token
*/
public void insertToken(Object token, double time) {
assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread";
transactionInsertToken(token, time, true);
}
// Undo a testToken call. Once the last token is returned,
// a token is reinserted into the bag of free tokens.
//
// The time is used as the time stamp of the returned token,
// if the current test is the last. Otherwise, the argument is
// ignored.
public abstract void untestToken(Object token);
/**
* Print trace messages for the insertion of initial tokens.
*
*/
private void traceInitialTokens(StepIdentifier stepIdentifier) {
assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread";
Iterator<Object> iterator = initTokens.iterator();
// Anything to do?
while (iterator.hasNext()) {
Object token = iterator.next();
if (place.getTrace()) {
// log activity on net level
SimulatorEventLogger.log(stepIdentifier,
new TraceEvent("Initializing " + token
+ " into " + this), this);
}
}
}
/**
* The associated net instance will call this method while
* its creation is confirmed and trace messages are printed.
*
* I will notify the database about all tokens that I kept during
* my initialisation, if the tokens must be available early.
*
* You must call this method at most once.
*
* In fact, this method is rather a kludge in the sense
* that transaction support should not be activated
* at all if a net requests early confirmation.
*/
void earlyConfirmation() {
if (earlyTokens) {
Iterator<Object> enumeration = initTokens.iterator();
// Record each token individually in the database.
while (enumeration.hasNext()) {
Object token = enumeration.next();
double time = SearchQueue.getTime();
// Do not keep a note to insert to tokens
// at commit time. They were added already during the
// creation of this net instance.
transactionInsertToken(token, time, false);
}
}
}
/**
* My net will call this method while its creation is traced.
*
*/
void earlyConfirmationTrace(StepIdentifier stepIdentifier) {
if (earlyTokens) {
traceInitialTokens(stepIdentifier);
}
}
/**
* My net will call this method if its creation is confirmed.
* I will free all tokens that I kept during my initialisation.
*
* You must call this method at most once.
*
*/
void lateConfirmation(StepIdentifier stepIdentifier) {
if (!earlyTokens) {
traceInitialTokens(stepIdentifier);
Iterator<Object> iterator = initTokens.iterator();
// Anything to do?
while (iterator.hasNext()) {
Object token = iterator.next();
insertToken(token, SearchQueue.getTime());
}
}
// Null the field to allow garbage collection.
initTokens = null;
}
/**
* Serialization method, behaves like default writeObject
* method except storing the not-really-transient field
* triggerables.
* If the stream used is a RenewObjectOutputStream, this
* field is delayed to cut down recursion depth.
* The domain trace feature of this special stream is also
* used.
* @see de.renew.util.RenewObjectOutputStream
**/
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
RenewObjectOutputStream rOut = null;
if (out instanceof RenewObjectOutputStream) {
rOut = (RenewObjectOutputStream) out;
}
if (rOut != null) {
rOut.beginDomain(this);
}
out.defaultWriteObject();
if (rOut != null) {
rOut.delayedWriteObject(triggerables, this);
rOut.endDomain(this);
} else {
out.writeObject(triggerables);
}
}
/**
* Deserialization method, behaves like default readObject
* method except restoring additional transient fields.
* Creates new lock object and gets a new lock order ticket.
* The method also restores the not-really-transient field
* <code>triggerables</code>, <b>if</b> the
* stream used is <b>not</b> a RenewObjectInputStream.
**/
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
lockOrder = de.renew.util.Orderer.getTicket();
lock = new Lock();
listeners = new PlaceEventListenerSet();
if (in instanceof RenewObjectInputStream) {
// Do nothing, the fields will be
// reassigned by the stream soon.
} else {
triggerables = (TriggerableCollection) in.readObject();
}
}
/**
* Method used on deserialization by RenewObjectInputStream.
* Reassigns values to the not-really-transient fields,
* one at a time.
* <p>
* Subclasses must implement this method, and the first
* statement should be a call to {@link #tryReassignField}.
* Example:
* <pre>
* public void reassignField(Object value) throws java.io.IOException {
* if (!tryReassignField(value)) {
* // Subclass field assignment goes here...
* }
* }
* </pre>
* </p>
**/
public abstract void reassignField(Object value) throws java.io.IOException;
/**
* Reassigns the value to the not-really-transient field
* <code>triggerables</code>.
* <p>
* This method must be called by subclasses at the beginning
* of their {@link #reassignField} implementation.
* If the method returns <code>false</code>, the value
* was not consumed and can be used by the subclass.
* </p><p>
* If a subclass wants to override this method, a <code>super</code>
* call and correct interpretation of the return value is mandatory.
* </p>
* @param value The value to be reassigned to a field.
* @return <code>true</code> if the value was consumed <br>
* <code>false</code> if the value didn't fit to
* any delayed field of this class
**/
protected boolean tryReassignField(Object value) throws java.io.IOException { //NOTICEthrows
if (value instanceof TriggerableCollection) {
triggerables = (TriggerableCollection) value;
return true;
} else {
return false;
}
}
} | 36.017825 | 96 | 0.652133 |
b6c60429c39516a6bdf80e01a1d74d0fbaeaeb5f | 3,298 | package com.example.oculusvrdemo;
import android.content.Context;
import android.util.Log;
import com.wahoofitness.connector.HardwareConnector;
import com.wahoofitness.connector.HardwareConnectorEnums;
import com.wahoofitness.connector.HardwareConnectorTypes;
import com.wahoofitness.connector.capabilities.Capability;
import com.wahoofitness.connector.capabilities.CrankRevs;
import com.wahoofitness.connector.conn.connections.SensorConnection;
import com.wahoofitness.connector.conn.connections.params.ConnectionParams;
import com.wahoofitness.connector.listeners.discovery.DiscoveryListener;
public class Sensor implements DiscoveryListener, SensorConnection.Listener, CrankRevs.Listener {
static boolean connected = false;
Sensor(Context context){
mHardwareConnector= new HardwareConnector(context ,mHardwareConnectorCallback);
mHardwareConnector.startDiscovery(HardwareConnectorTypes.SensorType.BIKE_SPEED_CADENCE, HardwareConnectorTypes.NetworkType.BTLE,this );
}
public void onDestroy() {
mHardwareConnector.disconnectAllSensors();
mHardwareConnector.shutdown();
}
HardwareConnector mHardwareConnector;
private final HardwareConnector.Callback mHardwareConnectorCallback=new HardwareConnector.Callback(){
@Override
public void connectorStateChanged(HardwareConnectorTypes.NetworkType networkType, HardwareConnectorEnums.HardwareConnectorState hardwareConnectorState) {
}
@Override
public void connectedSensor(SensorConnection sensorConnection) {
}
@Override
public void disconnectedSensor(SensorConnection sensorConnection) {
connected = false;
}
@Override
public void hasData() {
}
@Override
public void onFirmwareUpdateRequired(SensorConnection sensorConnection, String s, String s1) {
}
};
@Override
public void onCrankRevsData(CrankRevs.Data data) {
DataToSend.sended = false;
DataToSend.data = data;
}
@Override
public void onSensorConnectionStateChanged(SensorConnection sensorConnection, HardwareConnectorEnums.SensorConnectionState sensorConnectionState) {
}
@Override
public void onSensorConnectionError(SensorConnection sensorConnection, HardwareConnectorEnums.SensorConnectionError sensorConnectionError) {
}
@Override
public void onNewCapabilityDetected(SensorConnection sensorConnection, Capability.CapabilityType capabilityType) {
if(capabilityType == Capability.CapabilityType.CrankRevs){
CrankRevs _crankRevs = (CrankRevs)sensorConnection.getCurrentCapability(Capability.CapabilityType.CrankRevs);
_crankRevs.addListener(this);
connected = true;
new TcpListener();
}
}
@Override
public void onDeviceDiscovered(ConnectionParams connectionParams) {
mHardwareConnector.requestSensorConnection(connectionParams, this);
mHardwareConnector.stopDiscovery(HardwareConnectorTypes.NetworkType.BTLE);
}
@Override
public void onDiscoveredDeviceLost(ConnectionParams connectionParams) {
}
@Override
public void onDiscoveredDeviceRssiChanged(ConnectionParams connectionParams, int i) {
}
}
| 34.354167 | 161 | 0.757732 |
3369817e825ab2220f84ee8adb97496b3ccb2b43 | 1,403 | package daggerok.app.entities;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import static javax.persistence.CascadeType.ALL;
import static javax.persistence.EnumType.STRING;
import static javax.persistence.FetchType.LAZY;
import static javax.persistence.GenerationType.IDENTITY;
@Data
@Entity
@NoArgsConstructor
@Table(name = "orders")
@Accessors(chain = true)
public class Order implements Serializable {
private static final long serialVersionUID = -7479450314788871578L;
enum Status {
ACTIVE,
INACTIVE,
DELIVERED
}
@Id
@Column(name = "order_id")
@GeneratedValue(strategy = IDENTITY)
Long id;
@Enumerated(STRING)
@Column(length = 16, nullable = false)
Status status = Status.INACTIVE;
@ManyToMany(cascade = ALL, fetch = LAZY)
@JoinTable(
name = "orders_items",
foreignKey = @ForeignKey(name = "orders_items_to_order_items"),
inverseForeignKey = @ForeignKey(name = "orders_items_to_orders"),
joinColumns = {
@JoinColumn(name = "order_id", referencedColumnName = "order_id"),
},
inverseJoinColumns = {
@JoinColumn(name = "order_item_id", referencedColumnName = "order_item_id"),
}
)
Set<OrderItem> orderItems = new LinkedHashSet<>();
}
| 25.981481 | 86 | 0.725588 |
461685e8330a42842db7711dc21731ac4809b84e | 1,277 | package com.redhat.service.smartevents.shard.operator.resources.istio;
import java.util.List;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class AuthorizationPolicySpecRuleWhen {
private String key;
private List<String> values;
public AuthorizationPolicySpecRuleWhen() {
}
public AuthorizationPolicySpecRuleWhen(String key, List<String> values) {
this.key = key;
this.values = values;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AuthorizationPolicySpecRuleWhen that = (AuthorizationPolicySpecRuleWhen) o;
return Objects.equals(key, that.key) && Objects.equals(values, that.values);
}
@Override
public int hashCode() {
return Objects.hash(key, values);
}
}
| 23.218182 | 84 | 0.634299 |
73e564d23b75099a5d828566a004310c79d35d85 | 924 | package org.esfinge.aom.simpletypesquare;
import java.util.ArrayList;
import java.util.List;
import org.esfinge.aom.model.rolemapper.metadata.annotations.EntityType;
import org.esfinge.aom.model.rolemapper.metadata.annotations.Name;
import org.esfinge.aom.model.rolemapper.metadata.annotations.PropertyType;
@EntityType
public class ProductType {
public ProductType(String productCode) {
super();
this.productCode = productCode;
}
public ProductType() {
super();
}
@Name
private String productCode;
@PropertyType
private List<InformationType> list = new ArrayList<>();
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public List<InformationType> getList() {
return list;
}
public void setList(List<InformationType> list) {
this.list = list;
}
}
| 20.533333 | 75 | 0.721861 |
f0f16388eee76ee30919469510a57588d6dbeb74 | 1,306 | package uk.gov.hmcts.reform.professionalapi.domain;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Set;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@Getter
@Setter
public class UserProfileUpdatedData {
private String email;
private String firstName;
private String lastName;
private String idamStatus;
private Set<RoleName> rolesAdd;
private Set<RoleName> rolesDelete;
@JsonCreator
public UserProfileUpdatedData(@JsonProperty(value = "email") String email,
@JsonProperty(value = "firstName") String firstName,
@JsonProperty(value = "lastName") String lastName,
@JsonProperty(value = "idamStatus") String idamStatus,
@JsonProperty(value = "rolesAdd") Set<RoleName> rolesAdd,
@JsonProperty(value = "rolesDelete") Set<RoleName> rolesDelete
) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.idamStatus = idamStatus;
this.rolesAdd = rolesAdd;
this.rolesDelete = rolesDelete;
}
}
| 28.391304 | 96 | 0.639357 |
06e79fe841ac1f7080defea5552ff2264f44a364 | 933 | package saigonwithlove.ivy.intellij.shared;
import com.intellij.AbstractBundle;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.PropertyKey;
public class IvyBundle extends AbstractBundle {
@NonNls private static final String BUNDLE = "messages.IvyBundle";
private static Reference<IvyBundle> ivyBundle;
public IvyBundle() {
super(BUNDLE);
}
public static String message(
@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, @NotNull Object... params) {
return getBundle().getMessage(key, params);
}
private static IvyBundle getBundle() {
IvyBundle bundle = com.intellij.reference.SoftReference.dereference(ivyBundle);
if (bundle == null) {
bundle = new IvyBundle();
ivyBundle = new SoftReference<>(bundle);
}
return bundle;
}
}
| 29.15625 | 93 | 0.742765 |
1a75fb4b3c69877a92c3f24508d3f53f2f565237 | 1,149 | /*
* Copyright 1999-2011 Alibaba Group Holding Ltd.
*
* 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.alibaba.druid.wall;
import java.util.List;
import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;
public interface WallVisitor extends SQLASTVisitor {
WallConfig getConfig();
WallProvider getProvider();
List<Violation> getViolations();
void addViolation(Violation violation);
boolean isDenyTable(String name);
String toSQL(SQLObject obj);
boolean isSqlModified();
void setSqlModified(boolean sqlModified);
String getDbType();
}
| 26.72093 | 75 | 0.738903 |
20673c07f610032b0735e2011084fde8f3519744 | 106 | package facade;
/**
* Created by OGC on 2016/4/12.
*/
public interface SystemA {
void systema();
}
| 11.777778 | 31 | 0.632075 |
52060f3cba7b339e9dd3cc9f2a27266e02e32803 | 1,183 | public class Divs32 {
static final int MAX_INT = 2147483647;
static final int MIN_INT = -2147483648;
public static int divS32(int numerator, int denominator) {
int quotient;
int tempAbsQuotient;
boolean quotientNeedsNegation = false;
if (denominator == 0) {
quotient = numerator >= 0 ? MAX_INT : MIN_INT;
/* Divide by zero handler */
} else {
// quotientNeedsNegation = ((numerator < 0) != (denominator < 0));
if ((numerator < 0) && (denominator > 0)) quotientNeedsNegation = true;
else if ((numerator > 0) && (denominator < 0)) quotientNeedsNegation = true;
else quotientNeedsNegation = false;
int calcDenominator;
/* replacing this computation
tempAbsQuotient = (int) (numerator >= 0 ? numerator : -numerator) /
(denominator >= 0 ? denominator : -denominator);*/
if (denominator >= 0) calcDenominator = denominator;
else calcDenominator = -denominator;
tempAbsQuotient = (int) (numerator >= 0 ? numerator : -numerator) / calcDenominator;
quotient = quotientNeedsNegation ? -(int) tempAbsQuotient : (int) tempAbsQuotient;
}
return quotient;
}
}
| 31.972973 | 90 | 0.645816 |
8a2ff85c24f03e17fb53550ccf3cb124d0be703e | 1,740 | package com.flowid.futils;
import java.io.Serializable;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.flowid.xdo.cmn.StructMessage;
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
T value = null;
StructMessage error = null;
public Result() {
}
public Result(T t) {
this.value = t;
}
public Result(int code, String message) {
error = new StructMessage().withCode(code).withMessage(message);
}
public T value() {
return value;
}
public boolean isPresent() {
return value != null;
}
public boolean notPresent() {
return !isPresent();
}
public boolean isError() {
return error != null;
}
public static <T> Result<T> value(T t) {
return new Result<T>(t);
}
public static <T> Result<T> error(int code, String message) {
return new Result<T>(code, message);
}
public Result<T> addParam(String name, String value) {
error.getParams().add(ParamUtils.param(name, value));
return this;
}
@Override
public String toString() {
ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);
if (value != null) {
sb.append("value", value);
}
if (error != null) {
sb.append("code", error.getCode())
.append("message", error.getMessage())
.append("params", ParamUtils.toString(error.getParams()));
}
return sb.toString();
}
public void setError(StructMessage err) {
error = err;
}
}
| 23.835616 | 89 | 0.598276 |
091d203e4581587df26e1ae723577df475581d64 | 8,872 | package py.com.sodep.mobileforms.impl.services.metadata.core;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import py.com.sodep.mf.exchange.objects.device.MFDevice;
import py.com.sodep.mf.exchange.objects.device.MFDeviceInfo;
import py.com.sodep.mobileforms.api.entities.application.Application;
import py.com.sodep.mobileforms.api.entities.core.Device;
import py.com.sodep.mobileforms.api.entities.core.Device.OS;
import py.com.sodep.mobileforms.api.entities.core.User;
import py.com.sodep.mobileforms.api.exceptions.AuthorizationException;
import py.com.sodep.mobileforms.api.exceptions.DeviceBlacklistedException;
import py.com.sodep.mobileforms.api.exceptions.LicenseException;
import py.com.sodep.mobileforms.api.services.license.MFLicenseManager;
import py.com.sodep.mobileforms.api.services.metadata.PagedData;
import py.com.sodep.mobileforms.api.services.metadata.applications.IApplicationService;
import py.com.sodep.mobileforms.api.services.metadata.core.IDeviceService;
import py.com.sodep.mobileforms.api.services.metadata.core.IUserService;
import py.com.sodep.mobileforms.impl.services.metadata.BaseService;
import py.com.sodep.mobileforms.license.MFApplicationLicense;
@Service("DeviceService")
@Transactional
public class DeviceService extends BaseService<Device> implements IDeviceService {
private static final Logger logger = LoggerFactory.getLogger(DeviceService.class);
@Autowired
private IUserService userService;
@Autowired
private IApplicationService applicationService;
@Autowired
private MFLicenseManager mfLicenseManager;
public DeviceService() {
super(Device.class);
}
private void associate(User user, Device device) {
List<Device> devices = user.getDevices();
if (devices == null) {
devices = new ArrayList<Device>();
user.setDevices(devices);
}
if (!devices.contains(device)) {
devices.add(device);
List<User> users = device.getUsers();
if (users == null) {
users = new ArrayList<User>();
device.setUsers(users);
}
users.add(user);
}
}
@Override
public boolean isDeviceAssociated(User user, Application app, String identifier) {
String queryStr = "SELECT d FROM " + Device.class.getSimpleName() + " d JOIN d.users u"
+ " WHERE d.deleted = false AND d.active = true AND d.identifier = :identifier "
+ " AND d.application = :application " + " AND u = :user";
TypedQuery<Device> query = em.createQuery(queryStr, Device.class);
query.setParameter("application", app);
query.setParameter("identifier", identifier);
query.setParameter("user", user);
List<Device> resultList = query.getResultList();
return !resultList.isEmpty();
}
private Device search(String model, String brand, OS os, String identifier, Application application) {
String queryStr = "FROM " + Device.class.getSimpleName()
+ " WHERE os = :os AND brand = :brand AND identifier = :identifier "
+ "AND model = :model AND application = :application";
TypedQuery<Device> query = em.createQuery(queryStr, Device.class);
query.setParameter("os", os);
query.setParameter("brand", brand);
query.setParameter("model", model);
query.setParameter("identifier", identifier);
query.setParameter("application", application);
Device device = null;
try {
device = query.getSingleResult();
} catch (NoResultException e) {
}
return device;
}
private Long countDevices(User user, Application application) {
Query query = em.createQuery("SELECT COUNT(*) FROM Device d WHERE :user MEMBER OF d.users "
+ "AND d.application = :application");
query.setParameter("user", user);
query.setParameter("application", application);
return (Long) query.getSingleResult();
}
@Override
public Device getOrCreateIfNotExists(MFDevice device) {
MFDeviceInfo deviceInfo = device.getDeviceInfo();
String model = deviceInfo.getModel();
String brand = deviceInfo.getBrand();
OS os = OS.getOS(device.getDeviceInfo().getOs());
String identifier = deviceInfo.getIdentifier();
String versionNumber = deviceInfo.getVersionNumber();
Application application = applicationService.findById(device.getApplicationId());
Device d = search(model, brand, os, identifier, application);
if (d == null) {
d = DeviceHelper.toEntity(device);
d.setApplication(application);
d = save(d);
} else {
d.setVersionNumber(versionNumber);
}
return d;
}
@Override
public void disassociateDevice(Long userId, Long deviceId) {
Query q = em.createNativeQuery("Delete from core.users_devices where user_id=:userId and device_id=:deviceId");
q.setParameter("userId", userId);
q.setParameter("deviceId", deviceId);
q.executeUpdate();
}
private void disassociateAll(Long deviceId){
Query q = em.createNativeQuery("Delete from core.users_devices where device_id=:deviceId");
q.setParameter("deviceId", deviceId);
q.executeUpdate();
}
@Override
public void associate(User user, MFDevice mfDevice) {
Device device = getOrCreateIfNotExists(mfDevice);
if (device.getBlacklisted() != null && device.getBlacklisted()) {
throw new DeviceBlacklistedException();
}
user = userService.findById(user.getId());
Application application = device.getApplication();
Long applicationId = application.getId();
if (mfLicenseManager.doesLicenseApply(applicationId)) {
MFApplicationLicense applicationLicense = mfLicenseManager.getLicense(applicationId);
Long maxDevicesPerUser = applicationLicense.getMaxDevices();
Long deviceCount = countDevices(user, application);
List<Device> devices = user.getDevices();
boolean contains = false;
if (devices != null) {
contains = devices.contains(device);
}
if (!contains && deviceCount < maxDevicesPerUser) {
associate(user, device);
} else if (!contains) {
logger.info("Too many devices for user : " + user.getMail() + " in application #" + application.getId());
throw new LicenseException("Too many devices");
}
}
}
public List<MFDevice> getDevicesOfUser(Application app, User user) {
Query q = em.createNativeQuery(
"select d.* from core.users_devices ud join core.devices d on d.id=ud.device_id "
+ "where d.application_id=:appId and ud.user_id=:userId", Device.class);
q.setParameter("appId", app.getId());
q.setParameter("userId", user.getId());
List<Device> data = q.getResultList();
ArrayList<MFDevice> dtoList = new ArrayList<MFDevice>();
for (Device device : data) {
dtoList.add(DeviceHelper.fromEntity(device));
}
return dtoList;
}
@Override
public MFDevice findById(Long deviceId) {
Device device = em.find(Device.class, deviceId);
MFDevice dto = DeviceHelper.fromEntity(device);
return dto;
}
@Override
public PagedData<List<MFDeviceInfo>> listBlacklistedDevices(Application app, String orderBy, boolean ascending,
int pageNumber, int pageSize) {
PagedData<List<Device>> devices = find(app, "blacklisted", BaseService.OPER_EQUALS, true, orderBy, ascending,
pageNumber, pageSize, false, null);
return toPagedDataOfMFDeviceInfo(devices);
}
private Device getDeviceInAppOrThrow(Application app, Long deviceId) {
Device device = em.find(Device.class, deviceId);
if(!device.getApplication().getId().equals(app.getId())){
throw new AuthorizationException();
}
return device;
}
@Override
public boolean addToBlacklist(Application app, Long deviceId) {
//TODO when blacklisted, all associations must be removed
Device device = getDeviceInAppOrThrow(app, deviceId);
if (device != null) {
device.setBlacklisted(true);
disassociateAll(deviceId);
return true;
} else {
return false;
}
}
@Override
public boolean removeFromBlacklist(Application app, Long deviceId) {
Device device = getDeviceInAppOrThrow(app, deviceId);
if (device != null) {
device.setBlacklisted(false);
return true;
} else {
return false;
}
}
private PagedData<List<MFDeviceInfo>> toPagedDataOfMFDeviceInfo(PagedData<List<Device>> from) {
PagedData<List<MFDeviceInfo>> pagedData = new PagedData<List<MFDeviceInfo>>();
List<MFDeviceInfo> mfdevicesInfo = new ArrayList<MFDeviceInfo>();
List<Device> devices = from.getData();
for (Device d : devices) {
MFDevice mfDevice = DeviceHelper.fromEntity(d);
mfdevicesInfo.add(mfDevice.getDeviceInfo());
}
pagedData.setPageSize(from.getPageSize());
pagedData.setAvailable(from.getAvailable());
pagedData.setPageNumber(from.getPageNumber());
pagedData.setTotalCount(from.getTotalCount());
pagedData.setData(mfdevicesInfo);
return pagedData;
}
}
| 34.387597 | 113 | 0.746393 |
3c5e96ed687411f0b2b79f167479c4fc443877e5 | 2,231 | package org.objectweb.asm.commons;
import org.objectweb.asm.ModuleVisitor;
public class ModuleRemapper
extends ModuleVisitor
{
private final Remapper remapper;
public ModuleRemapper(ModuleVisitor paramModuleVisitor, Remapper paramRemapper)
{
this(393216, paramModuleVisitor, paramRemapper);
}
protected ModuleRemapper(int paramInt, ModuleVisitor paramModuleVisitor, Remapper paramRemapper)
{
super(paramInt, paramModuleVisitor);
remapper = paramRemapper;
}
public void visitMainClass(String paramString)
{
super.visitMainClass(remapper.mapType(paramString));
}
public void visitPackage(String paramString)
{
super.visitPackage(remapper.mapPackageName(paramString));
}
public void visitRequire(String paramString1, int paramInt, String paramString2)
{
super.visitRequire(remapper.mapModuleName(paramString1), paramInt, paramString2);
}
public void visitExport(String paramString, int paramInt, String... paramVarArgs)
{
String[] arrayOfString = null;
if (paramVarArgs != null)
{
arrayOfString = new String[paramVarArgs.length];
for (int i = 0; i < paramVarArgs.length; i++) {
arrayOfString[i] = remapper.mapModuleName(paramVarArgs[i]);
}
}
super.visitExport(remapper.mapPackageName(paramString), paramInt, arrayOfString);
}
public void visitOpen(String paramString, int paramInt, String... paramVarArgs)
{
String[] arrayOfString = null;
if (paramVarArgs != null)
{
arrayOfString = new String[paramVarArgs.length];
for (int i = 0; i < paramVarArgs.length; i++) {
arrayOfString[i] = remapper.mapModuleName(paramVarArgs[i]);
}
}
super.visitOpen(remapper.mapPackageName(paramString), paramInt, arrayOfString);
}
public void visitUse(String paramString)
{
super.visitUse(remapper.mapType(paramString));
}
public void visitProvide(String paramString, String... paramVarArgs)
{
String[] arrayOfString = new String[paramVarArgs.length];
for (int i = 0; i < paramVarArgs.length; i++) {
arrayOfString[i] = remapper.mapType(paramVarArgs[i]);
}
super.visitProvide(remapper.mapType(paramString), arrayOfString);
}
}
| 29.355263 | 98 | 0.711788 |
9867d2652856e94f3b7c5558d6ed0cd6f02d6af9 | 2,367 | package dk.viabill.productorders.entity;
// Generated Dec 8, 2018 4:40:16 PM by Hibernate Tools 4.3.1
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
/**
* Sysdiagrams generated by hbm2java
*/
@Entity
@Table(name = "sysdiagrams",
uniqueConstraints = @UniqueConstraint(columnNames = {"principal_id", "name"})
)
public class Sysdiagrams implements java.io.Serializable {
private int diagramId;
private Integer version;
private Serializable name;
private int principalId;
private byte[] definition;
public Sysdiagrams() {
}
public Sysdiagrams(int diagramId, Serializable name, int principalId) {
this.diagramId = diagramId;
this.name = name;
this.principalId = principalId;
}
public Sysdiagrams(int diagramId, Serializable name, int principalId, byte[] definition) {
this.diagramId = diagramId;
this.name = name;
this.principalId = principalId;
this.definition = definition;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "diagram_id", unique = true, nullable = false)
public int getDiagramId() {
return this.diagramId;
}
public void setDiagramId(int diagramId) {
this.diagramId = diagramId;
}
@Version
@Column(name = "version")
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Column(name = "name", nullable = false)
public Serializable getName() {
return this.name;
}
public void setName(Serializable name) {
this.name = name;
}
@Column(name = "principal_id", nullable = false)
public int getPrincipalId() {
return this.principalId;
}
public void setPrincipalId(int principalId) {
this.principalId = principalId;
}
@Column(name = "definition")
public byte[] getDefinition() {
return this.definition;
}
public void setDefinition(byte[] definition) {
this.definition = definition;
}
}
| 25.180851 | 94 | 0.672159 |
7e323c4f9a0eca7b4cffedb90b060ef34de45510 | 976 | package me.bedaring.imsproject.models;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
/**
* @author Michael DeAngelo
* last update date: Aug 21, 2018
* purpose: This class defines the group that users are assigned to. It it used to group users into functional units
* or teams.
*/
@Entity
public class AssignedGroup {
@Id
@GeneratedValue
private int id;
@NotNull
@Size(min = 1, message = "Required field")
private String groupName;
// constructor
public AssignedGroup() { }
// follows are the accessor and modifier methods
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getGroupName() {
return this.groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
| 19.918367 | 117 | 0.670082 |
292824408004dda52d8e2b6aa0a58d4a8359cbbc | 3,582 | package net.egork.collections;
import net.egork.generated.collections.comparator.IntComparator;
import net.egork.misc.ArrayUtils;
/**
* @author egor@egork.net
*/
public class KDTree2D {
private final int[] weight;
private final int[] x;
private final int[] y;
private final int[] at;
private final int[] maX;
private final int[] maY;
private final int[] miX;
private final int[] miY;
public KDTree2D(int[] x, int[] y, int[] startWeight) {
this.x = x.clone();
this.y = y.clone();
int nodeCount = Math.max(1, Integer.highestOneBit(x.length) << 2);
weight = new int[nodeCount];
maX = new int[nodeCount];
maY = new int[nodeCount];
miX = new int[nodeCount];
miY = new int[nodeCount];
int[] order = ArrayUtils.createOrder(x.length);
init(0, 0, x.length - 1, true, startWeight, order);
at = ArrayUtils.reversePermutation(order);
ArrayUtils.orderBy(at.clone(), this.x, this.y);
}
private void init(int root, int from, int to, final boolean byX, int[] startWeight, int[] order) {
if (from != to) {
ArrayUtils.sort(order, from, to + 1, new IntComparator() {
@Override
public int compare(int first, int second) {
if (byX) {
return x[first] < x[second] ? -1 : x[first] > x[second] ? 1 : 0;
} else {
return y[first] < y[second] ? -1 : y[first] > y[second] ? 1 : 0;
}
}
});
int middle = (from + to) >> 1;
init(2 * root + 1, from, middle, !byX, startWeight, order);
init(2 * root + 2, middle + 1, to, !byX, startWeight, order);
weight[root] = weight[2 * root + 1] + weight[2 * root + 2];
miX[root] = Math.min(miX[2 * root + 1], miX[2 * root + 2]);
maX[root] = Math.max(maX[2 * root + 1], maX[2 * root + 2]);
miY[root] = Math.min(miY[2 * root + 1], miY[2 * root + 2]);
maY[root] = Math.max(maY[2 * root + 1], maY[2 * root + 2]);
} else {
weight[root] = startWeight[order[from]];
miX[root] = maX[root] = x[order[from]];
miY[root] = maY[root] = y[order[from]];
}
}
public void changeWeight(int index, int newWeight) {
changeWeight(0, 0, x.length - 1, at[index], newWeight);
}
private void changeWeight(int root, int from, int to, int at, int newWeight) {
if (from > at || to < at) {
return;
}
if (from == to) {
weight[root] = newWeight;
} else {
int middle = (from + to) >> 1;
changeWeight(2 * root + 1, from, middle, at, newWeight);
changeWeight(2 * root + 2, middle + 1, to, at, newWeight);
weight[root] = weight[2 * root + 1] + weight[2 * root + 2];
}
}
public int query(int fX, int fY, int tX, int tY) {
return query(0, 0, x.length - 1, fX, fY, tX, tY);
}
private int query(int root, int from, int to, int fX, int fY, int tX, int tY) {
if (fX <= miX[root] && fY <= miY[root] && maX[root] <= tX && maY[root] <= tY) {
return weight[root];
}
if (fX > maX[root] || fY > maY[root] || tX < miX[root] || tY < miY[root]) {
return 0;
}
int middle = (from + to) >> 1;
return query(2 * root + 1, from, middle, fX, fY, tX, tY) + query(2 * root + 2, middle + 1, to, fX, fY, tX, tY);
}
}
| 38.106383 | 119 | 0.506979 |
a1aebcd1139e0bb3ea0535e023f2b4ef6451d3ad | 2,184 | /*
* Copyright 2003 - 2020 The eFaps Team
*
* 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.efaps.pos.dto;
import java.util.Collections;
import java.util.Map;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(builder = CollectStartResponseDto.Builder.class)
public class CollectStartResponseDto
{
private final String collectOrderId;
private final Map<String, Object> details;
private CollectStartResponseDto(final Builder builder)
{
collectOrderId = builder.collectOrderId;
details = builder.details;
}
public String getCollectOrderId()
{
return collectOrderId;
}
public Map<String, Object> getDetails()
{
return details;
}
/**
* Creates builder to build {@link CollectStartResponseDto}.
* @return created builder
*/
public static Builder builder()
{
return new Builder();
}
/**
* Builder to build {@link CollectStartResponseDto}.
*/
public static final class Builder
{
private String collectOrderId;
private Map<String, Object> details = Collections.emptyMap();
private Builder()
{
}
public Builder withCollectOrderId(final String collectOrderId)
{
this.collectOrderId = collectOrderId;
return this;
}
public Builder withDetails(final Map<String, Object> details)
{
this.details = details;
return this;
}
public CollectStartResponseDto build()
{
return new CollectStartResponseDto(this);
}
}
}
| 25.103448 | 75 | 0.657967 |
0742f66c536fce7d1241a6c82a7db175b1963ee0 | 3,209 | package xyz.less.bean;
import java.io.File;
import java.util.Map;
import java.util.Set;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import xyz.less.graphic.Guis;
import xyz.less.graphic.skin.MiniSkin;
import xyz.less.graphic.skin.Skin;
import xyz.less.graphic.skin.SkinManager;
import xyz.less.media.PlaybackQueue.PlayMode;
import xyz.less.service.DefaultMediaService;
import xyz.less.service.IMediaService;
import xyz.less.util.FileUtil;
public final class AppContext {
private static final AppContext CONTEXT = new AppContext();
private Configuration config;
private Stage mainStage;
private SkinManager skinManager;
private IMediaService mediaService;
private AppContext() {
}
public static AppContext get() {
return CONTEXT;
}
public static AppContext init(String[] args) {
return get().setConfiguration(Configuration.parseFrom(args));
}
public AppContext initMainStage(Stage mainStage) {
mainStage.initStyle(StageStyle.TRANSPARENT);
mainStage.setOnCloseRequest(e -> Guis.exitApplication());
return setMainStage(mainStage);
}
public AppContext setMainStage(Stage stage) {
this.mainStage = stage;
return this;
}
public Stage getMainStage() {
return mainStage;
}
public Configuration getConfiguration() {
return config;
}
public AppContext setConfiguration(Configuration cfg) {
this.config = cfg;
return this;
}
public SkinManager getSkinManager() {
if(skinManager == null) {
skinManager = new SkinManager();
}
return skinManager;
}
public AppContext setSkinManager(SkinManager skinMgr) {
this.skinManager = skinMgr;
return this;
}
public IMediaService getMediaService() {
if(mediaService == null) {
mediaService = new DefaultMediaService();
mediaService.setMediaView(new MediaView());
mediaService.setVolume(Constants.DEFAULT_VOLUME);
mediaService.setPlayMode(PlayMode.SHUFFLE);
}
return mediaService;
}
public String getSkinName() {
return config.getSkinName();
}
public AppContext setSkinName(String name) {
config.setSkinName(name);
return this;
}
public boolean isEnableAnim() {
return config.isEnableAnim();
}
public boolean hasArgsPlaylist() {
return config.hasPlaylistUri();
}
public String getArgsPlaylistUri() {
return config.getArgsPlaylistUri();
}
public boolean isEnableCoverAperture() {
return config.isEnableCoverAperture();
}
public boolean isMiniSkin() {
return MiniSkin.NAME.equalsIgnoreCase(getSkinName());
}
public Skin switchToSkin(String skinName) {
return getSkinManager().switchToSkin(skinName);
}
public Audio getCurrent() {
return getMediaService().getCurrent();
}
public Map<String, Object> getCurrentMetadata() {
return getMediaService().getCurrentMetadata();
}
public String[] getSuffixes() {
Set<String> suffixSet = getMediaService().getSuffixSet();
return suffixSet.toArray(new String[suffixSet.size()]);
}
public boolean isFileSupported(File file) {
return FileUtil.isFileSupported(file, getSuffixes());
}
}
| 23.595588 | 64 | 0.718604 |
e9946842b100c252bc14bd27e5b8ace134083453 | 1,275 | /*
* Copyright (c) 2020 www.hoprxi.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 hr.hoprxi.domain.model.organization;
import hr.hoprxi.domain.model.brace.Name;
/***
* @author <a href="www.hoprxi.com/authors/guan xiangHuan">guan xiangHuan</a>
* @since JDK8.0
* @version 0.0.1 2019-01-07
*/
public class OrganizationSnapshot {
private String unifiedSocialCreditCode;
private Name name;
protected OrganizationSnapshot(String unifiedSocialCreditCode, Name name) {
this.unifiedSocialCreditCode = unifiedSocialCreditCode;
this.name = name;
}
public String unifiedSocialCreditCode() {
return unifiedSocialCreditCode;
}
public Name name() {
return name;
}
}
| 30.357143 | 79 | 0.716863 |
b3ad27036c5d858393ac6b9e5b2915d93da616b3 | 379 | package com.moolng.canal.es.entity.suggest;
import lombok.Data;
import java.io.Serializable;
@Data
public class Source implements Serializable {
private static final long serialVersionUID = 6501362699465908840L;
private int id;
private String content;
private NameSuggest nameSuggest;
private Integer isPicappraisal;
private Integer isContrast;
}
| 19.947368 | 68 | 0.765172 |
70bde9cd026c884c09ec411c8c8c724e8514b307 | 56 | package p;
class A{
void m(int i){
class Local{}
}
} | 9.333333 | 15 | 0.589286 |
3d235e88c8e8914e8d3ef28caa95ac6bcda62aea | 1,710 | import java.io.IOException;
import java.io.InputStream;
public class MainEntry {
public static void main(String[] args) {
// the command to execute
executeCmd("ls -oa");
}
private static void executeCmd(String string) {
InputStream pipedOut = null;
try {
Process aProcess = Runtime.getRuntime().exec(string);
// These two thread shall stop by themself when the process end
Thread pipeThread = new Thread(new StreamGobber(aProcess.getInputStream()));
Thread errorThread = new Thread(new StreamGobber(aProcess.getErrorStream()));
pipeThread.start();
errorThread.start();
aProcess.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
//Replace the following thread with your intends reader
class StreamGobber implements Runnable {
private InputStream Pipe;
public StreamGobber(InputStream pipe) {
if(pipe == null) {
throw new NullPointerException("bad pipe");
}
Pipe = pipe;
}
public void run() {
try {
byte buffer[] = new byte[2048];
int read = Pipe.read(buffer);
while(read >= 0) {
System.out.write(buffer, 0, read);
read = Pipe.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(Pipe != null) {
try {
Pipe.close();
} catch (IOException e) {
}
}
}
}
}
| 26.307692 | 89 | 0.533918 |
b8294469b693be5f6045be2072dcd01ca8b4fa8d | 529 | package com.citraining.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import tldgen.Tag;
import tldgen.TagAttribute;
@Tag
public class HelloTag extends SimpleTagSupport{
private String name;
@TagAttribute(required=true)
public void setName(String name) {
this.name = name;
}
@Override
public void doTag() throws JspException, IOException {
getJspContext().getOut().print("Hello, "+name+"!");
}
}
| 21.16 | 59 | 0.701323 |
426ca84286bee88958910866e4c473e615b3d16d | 663 | package ru.kireev.junit_mockito.auth;
import java.util.Optional;
/*
*
* Проверить логику аутентификации:
* 1) Если логин/пароль введен верно - возвращается true
* 2) Если пользователя не существует или логин/пароль введен неверно - возвращается false
*
* */
public class AuthenticationService {
private final UserDao userDao;
public AuthenticationService(UserDao userDao) {
this.userDao = userDao;
}
public boolean authenticate(String name, String password) {
return Optional.ofNullable(userDao.findByName(name))
.map(user -> user.getPassword().equals(password))
.orElse(false);
}
}
| 24.555556 | 90 | 0.689291 |
44a52e10fef9865577a42407963619a6e76b1810 | 6,947 | package com.example.borrowface.coolweather;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.borrowface.coolweather.gson.Forecast;
import com.example.borrowface.coolweather.gson.Weather;
import com.example.borrowface.coolweather.util.HttpUtil;
import com.example.borrowface.coolweather.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by borrowface on 2018/1/10.
*/
public class WeatherFragment extends Fragment {
private SwipeRefreshLayout swipeRefresh;
private String mWeatherId;
private LinearLayout forecastLayout;
private TextView degreeText;
private TextView weatherInfoText;
private TextView aqiText;
private TextView pm25Text;
private TextView comfortText;
private TextView carWashText;
private TextView sportText;
private int ID;
public String cityName;
public String updateTime;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.activity_weather,container,false);
initViews(view);
return view;
}
public static WeatherFragment newInstance(String weatherId,int ID) {
WeatherFragment f = new WeatherFragment();
Bundle args=new Bundle();
args.putString("weatherId",weatherId);
args.putInt("ID",ID);
f.setArguments(args);
return f;
}
private void initViews(View view){
// titleView = view.findViewById(R.id.degree_text);
Bundle bundle = getArguments();
// titleView.setText(bundle == null ? "" : bundle.getString("text"));
swipeRefresh=view.findViewById(R.id.swipe_refresh);
forecastLayout=view.findViewById(R.id.forecast_layout);
degreeText=view.findViewById(R.id.degree_text);
weatherInfoText=view.findViewById(R.id.weather_info_text);
aqiText=view.findViewById(R.id.aqi_text);
pm25Text=view.findViewById(R.id.pm25_text);
comfortText=view.findViewById(R.id.comfort_text);
carWashText=view.findViewById(R.id.car_wash_text);
sportText=view.findViewById(R.id.sport_text);
mWeatherId=( bundle== null ? "" : bundle.getString("weatherId"));
ID=(bundle==null?null:bundle.getInt("ID"));
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(mWeatherId);
}
});
swipeRefresh.setRefreshing(true);
requestWeather(mWeatherId);
}
public void requestWeather(final String weatherId) {
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId +
"&key=b07a2d1025c544f285347844401bd187";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), "获取天气信息失败1", Toast.LENGTH_SHORT)
.show();
swipeRefresh.setRefreshing(false);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleWeatherResponse(responseText);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)) {
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(getActivity()).edit();
editor.putString("weather", responseText);
editor.apply();
mWeatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
Toast.makeText(getContext(), "获取天气信息失败2", Toast.LENGTH_SHORT)
.show();
}
swipeRefresh.setRefreshing(false);
}
});
}
});
}
private void showWeatherInfo(Weather weather) {
String cityName = weather.basic.cityName;
String updateTime = weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature + "°C";
String weatherInfo = weather.now.more.info;
this.cityName=cityName;
this.updateTime=updateTime;
if (ID==1){
MainActivity mainActivity= (MainActivity) getActivity();
mainActivity.titleCity.setText(cityName);
mainActivity.updateTime.setText(updateTime);
}
degreeText.setText(degree);
weatherInfoText.setText(weatherInfo);
forecastLayout.removeAllViews();
for (Forecast forecast : weather.forecastList) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.forecast_item,
forecastLayout, false);
TextView dateText = view.findViewById(R.id.date_text);
TextView infoText = view.findViewById(R.id.info_text);
TextView maxText = view.findViewById(R.id.max_text);
TextView minText = view.findViewById(R.id.min_text);
dateText.setText(forecast.date);
infoText.setText(forecast.more.info);
maxText.setText(forecast.temperature.max);
minText.setText(forecast.temperature.min);
forecastLayout.addView(view);
}
if (weather.aqi != null) {
aqiText.setText(weather.aqi.city.aqi);
pm25Text.setText(weather.aqi.city.pm25);
}
String comfort = "舒适度:" + weather.suggestion.comfort.info;
String carWash = "洗车指数:" + weather.suggestion.carWash.info;
String sport = "运动建议:" + weather.suggestion.sport.info;
comfortText.setText(comfort);
carWashText.setText(carWash);
sportText.setText(sport);
// weatherLayout.setVisibility(View.VISIBLE);
}
}
| 40.389535 | 123 | 0.627609 |
939633b797536bd7b7a5e3b59c76162a1ae19966 | 1,380 | package android.support.v7.view.menu;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.p008d.p009a.C0091c;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
class ae extends ac implements SubMenu {
ae(Context context, C0091c c0091c) {
super(context, c0091c);
}
public C0091c m2154b() {
return (C0091c) this.b;
}
public void clearHeader() {
m2154b().clearHeader();
}
public MenuItem getItem() {
return m2087a(m2154b().getItem());
}
public SubMenu setHeaderIcon(int i) {
m2154b().setHeaderIcon(i);
return this;
}
public SubMenu setHeaderIcon(Drawable drawable) {
m2154b().setHeaderIcon(drawable);
return this;
}
public SubMenu setHeaderTitle(int i) {
m2154b().setHeaderTitle(i);
return this;
}
public SubMenu setHeaderTitle(CharSequence charSequence) {
m2154b().setHeaderTitle(charSequence);
return this;
}
public SubMenu setHeaderView(View view) {
m2154b().setHeaderView(view);
return this;
}
public SubMenu setIcon(int i) {
m2154b().setIcon(i);
return this;
}
public SubMenu setIcon(Drawable drawable) {
m2154b().setIcon(drawable);
return this;
}
}
| 22.258065 | 62 | 0.635507 |
dabf96606f3f8c75279e522c40b1da11e0a55035 | 451 | // SPDX-License-Identifier: MIT
package com.mercedesbenz.sechub.domain.scan.config;
/**
* Just a special variant to have possibility to change ScanMappingConfiguration
*
* @author Albert Tregnaghi
*
*/
public class DeveloperToolsScanMappingConfigurationService extends ScanMappingConfigurationService {
public void switchConfigurationIfChanged(ScanMappingConfiguration config) {
super.switchConfigurationIfChanged(config);
}
}
| 26.529412 | 100 | 0.793792 |
a341146701f7d872e45c2b99f1ae1fd04d88ea3a | 4,193 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat 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 io.fabric8.kubernetes.provider.commands;
import io.fabric8.common.util.Filter;
import io.fabric8.common.util.Objects;
import io.fabric8.kubernetes.api.Kubernetes;
import io.fabric8.kubernetes.api.KubernetesHelper;
import io.fabric8.kubernetes.api.model.CurrentState;
import io.fabric8.kubernetes.api.model.DesiredState;
import io.fabric8.kubernetes.api.model.ManifestContainer;
import io.fabric8.kubernetes.api.model.ManifestSchema;
import io.fabric8.kubernetes.api.model.PodListSchema;
import io.fabric8.kubernetes.api.model.PodSchema;
import io.fabric8.kubernetes.provider.KubernetesHelpers;
import io.fabric8.kubernetes.provider.KubernetesService;
import io.fabric8.utils.TablePrinter;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.karaf.shell.console.AbstractAction;
import java.io.PrintStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@Command(name = PodList.FUNCTION_VALUE, scope = "fabric",
description = PodList.DESCRIPTION)
public class PodListAction extends AbstractAction {
@Argument(index = 0, name = "filter", description = "The label filter", required = false)
String filterText = null;
private final KubernetesService kubernetesService;
public PodListAction(KubernetesService kubernetesService) {
this.kubernetesService = kubernetesService;
}
@Override
protected Object doExecute() throws Exception {
Kubernetes kubernetes = kubernetesService.getKubernetes();
Objects.notNull(kubernetes, "kubernetes");
PodListSchema pods = kubernetes.getPods();
KubernetesHelper.removeEmptyPods(pods);
printContainers(pods, System.out);
return null;
}
private void printContainers(PodListSchema pods, PrintStream out) {
TablePrinter table = new TablePrinter();
table.columns("id", "image(s)", "host", "labels", "status");
List<PodSchema> items = pods.getItems();
if (items == null) {
items = Collections.EMPTY_LIST;
}
Filter<PodSchema> filter = KubernetesHelpers.createPodFilter(filterText);
for (PodSchema item : items) {
if (filter.matches(item)) {
String id = item.getId();
CurrentState currentState = item.getCurrentState();
String status = "";
String host = "";
if (currentState != null) {
status = currentState.getStatus();
host = currentState.getHost();
}
Map<String, String> labelMap = item.getLabels();
String labels = KubernetesHelpers.toLabelsString(labelMap);
DesiredState desiredState = item.getDesiredState();
if (desiredState != null) {
ManifestSchema manifest = desiredState.getManifest();
if (manifest != null) {
List<ManifestContainer> containers = manifest.getContainers();
for (ManifestContainer container : containers) {
String image = container.getImage();
table.row(id, image, host, labels, status);
id = "";
host = "";
status = "";
labels = "";
}
}
}
}
}
table.print();
}
}
| 39.186916 | 93 | 0.63606 |
5f28fca863bf304d14c7530ad02e1997ea6764d5 | 14,978 | /**
* SetTopBoxCreative.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201605;
/**
* A {@code Creative} that will be served into cable set-top boxes.
* There are no assets for this
* creative type, as they are hosted by external cable systems.
*/
public class SetTopBoxCreative extends com.google.api.ads.dfp.axis.v201605.BaseVideoCreative implements java.io.Serializable {
/* An external asset identifier that is used in the cable system.
* This attribute is read-only
* after creation. */
private java.lang.String externalAssetId;
/* An identifier for the provider in the cable system. This attribute
* is read-only after creation. */
private java.lang.String providerId;
/* IDs of regions where the creative is available to serve from
* a local cable video-on-demand
* server. This attribute is optional. */
private java.lang.String[] availabilityRegionIds;
/* The date and time that this creative can begin serving from
* a local cable video-on-demand
* server. This attribute is optional. */
private com.google.api.ads.dfp.axis.v201605.DateTime licenseWindowStartDateTime;
/* The date and time that this creative can no longer be served
* from a local cable video-on-demand
* server. This attribute is optional. */
private com.google.api.ads.dfp.axis.v201605.DateTime licenseWindowEndDateTime;
public SetTopBoxCreative() {
}
public SetTopBoxCreative(
java.lang.Long advertiserId,
java.lang.Long id,
java.lang.String name,
com.google.api.ads.dfp.axis.v201605.Size size,
java.lang.String previewUrl,
com.google.api.ads.dfp.axis.v201605.CreativePolicyViolation[] policyViolations,
com.google.api.ads.dfp.axis.v201605.AppliedLabel[] appliedLabels,
com.google.api.ads.dfp.axis.v201605.DateTime lastModifiedDateTime,
com.google.api.ads.dfp.axis.v201605.BaseCustomFieldValue[] customFieldValues,
java.lang.String destinationUrl,
com.google.api.ads.dfp.axis.v201605.DestinationUrlType destinationUrlType,
java.lang.Integer duration,
java.lang.Boolean allowDurationOverride,
com.google.api.ads.dfp.axis.v201605.ConversionEvent_TrackingUrlsMapEntry[] trackingUrls,
long[] companionCreativeIds,
java.lang.String customParameters,
java.lang.String vastPreviewUrl,
com.google.api.ads.dfp.axis.v201605.SslScanResult sslScanResult,
com.google.api.ads.dfp.axis.v201605.SslManualOverride sslManualOverride,
java.lang.String externalAssetId,
java.lang.String providerId,
java.lang.String[] availabilityRegionIds,
com.google.api.ads.dfp.axis.v201605.DateTime licenseWindowStartDateTime,
com.google.api.ads.dfp.axis.v201605.DateTime licenseWindowEndDateTime) {
super(
advertiserId,
id,
name,
size,
previewUrl,
policyViolations,
appliedLabels,
lastModifiedDateTime,
customFieldValues,
destinationUrl,
destinationUrlType,
duration,
allowDurationOverride,
trackingUrls,
companionCreativeIds,
customParameters,
vastPreviewUrl,
sslScanResult,
sslManualOverride);
this.externalAssetId = externalAssetId;
this.providerId = providerId;
this.availabilityRegionIds = availabilityRegionIds;
this.licenseWindowStartDateTime = licenseWindowStartDateTime;
this.licenseWindowEndDateTime = licenseWindowEndDateTime;
}
/**
* Gets the externalAssetId value for this SetTopBoxCreative.
*
* @return externalAssetId * An external asset identifier that is used in the cable system.
* This attribute is read-only
* after creation.
*/
public java.lang.String getExternalAssetId() {
return externalAssetId;
}
/**
* Sets the externalAssetId value for this SetTopBoxCreative.
*
* @param externalAssetId * An external asset identifier that is used in the cable system.
* This attribute is read-only
* after creation.
*/
public void setExternalAssetId(java.lang.String externalAssetId) {
this.externalAssetId = externalAssetId;
}
/**
* Gets the providerId value for this SetTopBoxCreative.
*
* @return providerId * An identifier for the provider in the cable system. This attribute
* is read-only after creation.
*/
public java.lang.String getProviderId() {
return providerId;
}
/**
* Sets the providerId value for this SetTopBoxCreative.
*
* @param providerId * An identifier for the provider in the cable system. This attribute
* is read-only after creation.
*/
public void setProviderId(java.lang.String providerId) {
this.providerId = providerId;
}
/**
* Gets the availabilityRegionIds value for this SetTopBoxCreative.
*
* @return availabilityRegionIds * IDs of regions where the creative is available to serve from
* a local cable video-on-demand
* server. This attribute is optional.
*/
public java.lang.String[] getAvailabilityRegionIds() {
return availabilityRegionIds;
}
/**
* Sets the availabilityRegionIds value for this SetTopBoxCreative.
*
* @param availabilityRegionIds * IDs of regions where the creative is available to serve from
* a local cable video-on-demand
* server. This attribute is optional.
*/
public void setAvailabilityRegionIds(java.lang.String[] availabilityRegionIds) {
this.availabilityRegionIds = availabilityRegionIds;
}
public java.lang.String getAvailabilityRegionIds(int i) {
return this.availabilityRegionIds[i];
}
public void setAvailabilityRegionIds(int i, java.lang.String _value) {
this.availabilityRegionIds[i] = _value;
}
/**
* Gets the licenseWindowStartDateTime value for this SetTopBoxCreative.
*
* @return licenseWindowStartDateTime * The date and time that this creative can begin serving from
* a local cable video-on-demand
* server. This attribute is optional.
*/
public com.google.api.ads.dfp.axis.v201605.DateTime getLicenseWindowStartDateTime() {
return licenseWindowStartDateTime;
}
/**
* Sets the licenseWindowStartDateTime value for this SetTopBoxCreative.
*
* @param licenseWindowStartDateTime * The date and time that this creative can begin serving from
* a local cable video-on-demand
* server. This attribute is optional.
*/
public void setLicenseWindowStartDateTime(com.google.api.ads.dfp.axis.v201605.DateTime licenseWindowStartDateTime) {
this.licenseWindowStartDateTime = licenseWindowStartDateTime;
}
/**
* Gets the licenseWindowEndDateTime value for this SetTopBoxCreative.
*
* @return licenseWindowEndDateTime * The date and time that this creative can no longer be served
* from a local cable video-on-demand
* server. This attribute is optional.
*/
public com.google.api.ads.dfp.axis.v201605.DateTime getLicenseWindowEndDateTime() {
return licenseWindowEndDateTime;
}
/**
* Sets the licenseWindowEndDateTime value for this SetTopBoxCreative.
*
* @param licenseWindowEndDateTime * The date and time that this creative can no longer be served
* from a local cable video-on-demand
* server. This attribute is optional.
*/
public void setLicenseWindowEndDateTime(com.google.api.ads.dfp.axis.v201605.DateTime licenseWindowEndDateTime) {
this.licenseWindowEndDateTime = licenseWindowEndDateTime;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof SetTopBoxCreative)) return false;
SetTopBoxCreative other = (SetTopBoxCreative) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.externalAssetId==null && other.getExternalAssetId()==null) ||
(this.externalAssetId!=null &&
this.externalAssetId.equals(other.getExternalAssetId()))) &&
((this.providerId==null && other.getProviderId()==null) ||
(this.providerId!=null &&
this.providerId.equals(other.getProviderId()))) &&
((this.availabilityRegionIds==null && other.getAvailabilityRegionIds()==null) ||
(this.availabilityRegionIds!=null &&
java.util.Arrays.equals(this.availabilityRegionIds, other.getAvailabilityRegionIds()))) &&
((this.licenseWindowStartDateTime==null && other.getLicenseWindowStartDateTime()==null) ||
(this.licenseWindowStartDateTime!=null &&
this.licenseWindowStartDateTime.equals(other.getLicenseWindowStartDateTime()))) &&
((this.licenseWindowEndDateTime==null && other.getLicenseWindowEndDateTime()==null) ||
(this.licenseWindowEndDateTime!=null &&
this.licenseWindowEndDateTime.equals(other.getLicenseWindowEndDateTime())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getExternalAssetId() != null) {
_hashCode += getExternalAssetId().hashCode();
}
if (getProviderId() != null) {
_hashCode += getProviderId().hashCode();
}
if (getAvailabilityRegionIds() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getAvailabilityRegionIds());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getAvailabilityRegionIds(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getLicenseWindowStartDateTime() != null) {
_hashCode += getLicenseWindowStartDateTime().hashCode();
}
if (getLicenseWindowEndDateTime() != null) {
_hashCode += getLicenseWindowEndDateTime().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(SetTopBoxCreative.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201605", "SetTopBoxCreative"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("externalAssetId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201605", "externalAssetId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("providerId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201605", "providerId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("availabilityRegionIds");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201605", "availabilityRegionIds"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("licenseWindowStartDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201605", "licenseWindowStartDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201605", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("licenseWindowEndDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201605", "licenseWindowEndDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201605", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| 41.261708 | 143 | 0.652156 |
44209313bffa2cb37eeda14b00a37a4eab35ec47 | 858 | package com.github.bogdanovmn.translator.web.app.user;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class OAuth2ProviderTest {
@Test
public void parsedResponse() throws URISyntaxException, IOException {
Oauth2UserInfoResponse response = OAuth2Provider.GitHub.parsedResponse(
new String(
Files.readAllBytes(
Paths.get(
getClass().getResource("/github.json").toURI()
)
)
)
);
assertThat(
response.getExternalId(),
is("bogdanovmn")
);
assertThat(
response.getName(),
is("Mikhail N Bogdanov")
);
assertThat(
response.getEmail(),
CoreMatchers.nullValue()
);
}
} | 19.5 | 73 | 0.723776 |
65f453e7d97ea0f75c5e8a42bb243dccd42b8fdf | 567 | package com.lge.stark.model;
import com.lge.stark.Jsonizable;
public class ChannelUserMap extends Jsonizable {
private String channelId;
private String userId;
public ChannelUserMap() {
}
public ChannelUserMap(String channelId, String userId) {
this.channelId = channelId;
this.userId = userId;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
| 17.181818 | 57 | 0.733686 |
74f46569f8828fa2145f94a7744ecb3d7da4eeeb | 5,861 | package lia.advsearching;
/**
* Copyright Manning Publications Co.
*
* 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 lan
*/
import junit.framework.TestCase;
import lia.common.TestUtil;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.CachingWrapperFilter;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryWrapperFilter;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.search.SpanQueryFilter;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.TermRangeFilter;
import org.apache.lucene.search.FieldCacheTermsFilter;
import org.apache.lucene.search.FieldCacheRangeFilter;
import org.apache.lucene.search.NumericRangeFilter;
import org.apache.lucene.search.PrefixFilter;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.store.Directory;
// From chapter 5
public class FilterTest extends TestCase {
private Query allBooks;
private IndexSearcher searcher;
private Directory dir;
protected void setUp() throws Exception { // #1
allBooks = new MatchAllDocsQuery();
dir = TestUtil.getBookIndexDirectory();
searcher = new IndexSearcher(dir);
}
protected void tearDown() throws Exception {
searcher.close();
dir.close();
}
public void testTermRangeFilter() throws Exception {
Filter filter = new TermRangeFilter("title2", "d", "j", true, true);
assertEquals(3, TestUtil.hitCount(searcher, allBooks, filter));
}
/*
#1 setUp() establishes baseline book count
*/
public void testNumericDateFilter() throws Exception {
// pub date of Lucene in Action, Second Edition and
// JUnit in ACtion, Second Edition is May 2010
Filter filter = NumericRangeFilter.newIntRange("pubmonth",
201001,
201006,
true,
true);
assertEquals(2, TestUtil.hitCount(searcher, allBooks, filter));
}
public void testFieldCacheRangeFilter() throws Exception {
Filter filter = FieldCacheRangeFilter.newStringRange("title2", "d", "j", true, true);
assertEquals(3, TestUtil.hitCount(searcher, allBooks, filter));
filter = FieldCacheRangeFilter.newIntRange("pubmonth",
201001,
201006,
true,
true);
assertEquals(2, TestUtil.hitCount(searcher, allBooks, filter));
}
public void testFieldCacheTermsFilter() throws Exception {
Filter filter = new FieldCacheTermsFilter("category",
new String[] {"/health/alternative/chinese",
"/technology/computers/ai",
"/technology/computers/programming"});
assertEquals("expected 7 hits",
7,
TestUtil.hitCount(searcher, allBooks, filter));
}
public void testQueryWrapperFilter() throws Exception {
TermQuery categoryQuery =
new TermQuery(new Term("category", "/philosophy/eastern"));
Filter categoryFilter = new QueryWrapperFilter(categoryQuery);
assertEquals("only tao te ching",
1,
TestUtil.hitCount(searcher, allBooks, categoryFilter));
}
public void testSpanQueryFilter() throws Exception {
SpanQuery categoryQuery =
new SpanTermQuery(new Term("category", "/philosophy/eastern"));
Filter categoryFilter = new SpanQueryFilter(categoryQuery);
assertEquals("only tao te ching",
1,
TestUtil.hitCount(searcher, allBooks, categoryFilter));
}
public void testFilterAlternative() throws Exception {
TermQuery categoryQuery =
new TermQuery(new Term("category", "/philosophy/eastern"));
BooleanQuery constrainedQuery = new BooleanQuery();
constrainedQuery.add(allBooks, BooleanClause.Occur.MUST);
constrainedQuery.add(categoryQuery, BooleanClause.Occur.MUST);
assertEquals("only tao te ching",
1,
TestUtil.hitCount(searcher, constrainedQuery));
}
public void testPrefixFilter() throws Exception {
Filter prefixFilter = new PrefixFilter(
new Term("category",
"/technology/computers"));
assertEquals("only /technology/computers/* books",
8,
TestUtil.hitCount(searcher,
allBooks,
prefixFilter));
}
public void testCachingWrapper() throws Exception {
Filter filter = new TermRangeFilter("title2",
"d", "j",
true, true);
CachingWrapperFilter cachingFilter;
cachingFilter = new CachingWrapperFilter(filter);
assertEquals(3,
TestUtil.hitCount(searcher,
allBooks,
cachingFilter));
}
}
| 36.861635 | 89 | 0.628732 |
b2a0656bff79c7d04b588f45dae650e7d385445d | 5,801 | package com.example.aliosama.des.Model;
import java.util.ArrayList;
/**
* Created by aliosama on 12/17/2017.
*/
public class Key {
static ArrayList<KeyModel> SubKeys;
static ArrayList<String> Key_8_blocks;
static String Key;
static ArrayList<CD_Model> C_D;
static int[][] PC1 =
{{57,49, 41, 33, 25, 17, 9},
{1, 58, 50, 42, 34, 26, 18},
{10, 2, 59, 51, 43, 35, 27},
{19, 11, 3, 60, 52, 44, 36},
{63, 55, 47, 39, 31, 23, 15},
{7, 62, 54, 46, 38, 30, 22},
{14, 6, 61, 53, 45, 37, 29},
{21, 13, 5, 28, 20, 12, 4,}};
static int[][] PC2 =
{{14 ,17, 11, 24, 1, 5},
{3, 28, 15, 6, 21, 10},
{23, 19, 12, 4, 26, 8},
{16, 7, 27, 20, 13, 2},
{41, 52, 31, 37, 47, 55},
{30, 40, 51, 45, 33, 48},
{44, 49, 39, 56, 34, 53},
{46, 42, 50, 36, 29, 32}};
public Key(){
SubKeys = new ArrayList<>();
Key_8_blocks = new ArrayList<>();
Key = "";
C_D = new ArrayList<>();
}
public ArrayList<KeyModel> Generate_16_Subkeys(String keyString){
// latest modification.
// keyString = Converter.Padding(keyString);//---------Padding the Key Length
// keyString = Converter.asciiToHex(keyString);//---------Convert ASCII to Hex.
// old version.
String BinaryKey = Converter.hexToBin(keyString);//---------Convert Hex to Binary
Key_8_blocks = divide_Key_into_blocks(BinaryKey);//---------Divide key into 8 Blocks
boolean CheckOddParity = false;
CheckOddParity = check_odd_parity(Key_8_blocks);//--Check the odd parity bit
if(!CheckOddParity){
System.out.println("8 Blocks of Key :\n" +Key_8_blocks);
System.out.println("check Odd Parity : False");
return null;
}
Key = apply_pc1(Key_8_blocks);//-----------------------------Apply PC1
C_D = split_key_into_C0_and_D0(Key);//-----------------------Split C0 D0
C_D = apply_shift(C_D);//------------------------------------apply Shift;
SubKeys = apply_pc2(C_D,SubKeys);//--------------------------Key(i) = C(i) + D(i)
print(Key_8_blocks,CheckOddParity,Key,C_D,SubKeys);
return SubKeys;
}
private static void print(ArrayList<String> key_8_blocks2, boolean Check, String key2, ArrayList<CD_Model> c_D2,
ArrayList<KeyModel> subKeys2) {
if(Check){
System.out.println("8 Blocks of Key :\n" +key_8_blocks2);
System.out.println("check Odd Parity : True");
System.out.println("Key After PC1 :\n"+key2);
int count = 0;
System.out.println("C D keys:");
for (CD_Model cd_Model : C_D) {
System.out.println(count++ + " " + cd_Model.getC() + " " + cd_Model.getD());
}
System.out.println("\n Final 16 Sub Keys :");
count = 0;
for (KeyModel keyModel : SubKeys) {
System.out.println(count++ + " " + keyModel.getKey());
}
}
}
private static ArrayList<String> divide_Key_into_blocks(String Key) {
ArrayList<String>result = new ArrayList<String>();
for(int i = 0 ; i < 64; i+=8)
result.add(Key.substring(i,i+8));
return result;
}
private static boolean check_odd_parity(ArrayList<String> Key) {
for(int i = 0 ; i < Key.size(); i++){
int counter = 0;
for(int index = 0 ; index < 8 ; index++){
if(Key.get(i).charAt(index) == '1')
counter++;
}
if(counter%2 == 0)
return false;
}
return true;
}
private static String apply_pc1(ArrayList<String> key) {
String keyString = "";
for (String string : key) keyString += string;
String result = "";
for(int i = 0 ; i < 8 ; i++)
for(int j = 0; j < 7; j++)
result += keyString.charAt(PC1[i][j]-1);
return result;
}
private static ArrayList<CD_Model> split_key_into_C0_and_D0(String Key) {
ArrayList<CD_Model> result = new ArrayList<>();
result.add(new CD_Model(Key.substring(0,28), Key.substring(28,Key.length())));
return result;
}
private static ArrayList<CD_Model> apply_shift(ArrayList<CD_Model> c_d) {
for(int i = 0 ; i < 16 ; i++){
String C = c_d.get(i).getC();
String D = c_d.get(i).getD();
if(i+1 == 1 ||i+1 == 2 ||i+1 == 9 ||i+1 == 16 ){
C = C.substring(1,C.length()) + C.charAt(0);
D = D.substring(1,D.length()) + D.charAt(0);
c_d.add(new CD_Model(C,D));
}else{
C = C.substring(2,C.length()) + C.substring(0,2);
D = D.substring(2,D.length()) + D.substring(0,2);
c_d.add(new CD_Model(C,D));
}
}
return c_d;
}
private static ArrayList<KeyModel> apply_pc2(ArrayList<CD_Model> cd,ArrayList<KeyModel> subKeys) {
String oldkey = "";
subKeys = new ArrayList<>();
for (int index = 1 ; index < cd.size(); index++) {
oldkey = cd.get(index).getC()+cd.get(index).getD();
String newKey = "";
for(int i = 0 ; i < PC2.length; i++){
for(int j = 0 ; j < PC2[0].length; j++){
newKey += oldkey.charAt(PC2[i][j]-1);
}
}
subKeys.add(new KeyModel(newKey));
}
return subKeys;
}
}
| 37.915033 | 116 | 0.489054 |
f885ce759eb71e51b1de8c0c47cf039ac3d6864d | 6,270 | package eu.iamgio.jrfl.program;
import eu.iamgio.jrfl.Console;
import eu.iamgio.jrfl.Logger;
import eu.iamgio.jrfl.api.JrflPlugin;
import eu.iamgio.jrfl.api.colors.Colors;
import eu.iamgio.jrfl.api.commands.Commands;
import eu.iamgio.jrfl.api.configuration.Configuration;
import eu.iamgio.jrfl.api.configuration.SubFolder;
import eu.iamgio.jrfl.plugins.DefaultPluginLoader;
import eu.iamgio.jrfl.plugins.Plugins;
import eu.iamgio.jrfl.program.commands.*;
import eu.iamgio.jrfl.program.configuration.configs.Cache;
import eu.iamgio.jrfl.program.configuration.configs.PreferencesConfig;
import eu.iamgio.jrfl.program.configuration.configs.StyleConfig;
import eu.iamgio.jrfl.program.configuration.folders.LogsFolder;
import eu.iamgio.jrfl.program.configuration.folders.PluginsFolder;
import eu.iamgio.jrfl.program.configuration.folders.StylesFolder;
import eu.iamgio.jrfl.program.configuration.styles.Style;
import eu.iamgio.jrfl.program.nodes.Nodes;
import eu.iamgio.libfx.api.CSS;
import eu.iamgio.libfx.api.FXML;
import eu.iamgio.libfx.api.elements.SimpleStage;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.File;
/**
* Main class
* @author Gio
* @since 17/05/2017
*/
public class Jrfl extends Application {
public static final String VERSION = "1.0.0";
public static final File FOLDER = new File(System.getProperty("user.home") + File.separator + ".jrfl");
public static SubFolder stylesFolder, pluginsFolder, logsFolder;
public static Configuration cache,
preferences,
style;
public static Style ACTIVE_STYLE;
private static ExternalClassesSystem externalClassesSystem;
@Override
public void start(Stage primaryStage) throws Exception {
initConfigurations();
setup(primaryStage);
new Style(cache.get("selected-style")).setActive();
HBox.setHgrow(Nodes.PATH_LABEL, Priority.NEVER);
HBox.setHgrow(Nodes.TEXTFIELD, Priority.ALWAYS);
Colors.init();
Console console = Console.getConsole();
console.setFolder(new File(System.getProperty("user.home")));
console.sendMessage(preferences.get("messages.join") + "\n§riAmGio (c) 2017");
Commands.registerCommands(
new HelpCommand(), new PluginsCommand(), new SetStyleCommand(), new ColorsCommand(), new VariablesCommand());
for(File file : pluginsFolder.getFile().listFiles()) {
if(file.getName().endsWith(".jar")) {
DefaultPluginLoader loader = new DefaultPluginLoader(file);
loader.enablePlugin();
}
}
console.getLogger().log(Logger.TIME_PREFIX() + "[System] JRFL opened");
Runtime.getRuntime().addShutdownHook(
new Thread(() -> {
Plugins.getPlugins().forEach(JrflPlugin::onShutdown);
console.getLogger().log(Logger.TIME_PREFIX() + "[System] JRFL closed");
}));
Commands.init();
}
private void initConfigurations() {
if(!FOLDER.exists()) FOLDER.mkdir();
stylesFolder = new StylesFolder();
pluginsFolder = new PluginsFolder();
logsFolder = new LogsFolder();
cache = new Cache();
preferences = new PreferencesConfig();
style = new StyleConfig();
}
private void setup(Stage primaryStage) {
Pane root = (Pane) FXML.load(getClass(), "/assets/scenes/MainScene.fxml");
root.setPrefSize(preferences.getInt("resolution.width"), preferences.getInt("resolution.height"));
Scene scene = new Scene(root, preferences.getInt("resolution.width"), preferences.getInt("resolution.height"));
CSS.load(getClass(), scene, "/assets/stylesheets/styles.css");
ScrollPane scrollPane = new ScrollPane();
scrollPane.setId("scrollpane");
root.getChildren().add(scrollPane);
initBoxes(root, scene);
SimpleStage stage = new SimpleStage(primaryStage);
stage.setIcon(getClass(), "/assets/icon.png");
stage.show(scene, "JRFL v" + VERSION, preferences.getBoolean("resizable"));
}
private void initBoxes(Pane root, Scene scene) {
VBox vBox = Nodes.TEXT_VBOX;
HBox hBox = Nodes.TEXTBAR_HBOX;
ScrollPane scrollPane = Nodes.SCROLL_PANE;
vBox.setTranslateY(10);
vBox.setTranslateX(10);
vBox.prefWidthProperty().bind(scene.widthProperty().subtract(10));
vBox.prefHeightProperty().bind(scene.heightProperty().subtract(20).subtract(preferences.getDouble("textbar-height")));
vBox.setSpacing((preferences.getDouble("messages-spacing-level") - 1)*10-5);
hBox.setPrefWidth(scene.getWidth());
hBox.setPrefHeight(preferences.getDouble("textbar-height"));
hBox.setTranslateY(scene.getHeight() - hBox.getPrefHeight());
hBox.setSpacing(20);
root.widthProperty().addListener(o -> hBox.setPrefWidth(root.getWidth()));
root.heightProperty().addListener(o -> hBox.setTranslateY(scene.getHeight() - Nodes.TEXTBAR_HBOX.getPrefHeight()));
scrollPane.setContent(vBox);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setTranslateX(vBox.getTranslateX());
scrollPane.setTranslateY(vBox.getTranslateY());
scrollPane.maxWidthProperty().bind(vBox.prefWidthProperty());
scrollPane.prefWidthProperty().bind(vBox.prefWidthProperty());
scrollPane.prefHeightProperty().bind(vBox.prefHeightProperty());
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
}
/**
* @return Current external-classes system
*/
public static ExternalClassesSystem getExternalClassesSystem() {
if(externalClassesSystem == null) externalClassesSystem = new ExternalClassesSystem();
return externalClassesSystem;
}
public static void main(String...args) {
launch(args);
}
}
| 38.466258 | 126 | 0.689474 |
c4e2222eac6b82b2aacf3f2775ec8c07bd04cdc8 | 2,155 | /**
*
Given an array of ints, is it possible to divide the ints into two groups,
so that the sum of one group is a multiple of 10, and the sum of the other group is odd.
Every int must be in one group or the other. Write a recursive helper method that takes
whatever arguments you like, and make the initial call to your recursive helper from splitOdd10(). (No loops needed.)
splitOdd10([5, 5, 5]) → true
splitOdd10([5, 5, 6]) → false
splitOdd10([5, 5, 6, 1]) → true
*/
public class SplitOdd10 {
private static boolean splitOdd10(int[] nums) {
//Empty Array
if (nums.length == 0) {
return false;
}
//Calculate totalSum
int totalSum = 0;
for (int i = 0; i < nums.length; i++) {
totalSum = totalSum + nums[i];
}
if (totalSum % 2 == 0) {
//Even
return false;
}
int desired10Sum = totalSum - (totalSum % 10);
return splitOdd10Helper(nums, nums.length, desired10Sum);
}
private static boolean splitOdd10Helper(int[] nums, int n, int sum) {
//Base Case
if (sum == 0) {
return true;
}
//Done with all and still sum is not 0
if ( n == 0 && sum != 0) {
return false;
}
//If last element is greater than sum, exclude
if (nums[n - 1] > sum) {
return splitOdd10Helper(nums, n - 1, sum);
}
//Include
if (splitOdd10Helper(nums, n - 1, sum - nums[n - 1])) {
return true;
}
//Exclude
if (splitOdd10Helper(nums, n - 1, sum)) {
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println("Two groups one multiple of 10 and other odd for array {5, 5, 5}: " + splitOdd10(new int[]{5, 5, 5}));
System.out.println("Two groups one multiple of 10 and other odd for array {5, 5, 6}: " + splitOdd10(new int[]{5, 5, 6}));
System.out.println("Two groups one multiple of 10 and other odd for array {5, 5, 6, 1}: " + splitOdd10(new int[]{5, 5, 6, 1}));
}
}
| 29.121622 | 135 | 0.553132 |
8fbd74063a8c2b368c2a2d8e2df6c484adf02dd5 | 4,191 | /*
Copyright (C) 2008 Richard Gomes
This source code is release under the BSD License.
This file is part of JQuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://jquantlib.org/
JQuantLib is free software: you can redistribute it and/or modify it
under the terms of the JQuantLib license. You should have received a
copy of the license along with this program; if not, please email
<jquant-devel@lists.sourceforge.net>. The license is also available online at
<http://www.jquantlib.org/index.php/LICENSE.TXT>.
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 license for more details.
JQuantLib is based on QuantLib. http://quantlib.org/
When applicable, the original copyright notice follows this notice.
*/
/*
Copyright (C) 2003 Ferdinando Ametrano
Copyright (C) 2004 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
package org.jquantlib.math.interpolations;
import org.jquantlib.math.interpolations.CubicInterpolation.BoundaryCondition;
import org.jquantlib.math.interpolations.CubicInterpolation.DerivativeApprox;
import org.jquantlib.math.interpolations.factories.Bilinear;
import org.jquantlib.math.matrixutilities.Array;
import org.jquantlib.math.matrixutilities.Matrix;
/**
* Bicubic spline interpolation between discrete points
*
* @see Bicubic
*
* @author Richard Gomes
*/
// TODO: rename to BicubicSpline
public class BicubicSplineInterpolation extends AbstractInterpolation2D {
//
// private constructors
//
/**
* Constructor for a bilinear interpolation between discrete points
*
* @see Bilinear
*/
public BicubicSplineInterpolation(final Array vx, final Array vy, final Matrix mz) {
super.impl_ = new BicubicSplineImpl(vx, vy, mz);
}
//
// private inner classes
//
/**
* This class is a default implementation for {@link BilinearInterpolation} instances.
*
* @author Richard Gomes
*/
private class BicubicSplineImpl extends AbstractInterpolation2D.Impl {
private Interpolation[] splines_;
public BicubicSplineImpl(final Array vx, final Array vy, final Matrix mz) {
super(vx, vy, mz);
calculate();
}
@Override
public void calculate() {
splines_ = new Interpolation[mz.rows()];
for (int i=0; i<mz.rows(); i++) {
splines_[i] = new CubicInterpolation(
vx, mz.rangeRow(i),
DerivativeApprox.Spline, false,
BoundaryCondition.SecondDerivative, 0.0,
BoundaryCondition.SecondDerivative, 0.0);
}
}
@Override
public double op(final double x, final double y) /* @ReadOnly */ {
final double[] section = new double[splines_.length];
for (int i=0; i<splines_.length; i++) {
section[i] = splines_[i].op(x, true);
}
final CubicInterpolation spline = new CubicInterpolation(vy, new Array(section),
DerivativeApprox.Spline, false,
BoundaryCondition.SecondDerivative, 0.0,
BoundaryCondition.SecondDerivative, 0.0);
return spline.op(y, true);
}
}
}
| 35.218487 | 92 | 0.66953 |
c1f57576ba84026717c4be207d0620b67e2e1f12 | 3,534 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* 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 android.telephony.cts;
import android.content.Context;
import android.cts.util.ReadElf;
import android.cts.util.TestThread;
import android.os.Looper;
import android.net.ConnectivityManager;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.test.AndroidTestCase;
import android.content.pm.PackageManager;
import android.util.Log;
public class CellLocationTest extends AndroidTestCase{
private boolean mOnCellLocationChangedCalled;
private final Object mLock = new Object();
private TelephonyManager mTelephonyManager;
private PhoneStateListener mListener;
private static ConnectivityManager mCm;
private static final String TAG = "android.telephony.cts.CellLocationTest";
@Override
protected void setUp() throws Exception {
super.setUp();
mTelephonyManager =
(TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
mCm = (ConnectivityManager)getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
}
@Override
protected void tearDown() throws Exception {
if (mListener != null) {
// unregister listener
mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
}
super.tearDown();
}
public void testCellLocation() throws Throwable {
if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
return;
}
CellLocation cl = CellLocation.getEmpty();
if (cl instanceof GsmCellLocation) {
GsmCellLocation gcl = (GsmCellLocation) cl;
assertNotNull(gcl);
assertEquals(-1, gcl.getCid());
assertEquals(-1, gcl.getLac());
}
TestThread t = new TestThread(new Runnable() {
public void run() {
Looper.prepare();
mListener = new PhoneStateListener() {
@Override
public void onCellLocationChanged(CellLocation location) {
synchronized (mLock) {
mOnCellLocationChangedCalled = true;
mLock.notify();
}
}
};
mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_CELL_LOCATION);
Looper.loop();
}
});
t.start();
CellLocation.requestLocationUpdate();
synchronized (mLock) {
while (!mOnCellLocationChangedCalled) {
mLock.wait();
}
}
Thread.sleep(1000);
assertTrue(mOnCellLocationChangedCalled);
t.checkException();
}
}
| 34.647059 | 95 | 0.648557 |
14beb6faec225ea2df7cbc13c89653f150062683 | 1,356 | /*
* 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.sirona.cube;
import org.apache.sirona.configuration.ioc.AutoSet;
import org.apache.sirona.configuration.ioc.Created;
/**
*
*/
@AutoSet
public class AsyncHttpClientCubeBuilder
extends CubeBuilder
{
private Cube cubeInstance;
@Created
public void createInstance()
{
cubeInstance = this.build();
}
@Override
public synchronized Cube build()
{
if (cubeInstance != null)
{
return cubeInstance;
}
return new AsyncHttpClientCube( this );
}
}
| 28.25 | 75 | 0.708702 |
d37efc24b2f00df1e3f34fc2b7669d817f9f9ece | 11,933 | /*
* 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.jackrabbit.oak.segment.aws;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClientOptions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClientOptions.AmazonDynamoDBLockClientOptionsBuilder;
import com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.BillingMode;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughputDescription;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.model.UpdateTableRequest;
import com.amazonaws.services.dynamodbv2.model.WriteRequest;
import com.amazonaws.services.dynamodbv2.util.TableUtils;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public final class DynamoDBClient {
private static final String TABLE_ATTR_TIMESTAMP = "timestamp";
private static final String TABLE_ATTR_FILENAME = "filename";
public static final String TABLE_ATTR_CONTENT = "content";
private static final int TABLE_MAX_BATCH_WRITE_SIZE = 25;
private static final String LOCKTABLE_KEY = "key";
private final AmazonDynamoDB ddb;
private final String journalTableName;
private final Table journalTable;
private final String lockTableName;
private DynamoDBProvisioningData provisioningData;
public DynamoDBClient(AmazonDynamoDB ddb, String journalTableName, String lockTableName) {
this(ddb, journalTableName, lockTableName, DynamoDBProvisioningData.DEFAULT);
}
public DynamoDBClient(AmazonDynamoDB ddb, String journalTableName, String lockTableName, DynamoDBProvisioningData provisioningData) {
this.ddb = ddb;
this.journalTableName = journalTableName;
this.journalTable = new DynamoDB(ddb).getTable(journalTableName);
this.lockTableName = lockTableName;
if (provisioningData == null) {
this.provisioningData = DynamoDBProvisioningData.DEFAULT;
} else {
this.provisioningData = provisioningData;
}
}
public void ensureTables() throws IOException {
try {
CreateTableRequest createJournalTableRequest = new CreateTableRequest().withTableName(journalTableName)
.withKeySchema(new KeySchemaElement(TABLE_ATTR_FILENAME, KeyType.HASH),
new KeySchemaElement(TABLE_ATTR_TIMESTAMP, KeyType.RANGE))
.withAttributeDefinitions(new AttributeDefinition(TABLE_ATTR_FILENAME, ScalarAttributeType.S),
new AttributeDefinition(TABLE_ATTR_TIMESTAMP, ScalarAttributeType.N))
.withBillingMode(provisioningData.getBillingMode());
ensureTable(createJournalTableRequest, provisioningData.getJournalTableProvisionedRcu(), provisioningData.getJournalTableProvisionedWcu());
CreateTableRequest createLockTableRequest = new CreateTableRequest().withTableName(lockTableName)
.withKeySchema(new KeySchemaElement(LOCKTABLE_KEY, KeyType.HASH))
.withAttributeDefinitions(new AttributeDefinition(LOCKTABLE_KEY, ScalarAttributeType.S))
.withBillingMode(provisioningData.getBillingMode());
ensureTable(createLockTableRequest, provisioningData.getLockTableProvisionedRcu(), provisioningData.getLockTableProvisionedWcu());
} catch (SdkClientException | InterruptedException e) {
throw new IOException(e);
}
}
private void ensureTable(CreateTableRequest createTableRequest, Long tableRcu, Long tableWcu) throws InterruptedException {
if (provisioningData.getBillingMode().equals(BillingMode.PROVISIONED)) {
createTableRequest.withProvisionedThroughput(new ProvisionedThroughput(tableRcu, tableWcu));
}
TableUtils.createTableIfNotExists(ddb, createTableRequest);
TableUtils.waitUntilActive(ddb, createTableRequest.getTableName());
}
/**
* Updates table billing mode.
*
* @param table
* @return true if billing mode has changed
*/
private boolean updateBillingMode(Table table, Long tableRcu, Long tableWcu) {
final BillingMode currentBillingMode = BillingMode.valueOf(table.describe().getBillingModeSummary().getBillingMode());
ProvisionedThroughputDescription throughputDescription = table.getDescription().getProvisionedThroughput();
//update the table if billing mode is different or provisioned capacity has changed
if (currentBillingMode != provisioningData.getBillingMode() ||
(provisioningData.getBillingMode() == BillingMode.PROVISIONED &&
(!throughputDescription.getReadCapacityUnits().equals(tableRcu) || !throughputDescription.getReadCapacityUnits().equals(tableWcu)))) {
UpdateTableRequest tableUpdateRequest = new UpdateTableRequest()
.withTableName(table.getTableName())
.withBillingMode(provisioningData.getBillingMode());
if (provisioningData.getBillingMode().equals(BillingMode.PROVISIONED)) {
tableUpdateRequest.withProvisionedThroughput(new ProvisionedThroughput(tableRcu, tableWcu));
}
ddb.updateTable(tableUpdateRequest);
return true;
}
return false;
}
public String getConfig() {
return journalTableName + ";" + lockTableName;
}
public AmazonDynamoDBLockClientOptionsBuilder getLockClientOptionsBuilder() {
return AmazonDynamoDBLockClientOptions.builder(ddb, lockTableName).withPartitionKeyName(LOCKTABLE_KEY);
}
public void deleteAllDocuments(String fileName) throws IOException {
List<PrimaryKey> primaryKeys = getDocumentsStream(fileName).map(item -> {
return new PrimaryKey(TABLE_ATTR_FILENAME, item.getString(TABLE_ATTR_FILENAME), TABLE_ATTR_TIMESTAMP,
item.getNumber(TABLE_ATTR_TIMESTAMP));
}).collect(Collectors.toList());
for (int i = 0; i < primaryKeys.size(); i += TABLE_MAX_BATCH_WRITE_SIZE) {
PrimaryKey[] currentKeys = new PrimaryKey[Math.min(TABLE_MAX_BATCH_WRITE_SIZE, primaryKeys.size() - i)];
for (int j = 0; j < currentKeys.length; j++) {
currentKeys[j] = primaryKeys.get(i + j);
}
new DynamoDB(ddb).batchWriteItem(
new TableWriteItems(journalTableName).withPrimaryKeysToDelete(currentKeys));
}
}
public List<String> getDocumentContents(String fileName) throws IOException {
return getDocumentsStream(fileName).map(item -> item.getString(TABLE_ATTR_CONTENT))
.collect(Collectors.toList());
}
public Stream<Item> getDocumentsStream(String fileName) throws IOException {
String FILENAME_KEY = ":v_filename";
QuerySpec spec = new QuerySpec().withScanIndexForward(false)
.withKeyConditionExpression(TABLE_ATTR_FILENAME + " = " + FILENAME_KEY)
.withValueMap(new ValueMap().withString(FILENAME_KEY, fileName));
try {
ItemCollection<QueryOutcome> outcome = journalTable.query(spec);
return StreamSupport.stream(outcome.spliterator(), false);
} catch (AmazonServiceException e) {
throw new IOException(e);
}
}
public void batchPutDocument(String fileName, List<String> lines) {
List<Item> items = lines.stream()
.map(content -> toItem(fileName, content))
.collect(Collectors.toList());
batchPutDocumentItems(fileName, items);
}
public void batchPutDocumentItems(String fileName, List<Item> items) {
items.forEach(item -> item.withString(TABLE_ATTR_FILENAME, fileName));
AtomicInteger counter = new AtomicInteger();
items.stream()
.collect(Collectors.groupingBy(x -> counter.getAndIncrement() / TABLE_MAX_BATCH_WRITE_SIZE))
.values()
.forEach(chunk -> putDocumentsChunked(chunk));
}
/**
* There is a limition on the request size, see https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html
* Therefore the number of items needs to be provided as chunks by the caller.
*
* @param items chunk of items
*/
private void putDocumentsChunked(List<Item> items) {
// See explanation at https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/batch-operation-document-api-java.html
DynamoDB dynamoDB = new DynamoDB(ddb);
TableWriteItems table = new TableWriteItems(journalTableName);
BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(table.withItemsToPut(items));
do {
// Check for unprocessed keys which could happen if you exceed
// provisioned throughput
Map<String, List<WriteRequest>> unprocessedItems = outcome.getUnprocessedItems();
if (outcome.getUnprocessedItems().size() > 0) {
outcome = dynamoDB.batchWriteItemUnprocessed(unprocessedItems);
}
} while (outcome.getUnprocessedItems().size() > 0);
}
public void putDocument(String fileName, String line) throws IOException {
Item item = toItem(fileName, line);
try {
journalTable.putItem(item);
} catch (AmazonServiceException e) {
throw new IOException(e);
}
}
public Item toItem(String fileName, String line) {
// making sure that timestamps are unique by sleeping 1ms
try {
Thread.sleep(1L);
} catch (InterruptedException e) {
}
return new Item()
.with(TABLE_ATTR_TIMESTAMP, new Date().getTime())
.with(TABLE_ATTR_FILENAME, fileName)
.with(TABLE_ATTR_CONTENT, line);
}
}
| 46.796078 | 158 | 0.715662 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.