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
|
---|---|---|---|---|---|
d2518d6420940971b6d8fe66aa72f878cb61e114 | 2,935 | package com.bono.utils;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
public class PasswordEncoder {
public static final String commonPasswordKey = "TotalWingsSecureVersion1.0";
private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";
private static final int TAG_LENGTH_BIT = 128; // must be one of {128, 120, 112, 104, 96}
private static final int IV_LENGTH_BYTE = 12;
private static final int SALT_LENGTH_BYTE = 16;
private static final Charset UTF_8 = StandardCharsets.UTF_8;
public static String encrypt(String normalPassword) throws Exception {
return encrypt(normalPassword.getBytes(), commonPasswordKey);
}
// return a base64 encoded AES encrypted text
public static String encrypt(byte[] pText, String password) throws Exception {
// 16 bytes salt
byte[] salt = CryptoUtils.getRandomNonce(SALT_LENGTH_BYTE);
// GCM recommended 12 bytes iv?
byte[] iv = CryptoUtils.getRandomNonce(IV_LENGTH_BYTE);
// secret key from password
SecretKey aesKeyFromPassword = CryptoUtils.getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
// ASE-GCM needs GCMParameterSpec
cipher.init(Cipher.ENCRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] cipherText = cipher.doFinal(pText);
// prefix IV and Salt to cipher text
byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length).put(iv).put(salt)
.put(cipherText).array();
// string representation, base64, send this string to other for decryption.
return Base64.getEncoder().encodeToString(cipherTextWithIvSalt);
}
public static String decrypt(String encryptPassword) throws Exception {
return decrypt(encryptPassword, commonPasswordKey);
}
// we need the same password, salt and iv to decrypt it
public static String decrypt(String cText, String password) throws Exception {
byte[] decode = Base64.getDecoder().decode(cText.getBytes(UTF_8));
// get back the iv and salt from the cipher text
ByteBuffer bb = ByteBuffer.wrap(decode);
byte[] iv = new byte[IV_LENGTH_BYTE];
bb.get(iv);
byte[] salt = new byte[SALT_LENGTH_BYTE];
bb.get(salt);
byte[] cipherText = new byte[bb.remaining()];
bb.get(cipherText);
// get back the aes key from the same password and salt
SecretKey aesKeyFromPassword = CryptoUtils.getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] plainText = cipher.doFinal(cipherText);
return new String(plainText, UTF_8);
}
}
| 34.127907 | 115 | 0.741738 |
a0ed713543a89d041ecaa5f71a18b226027cab7a | 1,499 | package io.egen.proteus.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import io.egen.proteus.exception.LoginRequiredException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
if(request.getMethod().equals("OPTIONS")) {
System.out.println("Forwarded OPTIONS");
return true;
}
final String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
throw new LoginRequiredException();
}
final String token = authHeader.substring(7);
System.out.println(token);
final Claims claims = Jwts.parser().setSigningKey("secretkey")
.parseClaimsJws(token).getBody();
System.out.println(claims.getExpiration());
request.setAttribute("claims", claims);
return true;
}
}
| 30.591837 | 115 | 0.746498 |
38b8c30bcdadd807407fd28b7187bd7f4f051c7e | 550 | package org.owntournament.extension.korfball.models;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.owntournament.core.interfaces.models.IBaseDTO;
import javax.persistence.*;
import java.time.Instant;
@Data
@MappedSuperclass
public class BaseDTO implements IBaseDTO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
@Version
Long version;
@CreationTimestamp
private Instant createdAt;
@UpdateTimestamp
private Instant updatedAt;
}
| 19.642857 | 57 | 0.809091 |
90e1e1096c76a1dc0046047d6572e58cb1c3c9e3 | 1,077 | public class Sept7th {
public ListNode reverseList(ListNode head) {
ListNode curr = head; // 1
ListNode prev = null;
while (curr != null) {
ListNode nextTemp = curr.next; // [hold all the remaining] 2345 - 345 - 45 - 5 - null
curr.next = prev; // null - 1 - 2 - 3 - 4
prev = curr; // 1 - 2 - 3 - 4 - 5
curr = nextTemp; // remaing of chain 2345 - 345 - 45 - 5 - null
}
return prev;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
Sept7th sept7th = new Sept7th();
ListNode result = sept7th.reverseList(node1);
while (result != null) {
System.out.println(result.val);
result = result.next;
}
}
}
| 28.342105 | 97 | 0.528319 |
dd36bdd28d7fdea3dfceed6cc1c2d3e8df0d6581 | 33 | package com.dadsunion.demo.feign; | 33 | 33 | 0.848485 |
e783ae2e837d7594dace0c2dc36a7dc72727d415 | 942 | package benn1ed.curseofdisintegration;
import benn1ed.curseofdisintegration.util.Utils;
public class Frames
{
private int _maxValue;
private int _framesPassed = 0;
public Frames(int maxFrames)
{
setMaxFrames(maxFrames);
}
public int getMaxFrames()
{
return _maxValue;
}
public void setMaxFrames(int value)
{
_maxValue = value;
}
public int getFramesPassed()
{
return _framesPassed;
}
private void setFramesPassed(int value)
{
_framesPassed = Utils.clamp(value, 0, getMaxFrames());
}
private void incrementFramesPassed()
{
setFramesPassed(getFramesPassed() + 1);
}
public int getFramesLeft()
{
return getMaxFrames() - getFramesPassed();
}
public void tick()
{
incrementFramesPassed();
}
public void reset()
{
setFramesPassed(0);
}
public boolean done()
{
return getFramesPassed() >= getMaxFrames();
}
public void makeDone()
{
setFramesPassed(getMaxFrames());
}
} | 14.71875 | 56 | 0.700637 |
482c750cb3a90b081e212c53ef78709a2c0c0f70 | 412 | package chapter5.demo519;
public class Demo {
public static void main(String[] args) {
Singleton inst = Singleton.getInstance();
System.out.println(inst);//查看对象内存地址信息
inst.print();//执行对象的方法
Singleton inst2 = Singleton.getInstance();
System.out.println(inst2);//查看对象内存地址信息
inst2.print();
System.out.println(inst == inst2);//inst、inst2是否同一个实例对象
}
}
| 29.428571 | 63 | 0.640777 |
4bd3e813642b57165d4fa124a8076ade89581672 | 10,040 | /**
* 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.hive.hcatalog.api.repl;
import com.google.common.base.Function;
import org.apache.hive.hcatalog.api.HCatNotificationEvent;
import org.apache.hive.hcatalog.common.HCatConstants;
import org.apache.hive.hcatalog.messaging.MessageFactory;
/**
* ReplicationTask captures the concept of what it'd take to replicate changes from
* one warehouse to another given a notification event that captures what changed.
*/
public abstract class ReplicationTask {
protected HCatNotificationEvent event;
protected StagingDirectoryProvider srcStagingDirProvider = null;
protected StagingDirectoryProvider dstStagingDirProvider = null;
protected Function<String,String> tableNameMapping = null;
protected Function<String,String> dbNameMapping = null;
protected static MessageFactory messageFactory = MessageFactory.getInstance();
public interface Factory {
public ReplicationTask create(HCatNotificationEvent event);
}
/**
* Dummy NoopFactory for testing, returns a NoopReplicationTask for all recognized events.
* Warning : this will eventually go away or move to the test section - it's intended only
* for integration testing purposes.
*/
public static class NoopFactory implements Factory {
@Override
public ReplicationTask create(HCatNotificationEvent event) {
// TODO : Java 1.7+ support using String with switches, but IDEs don't all seem to know that.
// If casing is fine for now. But we should eventually remove this. Also, I didn't want to
// create another enum just for this.
String eventType = event.getEventType();
if (eventType.equals(HCatConstants.HCAT_CREATE_DATABASE_EVENT)) {
return new NoopReplicationTask(event);
} else if (eventType.equals(HCatConstants.HCAT_DROP_DATABASE_EVENT)) {
return new NoopReplicationTask(event);
} else if (eventType.equals(HCatConstants.HCAT_CREATE_TABLE_EVENT)) {
return new NoopReplicationTask(event);
} else if (eventType.equals(HCatConstants.HCAT_DROP_TABLE_EVENT)) {
return new NoopReplicationTask(event);
} else if (eventType.equals(HCatConstants.HCAT_ADD_PARTITION_EVENT)) {
return new NoopReplicationTask(event);
} else if (eventType.equals(HCatConstants.HCAT_DROP_PARTITION_EVENT)) {
return new NoopReplicationTask(event);
} else if (eventType.equals(HCatConstants.HCAT_ALTER_TABLE_EVENT)) {
return new NoopReplicationTask(event);
} else if (eventType.equals(HCatConstants.HCAT_ALTER_PARTITION_EVENT)) {
return new NoopReplicationTask(event);
} else if (eventType.equals(HCatConstants.HCAT_INSERT_EVENT)) {
return new NoopReplicationTask(event);
} else {
throw new IllegalStateException("Unrecognized Event type, no replication task available");
}
}
}
private static Factory factoryInstance = null;
private static Factory getFactoryInstance() {
if (factoryInstance == null){
// TODO: Eventually, we'll have a bit here that looks at a config param to instantiate
// the appropriate factory, with EXIMFactory being the default - that allows
// others to implement their own ReplicationTask.Factory for other replication
// implementations.
// That addition will be brought in by the EXIMFactory patch.
factoryInstance = new NoopFactory();
}
return factoryInstance;
}
/**
* Factory method to return appropriate subtype of ReplicationTask for given event
* @param event HCatEventMessage returned by the notification subsystem
* @return corresponding ReplicationTask
*/
public static ReplicationTask create(HCatNotificationEvent event){
if (event == null){
throw new IllegalArgumentException("event should not be null");
}
return getFactoryInstance().create(event);
}
// Primary entry point is a factory method instead of ctor
// to allow for future ctor mutabulity in design
protected ReplicationTask(HCatNotificationEvent event) {
this.event = event;
}
/**
* Returns the event that this ReplicationTask is attempting to replicate
* @return underlying event
*/
public HCatNotificationEvent getEvent(){
return this.event;
}
/**
* Returns true if the replication task in question needs to create staging
* directories to complete its operation. This will mean that you will need
* to copy these directories over to the destination warehouse for each
* source-destination warehouse pair.
* If this is true, you will need to call .withSrcStagingDirProvider(...)
* and .withDstStagingDirProvider(...) before this ReplicationTask is usable
*/
public abstract boolean needsStagingDirs();
/**
* Returns true if this ReplicationTask is prepared with all info it needs, and is
* ready to be used
*/
public boolean isActionable(){
if (! this.needsStagingDirs()) {
return true;
}
if ((srcStagingDirProvider != null) && (dstStagingDirProvider != null)){
return true;
}
return false;
}
/**
* See {@link org.apache.hive.hcatalog.api.repl.StagingDirectoryProvider}
* @param srcStagingDirProvider Staging Directory Provider for the source warehouse
* @return this
*/
public ReplicationTask withSrcStagingDirProvider(StagingDirectoryProvider srcStagingDirProvider){
this.srcStagingDirProvider = srcStagingDirProvider;
return this;
}
/**
* See {@link org.apache.hive.hcatalog.api.repl.StagingDirectoryProvider}
* @param dstStagingDirProvider Staging Directory Provider for the destination warehouse
* @return this replication task
*/
public ReplicationTask withDstStagingDirProvider(StagingDirectoryProvider dstStagingDirProvider){
this.dstStagingDirProvider = dstStagingDirProvider;
return this;
}
/**
* Allows a user to specify a table name mapping, where the the function provided maps the name of
* the table in the source warehouse to the name of the table in the dest warehouse. It is expected
* that if the mapping does not exist, it should return the same name sent in. Or, if the function
* throws an IllegalArgumentException as well, a ReplicationTask will use the same key sent in.
* That way, the default will then be that the destination db name is the same as the src db name
*
* If you want to use a Map<String,String> mapping instead of a Function<String,String>,
* simply call this function as .withTableNameMapping(com.google.common.base.Functions.forMap(tableMap))
* @param tableNameMapping
* @return this replication task
*/
public ReplicationTask withTableNameMapping(Function<String,String> tableNameMapping){
this.tableNameMapping = tableNameMapping;
return this;
}
/**
* Allows a user to specify a db name mapping, where the the function provided maps the name of
* the db in the source warehouse to the name of the db in the dest warehouse. It is expected
* that if the mapping does not exist, it should return the same name sent in. Or, if the function
* throws an IllegalArgumentException as well, a ReplicationTask will use the same key sent in.
* That way, the default will then be that the destination db name is the same as the src db name
*
* If you want to use a Map<String,String> mapping instead of a Function<String,String>,
* simply call this function as .withDb(com.google.common.base.Functions.forMap(dbMap))
* @param dbNameMapping
* @return this replication task
*/
public ReplicationTask withDbNameMapping(Function<String,String> dbNameMapping){
this.dbNameMapping = dbNameMapping;
return this;
}
protected void verifyActionable() {
if (!this.isActionable()){
throw new IllegalStateException("actionable command on task called when ReplicationTask is still not actionable.");
}
}
/**
* Returns a Iterable<Command> to send to a hive driver on the source warehouse
*
* If you *need* a List<Command> instead, you can use guava's
* ImmutableList.copyOf(iterable) or Lists.newArrayList(iterable) to
* get the underlying list, but this defeats the purpose of making this
* interface an Iterable rather than a List, since it is very likely
* that the number of Commands returned here will cause your process
* to run OOM.
*/
abstract public Iterable<? extends Command> getSrcWhCommands();
/**
* Returns a Iterable<Command> to send to a hive driver on the source warehouse
*
* If you *need* a List<Command> instead, you can use guava's
* ImmutableList.copyOf(iterable) or Lists.newArrayList(iterable) to
* get the underlying list, but this defeats the purpose of making this
* interface an Iterable rather than a List, since it is very likely
* that the number of Commands returned here will cause your process
* to run OOM.
*/
abstract public Iterable<? extends Command> getDstWhCommands();
protected void validateEventType(HCatNotificationEvent event, String allowedEventType) {
if (event == null || !allowedEventType.equals(event.getEventType())){
throw new IllegalStateException(this.getClass().getName() + " valid only for " +
allowedEventType + " events.");
}
}
}
| 42.723404 | 121 | 0.736255 |
9432d36443fc131635f6041ecb0781f2088c8d44 | 971 | package com.polydes.extrasmanager.app.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class ExtrasUtil
{
private static HashSet<String> blankSet = new HashSet<String>();
/**
* @param toOrder
* @param toExclude
* @return A list of files, minus OS and hidden files, with directories first and files second.
*/
public static List<File> orderFiles(File[] toOrder, HashSet<String> toExclude)
{
if(toExclude == null)
toExclude = blankSet;
ArrayList<File> folders = new ArrayList<File>();
ArrayList<File> files = new ArrayList<File>();
for(File f : toOrder)
{
if(f.isHidden())
continue;
if(f.getName().startsWith("."))
continue;
if(f.getName().equals("desktop.ini"))
continue;
if(toExclude.contains(f.getName()))
continue;
if(f.isDirectory())
folders.add(f);
else
files.add(f);
}
folders.addAll(files);
return folders;
}
}
| 21.108696 | 96 | 0.670443 |
7f618e7e10e67476d005792961419c92228d5f8e | 5,027 | /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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 sample.contact;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Tests {@link ContactManager}.
*
* @author David Leal
* @author Ben Alex
* @author Luke Taylor
*/
@ContextConfiguration(locations = { "/applicationContext-security.xml",
"/applicationContext-common-authorization.xml",
"/applicationContext-common-business.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class ContactManagerTests {
// ~ Instance fields
// ================================================================================================
@Autowired
protected ContactManager contactManager;
// ~ Methods
// ========================================================================================================
void assertContainsContact(long id, List<Contact> contacts) {
for (Contact contact : contacts) {
if (contact.getId().equals(Long.valueOf(id))) {
return;
}
}
fail("List of contacts should have contained: " + id);
}
void assertDoestNotContainContact(long id, List<Contact> contacts) {
for (Contact contact : contacts) {
if (contact.getId().equals(Long.valueOf(id))) {
fail("List of contact should NOT (but did) contain: " + id);
}
}
}
/**
* Locates the first <code>Contact</code> of the exact name specified.
* <p>
* Uses the {@link ContactManager#getAll()} method.
*
* @param id Identify of the contact to locate (must be an exact match)
*
* @return the domain or <code>null</code> if not found
*/
Contact getContact(String id) {
for (Contact contact : contactManager.getAll()) {
if (contact.getId().equals(id)) {
return contact;
}
}
return null;
}
private void makeActiveUser(String username) {
String password = "";
if ("rod".equals(username)) {
password = "koala";
}
else if ("dianne".equals(username)) {
password = "emu";
}
else if ("scott".equals(username)) {
password = "wombat";
}
else if ("peter".equals(username)) {
password = "opal";
}
Authentication authRequest = new UsernamePasswordAuthenticationToken(username,
password);
SecurityContextHolder.getContext().setAuthentication(authRequest);
}
@After
public void clearContext() {
SecurityContextHolder.clearContext();
}
@Test
public void testDianne() {
makeActiveUser("dianne"); // has ROLE_USER
List<Contact> contacts = contactManager.getAll();
assertEquals(4, contacts.size());
assertContainsContact(4, contacts);
assertContainsContact(5, contacts);
assertContainsContact(6, contacts);
assertContainsContact(8, contacts);
assertDoestNotContainContact(1, contacts);
assertDoestNotContainContact(2, contacts);
assertDoestNotContainContact(3, contacts);
}
@Test
public void testrod() {
makeActiveUser("rod"); // has ROLE_SUPERVISOR
List<Contact> contacts = contactManager.getAll();
assertEquals(4, contacts.size());
assertContainsContact(1, contacts);
assertContainsContact(2, contacts);
assertContainsContact(3, contacts);
assertContainsContact(4, contacts);
assertDoestNotContainContact(5, contacts);
Contact c1 = contactManager.getById(new Long(4));
contactManager.deletePermission(c1, new PrincipalSid("bob"),
BasePermission.ADMINISTRATION);
contactManager.addPermission(c1, new PrincipalSid("bob"),
BasePermission.ADMINISTRATION);
}
@Test
public void testScott() {
makeActiveUser("scott"); // has ROLE_USER
List<Contact> contacts = contactManager.getAll();
assertEquals(5, contacts.size());
assertContainsContact(4, contacts);
assertContainsContact(6, contacts);
assertContainsContact(7, contacts);
assertContainsContact(8, contacts);
assertContainsContact(9, contacts);
assertDoestNotContainContact(1, contacts);
}
}
| 28.725714 | 108 | 0.708574 |
f56648a128cb7ede038400218ca2c446919ca06b | 3,463 | package de.polocloud.api;
import com.google.inject.Injector;
import de.polocloud.api.command.ICommandManager;
import de.polocloud.api.command.executor.CommandExecutor;
import de.polocloud.api.common.PoloType;
import de.polocloud.api.config.loader.IConfigLoader;
import de.polocloud.api.config.saver.IConfigSaver;
import de.polocloud.api.event.IEventHandler;
import de.polocloud.api.gameserver.IGameServerManager;
import de.polocloud.api.network.INetworkConnection;
import de.polocloud.api.network.protocol.IProtocol;
import de.polocloud.api.player.ICloudPlayerManager;
import de.polocloud.api.pubsub.IPubSubManager;
import de.polocloud.api.template.ITemplateService;
import org.jetbrains.annotations.NotNull;
public abstract class PoloCloudAPI {
/**
* The instance of the cloud api
*/
private static PoloCloudAPI instance;
/**
* Gets the current {@link PoloCloudAPI}
*/
public static PoloCloudAPI getInstance() {
return instance;
}
/**
* Sets the {@link PoloCloudAPI} instance
*
* @param instance the instance
*/
protected static void setInstance(@NotNull PoloCloudAPI instance) {
PoloCloudAPI.instance = instance;
}
/**
* The {@link PoloType} of this cloud instance
* To identify this process as Master/Wrapper or Spigot/Proxy
*/
public abstract PoloType getType();
/**
* The current {@link INetworkConnection} to manage
* all the networking stuff like sending packets
* and registering packet handlers or
* creating and sending requests and responses
*/
public abstract INetworkConnection getConnection();
/**
* The current {@link ICommandManager} to manage all commands
*/
public abstract ICommandManager getCommandManager();
/**
* The current {@link ITemplateService} to manage
* all the cached {@link de.polocloud.api.template.ITemplate}s
*/
public abstract ITemplateService getTemplateService();
/**
* The current {@link CommandExecutor} (e.g. console)
*/
public abstract CommandExecutor getCommandExecutor();
/**
* The current {@link IGameServerManager} instance
* to manage all {@link de.polocloud.api.gameserver.IGameServer}s
*/
public abstract IGameServerManager getGameServerManager();
/**
* The current {@link ICloudPlayerManager} instance
* to manage all {@link de.polocloud.api.player.ICloudPlayer}s
*/
public abstract ICloudPlayerManager getCloudPlayerManager();
/**
* The current {@link IConfigLoader} instance to load {@link de.polocloud.api.config.IConfig}s
*/
public abstract IConfigLoader getConfigLoader();
/**
* The current {@link IConfigSaver} instance to save {@link de.polocloud.api.config.IConfig}s
*/
public abstract IConfigSaver getConfigSaver();
/**
* The current {@link IPubSubManager} to manage all
* data-flows and register channel-handlers or send data yourself
*/
public abstract IPubSubManager getPubSubManager();
/**
* The current {@link IProtocol} of the cloud
*/
public abstract IProtocol getCloudProtocol();
/**
* The current {@link IEventHandler} instance
*/
public abstract IEventHandler getEventHandler();
/**
* The current {@link Injector} instance
* (Google {@link com.google.inject.Guice})
*/
public abstract Injector getGuice();
}
| 29.853448 | 98 | 0.697661 |
06434567649de60aeb52b9d136101043f08a6cc4 | 2,248 | package com.nike.wingtips.zipkin2.util;
import com.nike.wingtips.Span;
import com.nike.wingtips.Span.SpanPurpose;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
import zipkin2.Endpoint;
/**
* Default implementation of {@link WingtipsToZipkinSpanConverter} that knows how to convert a Wingtips span to a
* Zipkin span.
*
* @author Nic Munroe
*/
public class WingtipsToZipkinSpanConverterDefaultImpl implements WingtipsToZipkinSpanConverter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public zipkin2.Span convertWingtipsSpanToZipkinSpan(Span wingtipsSpan, Endpoint zipkinEndpoint) {
long durationMicros = TimeUnit.NANOSECONDS.toMicros(wingtipsSpan.getDurationNanos());
return zipkin2.Span
.newBuilder()
.id(wingtipsSpan.getSpanId())
.name(wingtipsSpan.getSpanName())
.parentId(wingtipsSpan.getParentSpanId())
.traceId(wingtipsSpan.getTraceId())
.timestamp(wingtipsSpan.getSpanStartTimeEpochMicros())
.duration(durationMicros)
.localEndpoint(zipkinEndpoint)
.kind(determineZipkinKind(wingtipsSpan))
.build();
}
@SuppressWarnings("WeakerAccess")
protected zipkin2.Span.Kind determineZipkinKind(Span wingtipsSpan) {
SpanPurpose wtsp = wingtipsSpan.getSpanPurpose();
// Clunky if checks necessary to avoid code coverage gaps with a switch statement
// due to unreachable default case. :(
if (SpanPurpose.SERVER == wtsp) {
return zipkin2.Span.Kind.SERVER;
}
else if (SpanPurpose.CLIENT == wtsp) {
return zipkin2.Span.Kind.CLIENT;
}
else if (SpanPurpose.LOCAL_ONLY == wtsp || SpanPurpose.UNKNOWN == wtsp) {
// No Zipkin Kind associated with these SpanPurposes.
return null;
}
else {
// This case should technically be impossible, but in case it happens we'll log a warning and default to
// no Zipkin kind.
logger.warn("Unhandled SpanPurpose type: {}", String.valueOf(wtsp));
return null;
}
}
}
| 35.125 | 116 | 0.665036 |
44a8e3665979e0d7c31e1bdd0a0affff74241330 | 3,433 | package net.minecraft.world.level.material;
import java.util.Optional;
import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.core.BlockPosition;
import net.minecraft.core.EnumDirection;
import net.minecraft.core.RegistryBlockID;
import net.minecraft.core.particles.ParticleParam;
import net.minecraft.sounds.SoundEffect;
import net.minecraft.tags.Tag;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.IBlockAccess;
import net.minecraft.world.level.IWorldReader;
import net.minecraft.world.level.World;
import net.minecraft.world.level.block.state.BlockStateList;
import net.minecraft.world.level.block.state.IBlockData;
import net.minecraft.world.phys.Vec3D;
import net.minecraft.world.phys.shapes.VoxelShape;
public abstract class FluidType {
public static final RegistryBlockID<Fluid> FLUID_STATE_REGISTRY = new RegistryBlockID<>();
protected final BlockStateList<FluidType, Fluid> stateDefinition;
private Fluid defaultFluidState;
protected FluidType() {
BlockStateList.a<FluidType, Fluid> blockstatelist_a = new BlockStateList.a<>(this);
this.createFluidStateDefinition(blockstatelist_a);
this.stateDefinition = blockstatelist_a.create(FluidType::defaultFluidState, Fluid::new);
this.registerDefaultState((Fluid) this.stateDefinition.any());
}
protected void createFluidStateDefinition(BlockStateList.a<FluidType, Fluid> blockstatelist_a) {}
public BlockStateList<FluidType, Fluid> getStateDefinition() {
return this.stateDefinition;
}
protected final void registerDefaultState(Fluid fluid) {
this.defaultFluidState = fluid;
}
public final Fluid defaultFluidState() {
return this.defaultFluidState;
}
public abstract Item getBucket();
protected void animateTick(World world, BlockPosition blockposition, Fluid fluid, Random random) {}
protected void tick(World world, BlockPosition blockposition, Fluid fluid) {}
protected void randomTick(World world, BlockPosition blockposition, Fluid fluid, Random random) {}
@Nullable
protected ParticleParam getDripParticle() {
return null;
}
protected abstract boolean canBeReplacedWith(Fluid fluid, IBlockAccess iblockaccess, BlockPosition blockposition, FluidType fluidtype, EnumDirection enumdirection);
protected abstract Vec3D getFlow(IBlockAccess iblockaccess, BlockPosition blockposition, Fluid fluid);
public abstract int getTickDelay(IWorldReader iworldreader);
protected boolean isRandomlyTicking() {
return false;
}
protected boolean isEmpty() {
return false;
}
protected abstract float getExplosionResistance();
public abstract float getHeight(Fluid fluid, IBlockAccess iblockaccess, BlockPosition blockposition);
public abstract float getOwnHeight(Fluid fluid);
protected abstract IBlockData createLegacyBlock(Fluid fluid);
public abstract boolean isSource(Fluid fluid);
public abstract int getAmount(Fluid fluid);
public boolean isSame(FluidType fluidtype) {
return fluidtype == this;
}
public boolean is(Tag<FluidType> tag) {
return tag.contains(this);
}
public abstract VoxelShape getShape(Fluid fluid, IBlockAccess iblockaccess, BlockPosition blockposition);
public Optional<SoundEffect> getPickupSound() {
return Optional.empty();
}
}
| 33.656863 | 168 | 0.760559 |
bbe7c63dc14d9c16ebfb4930547b8633d283eff4 | 1,938 | package com.aclic.lottery.Models.compound;
import java.util.Date;
public class CommentMUser {
private String id;
private String newsid;
private String userid;
private String content;
private Date createtime;
private String account;
private String av;
public CommentMUser(){}
public CommentMUser(String id, String newsid, String userid, String content, Date createtime, String account) {
this.id = id;
this.newsid = newsid;
this.userid = userid;
this.content = content;
this.createtime = createtime;
this.account = account;
}
public CommentMUser(String id, String newsid, String userid, String content, Date createtime, String account, String av) {
this.id = id;
this.newsid = newsid;
this.userid = userid;
this.content = content;
this.createtime = createtime;
this.account = account;
this.av = av;
}
public String getAv() {
return av;
}
public void setAv(String av) {
this.av = av;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNewsid() {
return newsid;
}
public void setNewsid(String newsid) {
this.newsid = newsid;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
}
| 21.065217 | 126 | 0.600619 |
e4c42a665c7539d9a4887b8316f4e37d6a599f6a | 14,228 | /*
* This file was generated by openASN.1 - an open source ASN.1 toolkit for java
*
* openASN.1 is Copyright (C) 2007 Clayton Hoss, Marc Weyland
*
* openASN.1 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* openASN.1 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with openASN.1. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.uic.barcode.ticket.api.asn.omv3;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.uic.barcode.asn1.datatypes.Asn1BigInteger;
import org.uic.barcode.asn1.datatypes.Asn1Default;
import org.uic.barcode.asn1.datatypes.Asn1Optional;
import org.uic.barcode.asn1.datatypes.CharacterRestriction;
import org.uic.barcode.asn1.datatypes.FieldOrder;
import org.uic.barcode.asn1.datatypes.HasExtensionMarker;
import org.uic.barcode.asn1.datatypes.IntRange;
import org.uic.barcode.asn1.datatypes.RestrictedString;
import org.uic.barcode.asn1.datatypes.Sequence;
import org.uic.barcode.asn1.datatypesimpl.SequenceOfStringIA5;
import org.uic.barcode.ticket.api.asn.omv3.SequenceOfActivatedDays;
import org.uic.barcode.ticket.api.utils.DateTimeUtils;
@Sequence
@HasExtensionMarker
public class PassData extends Object {
public PassData() {
}
@FieldOrder(order = 0)
@Asn1Optional public Asn1BigInteger referenceNum;
@FieldOrder(order = 1)
@RestrictedString(CharacterRestriction.IA5String)
@Asn1Optional public String referenceIA5;
@FieldOrder(order = 2)
@IntRange(minValue=1,maxValue=32000)
@Asn1Optional public Long productOwnerNum;
@FieldOrder(order = 3)
@RestrictedString(CharacterRestriction.IA5String)
@Asn1Optional public String productOwnerIA5;
@FieldOrder(order = 4)
@IntRange(minValue=0,maxValue=65535)
@Asn1Optional public Long productIdNum;
@FieldOrder(order = 5)
@RestrictedString(CharacterRestriction.IA5String)
@Asn1Optional public String productIdIA5;
@FieldOrder(order = 6)
@IntRange(minValue=1,maxValue=250)
@Asn1Optional public Long passType;
@FieldOrder(order = 7)
@RestrictedString(CharacterRestriction.UTF8String)
@Asn1Optional public String passDescription;
@FieldOrder(order = 8)
@Asn1Default (value="second")
@Asn1Optional public TravelClassType classCode;
@FieldOrder(order = 9)
@IntRange(minValue=-367,maxValue=700)
@Asn1Optional public Long validFromDay;
@FieldOrder(order = 10)
@IntRange(minValue=0,maxValue=1439)
@Asn1Optional public Long validFromTime;
@FieldOrder(order = 11)
@IntRange(minValue=-60, maxValue=60)
@Asn1Optional public Long validFromUTCOffset;
@FieldOrder(order = 12)
@IntRange(minValue=-1,maxValue=370)
@Asn1Optional public Long validUntilDay;
@FieldOrder(order = 13)
@IntRange(minValue=0,maxValue=1439)
@Asn1Optional public Long validUntilTime;
@FieldOrder(order = 14)
@IntRange(minValue=-60, maxValue=60)
@Asn1Optional public Long validUntilUTCOffset;
@FieldOrder(order = 15)
@Asn1Optional public ValidityPeriodDetailType validityPeriodDetails;
@FieldOrder(order = 16)
@IntRange(minValue=0,maxValue=370)
@Asn1Optional public Long numberOfValidityDays;
@FieldOrder(order = 17)
@Asn1Optional public TrainValidityType trainValidity;
@FieldOrder(order = 18)
@IntRange(minValue=1,maxValue=250)
@Asn1Optional public Long numberOfPossibleTrips;
@FieldOrder(order = 19)
@IntRange(minValue=1,maxValue=250)
@Asn1Optional public Long numberOfDaysOfTravel;
@FieldOrder(order = 20)
@Asn1Optional public SequenceOfActivatedDays activatedDay;
@FieldOrder(order = 21)
@Asn1Optional public SequenceOfCountries countries;
@FieldOrder(order = 22)
@Asn1Optional public SequenceOfCarrierNum includedCarriersNum;
@FieldOrder(order = 23)
@Asn1Optional public SequenceOfStringIA5 includedCarriersIA5;
@FieldOrder(order = 24)
@Asn1Optional public SequenceOfCarrierNum excludedCarriersNum;
@FieldOrder(order = 25)
@Asn1Optional public SequenceOfStringIA5 excludedCarriersIA5;
@FieldOrder(order = 26)
@Asn1Optional public SequenceOfServiceBrands includedServiceBrands;
@FieldOrder(order = 27)
@Asn1Optional public SequenceOfServiceBrands excludedServiceBrands;
@FieldOrder(order = 28)
@Asn1Optional public SequenceOfRegionalValidityType validRegion;
@FieldOrder(order = 29)
@Asn1Optional public SequenceOfTariffType tariffs;
@FieldOrder(order = 30)
@Asn1Optional Asn1BigInteger price;
@FieldOrder(order = 31)
@Asn1Optional SequenceOfVatDetail vatDetails;
@FieldOrder(order = 32)
@RestrictedString(CharacterRestriction.UTF8String)
@Asn1Optional public String infoText;
@FieldOrder(order = 33)
@Asn1Optional public ExtensionData extension;
public Asn1BigInteger getReferenceNum() {
return this.referenceNum;
}
public String getReferenceIA5() {
return this.referenceIA5;
}
public Long getProductOwnerNum() {
return this.productOwnerNum;
}
public String getProductOwnerIA5() {
return this.productOwnerIA5;
}
public Long getProductIdNum() {
return this.productIdNum;
}
public String getProductIdIA5() {
return this.productIdIA5;
}
public Long getPassType() {
return this.passType;
}
public String getPassDescription() {
return this.passDescription;
}
public TravelClassType getClassCode() {
if (classCode == null){
return TravelClassType.second;
}
return this.classCode;
}
public Long getValidFromDay() {
return this.validFromDay;
}
public Long getValidFromTime() {
return this.validFromTime;
}
public Long getValidUntilDay() {
return this.validUntilDay;
}
public Long getValidUntilTime() {
return this.validUntilTime;
}
public ValidityPeriodDetailType getValidityPeriodDetails() {
return this.validityPeriodDetails;
}
public Long getNumberOfValidityDays() {
return this.numberOfValidityDays;
}
public Long getNumberOfPossibleTrips() {
return this.numberOfPossibleTrips;
}
public Long getNumberOfDaysOfTravel() {
return this.numberOfDaysOfTravel;
}
public List<Long> getActivatedDay() {
return this.activatedDay;
}
public List<Long> getCountries() {
return this.countries;
}
public List<Long> getIncludedCarriersNum() {
return this.includedCarriersNum;
}
public List<String> getIncludedCarriersIA5() {
return this.includedCarriersIA5;
}
public List<Long> getExcludedCarriersNum() {
return this.excludedCarriersNum;
}
public SequenceOfStringIA5 getExcludedCarriersIA5() {
return this.excludedCarriersIA5;
}
public SequenceOfServiceBrands getIncludedServiceBrands() {
return this.includedServiceBrands;
}
public SequenceOfServiceBrands getExcludedServiceBrands() {
return this.excludedServiceBrands;
}
public List<RegionalValidityType> getValidRegion() {
return this.validRegion;
}
public List<TariffType> getTariffs() {
return this.tariffs;
}
public String getInfoText() {
return this.infoText;
}
public ExtensionData getExtension() {
return this.extension;
}
public void setReferenceNum(Asn1BigInteger referenceNum) {
this.referenceNum = referenceNum;
}
public void setReferenceIA5(String referenceIA5) {
this.referenceIA5 = referenceIA5;
}
public void setProductOwnerNum(Long productOwnerNum) {
this.productOwnerNum = productOwnerNum;
}
public void setProductOwnerIA5(String productOwnerIA5) {
this.productOwnerIA5 = productOwnerIA5;
}
public void setProductIdNum(Long productIdNum) {
this.productIdNum = productIdNum;
}
public void setProductIdIA5(String productIdIA5) {
this.productIdIA5 = productIdIA5;
}
public void setPassType(Long passType) {
this.passType = passType;
}
public void setPassDescription(String passDescription) {
this.passDescription = passDescription;
}
public void setClassCode(TravelClassType classCode) {
this.classCode = classCode;
}
public void setValidFromDay(Long validFromDay) {
this.validFromDay = validFromDay;
}
public void setValidFromTime(Long validFromTime) {
this.validFromTime = validFromTime;
}
public void setValidUntilDay(Long validUntilDay) {
this.validUntilDay = validUntilDay;
}
public void setValidUntilTime(Long validUntilTime) {
this.validUntilTime = validUntilTime;
}
public void setValidityPeriodDetails(ValidityPeriodDetailType validityPeriodDetails) {
this.validityPeriodDetails = validityPeriodDetails;
}
public void setNumberOfValidityDays(Long numberOfValidityDays) {
this.numberOfValidityDays = numberOfValidityDays;
}
public void setNumberOfPossibleTrips(Long numberOfPossibleTrips) {
this.numberOfPossibleTrips = numberOfPossibleTrips;
}
public void setNumberOfDaysOfTravel(Long numberOfDaysOfTravel) {
this.numberOfDaysOfTravel = numberOfDaysOfTravel;
}
public void setActivatedDay(SequenceOfActivatedDays activatedDay) {
this.activatedDay = activatedDay;
}
public void setCountries(SequenceOfCountries countries) {
this.countries = countries;
}
public void setIncludedCarriersNum(SequenceOfCarrierNum includedCarriersNum) {
this.includedCarriersNum = includedCarriersNum;
}
public void setIncludedCarriersIA5(SequenceOfStringIA5 includedCarriersIA5) {
this.includedCarriersIA5 = includedCarriersIA5;
}
public void setExcludedCarriersNum(SequenceOfCarrierNum excludedCarriersNum) {
this.excludedCarriersNum = excludedCarriersNum;
}
public void setExcludedCarriersIA5(SequenceOfStringIA5 excludedCarriersIA5) {
this.excludedCarriersIA5 = excludedCarriersIA5;
}
public void setIncludedServiceBrands(SequenceOfServiceBrands includedServiceBrands) {
this.includedServiceBrands = includedServiceBrands;
}
public void setExcludedServiceBrands(SequenceOfServiceBrands excludedServiceBrands) {
this.excludedServiceBrands = excludedServiceBrands;
}
public void setValidRegion(SequenceOfRegionalValidityType validRegion) {
this.validRegion = validRegion;
}
public void setTariffs(SequenceOfTariffType tariffs) {
this.tariffs = tariffs;
}
public void setInfoText(String infoText) {
this.infoText = infoText;
}
public void setExtension(ExtensionData extension) {
this.extension = extension;
}
public Long getPrice() {
return Asn1BigInteger.toLong(price);
}
public void setPrice(Long price) {
this.price = Asn1BigInteger.toAsn1(price);
}
public SequenceOfVatDetail getVatDetails() {
return vatDetails;
}
public void setVatDetails(SequenceOfVatDetail vatDetails) {
this.vatDetails = vatDetails;
}
public void addVatDetail(VatDetailType vatDetail) {
if (this.vatDetails == null) {
this.vatDetails = new SequenceOfVatDetail();
}
this.vatDetails.add(vatDetail);
}
public void setValidityDates (Date fromDate, Date untilDate, Date issuingDate){
if (issuingDate == null || fromDate == null) return;
this.validFromDay = DateTimeUtils.getDateDifference(issuingDate,fromDate);
this.validFromTime = DateTimeUtils.getTime(fromDate);
if (untilDate != null){
this.validUntilDay = DateTimeUtils.getDateDifference(fromDate, untilDate);
this.validUntilTime = DateTimeUtils.getTime(untilDate);
}
}
public Date getValidFromDate(Date issuingDate){
return DateTimeUtils.getDate(issuingDate, this.validFromDay, this.validFromTime);
}
public Date getValidUntilDate(Date issuingDate){
if (issuingDate == null) return null;
if (this.validFromDay == null) {
this.validFromDay = 0L;
}
if (this.validUntilDay == null) {
return null;
}
return DateTimeUtils.getDate(issuingDate, this.validFromDay + this.validUntilDay, this.validUntilTime);
}
public void addActivatedDays(Collection<Long> days) {
if (days == null || days.isEmpty()) return;
if (this.activatedDay == null) {
this.activatedDay = new SequenceOfActivatedDays();
}
for (Long l : days) {
this.activatedDay.add(l);
}
}
public void addActivatedDay(Date issuingDate, Date day){
Long dayDiff = DateTimeUtils.getDateDifference(issuingDate, day);
if (this.activatedDay == null) {
this.activatedDay = new SequenceOfActivatedDays();
}
if (dayDiff != null) {
this.activatedDay.add(dayDiff);
}
}
/**
* Gets the activated days.
*
* @param issuingDate the issuing date
* @return the activated days
*/
public Collection<Date> getActivatedDays(Date issuingDate) {
if (this.activatedDay == null) return null;
ArrayList<Date> dates = new ArrayList<Date>();
for (Long diff: this.getActivatedDay()) {
Date day = DateTimeUtils.getDate(this.getValidFromDate(issuingDate), diff, null);
if (day != null) {
dates.add(day);
}
}
return dates;
}
public Long getValidFromUTCOffset() {
return validFromUTCOffset;
}
public void setValidFromUTCOffset(Long validFromUTCOffset) {
this.validFromUTCOffset = validFromUTCOffset;
}
public Long getValidUntilUTCOffset() {
return validUntilUTCOffset;
}
public void setValidUntilUTCOffset(Long validUntilUTCOffset) {
this.validUntilUTCOffset = validUntilUTCOffset;
}
public TrainValidityType getTrainValidity() {
return trainValidity;
}
public void setTrainValidity(TrainValidityType trainValidity) {
this.trainValidity = trainValidity;
}
}
| 23.595357 | 106 | 0.732007 |
1c10abba3be54a0584c0b49773ff7636bde3b953 | 2,131 | /*
Copyright Amazon.com, Inc. or its affiliates. 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.
A copy of the License is located at
http://www.apache.org/licenses/LICENSE-2.0
or in the "license" file accompanying this file. This file 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.amazonaws.services.neptune.cli;
import com.amazonaws.services.neptune.propertygraph.NeptuneGremlinClient;
import com.amazonaws.services.neptune.propertygraph.io.SerializationConfig;
import com.amazonaws.services.neptune.propertygraph.schema.TokensOnly;
import com.github.rvesse.airline.annotations.Option;
import com.github.rvesse.airline.annotations.restrictions.AllowedEnumValues;
import com.github.rvesse.airline.annotations.restrictions.AllowedValues;
import com.github.rvesse.airline.annotations.restrictions.Once;
import org.apache.tinkerpop.gremlin.driver.ser.Serializers;
public class PropertyGraphSerializationModule {
@Option(name = {"--serializer"}, description = "Message serializer – (optional, default 'GRAPHBINARY_V1D0').")
@AllowedEnumValues(Serializers.class)
@Once
private String serializer = Serializers.GRAPHBINARY_V1D0.name();
@Option(name = {"--janus"}, description = "Use JanusGraph serializer.")
@Once
private boolean useJanusSerializer = false;
@Option(name = {"--max-content-length"}, description = "Max content length (optional, default 50000000).")
@Once
private int maxContentLength = 50000000;
@Option(name = {"-b", "--batch-size"}, description = "Batch size (optional, default 64). Reduce this number if your queries trigger CorruptedFrameExceptions.")
@Once
private int batchSize = NeptuneGremlinClient.DEFAULT_BATCH_SIZE;
public SerializationConfig config(){
return new SerializationConfig(serializer, maxContentLength, batchSize, useJanusSerializer);
}
}
| 43.489796 | 163 | 0.775223 |
b61b42de76dc37854f42f97036b4daf085c086d4 | 14,323 | package com.ks.process.operation;
import com.google.common.collect.ImmutableList;
import com.ks.bean.KJson;
import com.ks.error.KConfigException;
import com.ks.error.KRunException;
import org.apache.kafka.clients.producer.internals.DefaultPartitioner;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.kstream.JoinWindows;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.ValueJoiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
/**
* join.com.ks.name 执行join操作的目标kSource名称
* <p>
* join.source.through source的partition与target不一致,运行前手动创建一个与target相同partition的topic,{@link DefaultPartitioner} is used.
* <p>
* join.target.through target的partition与source不一致,运行前手动创建一个与source相同partition的topic{@link DefaultPartitioner} is used.
* <p>
* 如果operation.ks与join.ks两者有一者为table,则before,after,retention无需配置.
* join.beforeMs=0
* join.afterMs=0
* SELECT * FROM stream1, stream2 WHERE stream1.key = stream2.key AND stream1.ts - before <= stream2.ts AND stream2.ts <= stream1.ts + after
* There are three different window configuration supported:
* 1,before = after = time-difference;
* 2,before = 0 and after = time-difference;
* 3,before = time-difference and after = 0
* <p>
* join.retentionMs retentionMs > before+after
* <p>
* join.output.strategy 输出策略,overwrite:相同子段覆盖;uncover:相同的子段后缀添加数字,默认overwrite.如f=>f1,f1=>f11...
* <p>
* join.output.fields.value.add 输出策略外的允许同名字段值追加,优先级高于输出策略
* <p>
* join.output.fields.value.add.interval 值追加间隔符.默认','
* <p>
* 支持以下方式:
* KTable [join,leftJoin,outerJoin] KTable
* KStream [join,leftJoin,outerJoin] KStream
* KStream [join,leftJoin] KTable
* **************************************************************
* kafka0.11版本
* ***************************************************
* *****************Stream-->Stream*******************
* *****************join*****************
* -----------------------------------
* this other result
* -----------------------------------
* <K1:A>
* -----------------------------------
* <K2:B> <K2:b> <K2:ValueJoiner(B,b)>
* ------------------------------------
* <K3:c>
* ------------------------------------
* *****************leftJoin*****************
* -----------------------------------
* this other result
* -----------------------------------
* <K1:A> <K1:ValueJoiner(A,null)>
* -----------------------------------
* *************** <K2:ValueJoiner(B,null)>
* <K2:B> <K2:b> <K2:ValueJoiner(B,b)>
* ------------------------------------
* <K3:c>
* ------------------------------------
* ********leftJoin多出来的(B,null),可以先保存,然后以table读出来
* *****************outerJoin*****************
* -----------------------------------
* this other result
* -----------------------------------
* <K1:A> <K1:ValueJoiner(A,null)>
* -----------------------------------
* *************** <K2:ValueJoiner(B,null)>
* <K2:B> <K2:b> <K2:ValueJoiner(B,b)>
* ------------------------------------
* <K3:c> <K3:ValueJoiner(null,c)>
* ------------------------------------
* ********可以采取leftJoin的方式处理多出的(B,null)值
* ***************************************************
* *****************Table-->Table*****************
* 如果两个table都在更新,则结果类似笛卡尔积
* *****************join*****************
* ***********需要配置store(operation.table.store),否则则(B,b)会多次输出
* -----------------------------------
* thisState otherState result
* -----------------------------------
* <K1:A>
* -----------------------------------
* <K2:B> <K2:b> <K2:ValueJoiner(B,b)>
* ------------------------------------
* <K3:c>
* ------------------------------------
* *****************leftJoin*****************
* ***********需要配置store(operation.table.store),否则则(B,b)会多次输出
* -----------------------------------
* thisState otherState result
* -----------------------------------
* <K1:A> <K1:ValueJoiner(A,null)>
* -----------------------------------
* <K2:B> <K2:b> <K2:ValueJoiner(B,b)>
* ------------------------------------
* <K3:c>
* ------------------------------------
* *****************outerJoin*****************
* ***********需要配置store(operation.table.store),否则则(B,b)会多次输出
* -----------------------------------
* thisState otherState result
* -----------------------------------
* <K1:A> <K1:ValueJoiner(A,null)>
* -----------------------------------
* <K2:B> <K2:b> <K2:ValueJoiner(B,b)>
* ------------------------------------
* <K3:c> <K3:ValueJoiner(null,c)>
* ------------------------------------
* ***************************************************
* *****************Stream-->Table*****************
* *****************join*****************
* **The join is a primary key table lookup join with join attribute stream.key == table.key.
* **"Table lookup join" means, that results are only computed if KStream records are processed.
* **In contrast, processing KTable input records will only update the internal KTable state
* **and will not produce any result records.
* -----------------------------------
* this otherState result
* -----------------------------------
* <K1:A>
* -----------------------------------
* <K2:B> <K2:b> <K2:ValueJoiner(B,b)>
* ------------------------------------
* <K3:c>
* ------------------------------------
* *****************leftJoin*****************
* -----------------------------------
* this otherState result
* -----------------------------------
* <K1:A> <K1:ValueJoiner(A,null)>
* -----------------------------------
* <K2:B> <K2:b> <K2:ValueJoiner(B,b)>
* ------------------------------------
* <K3:c>
* ------------------------------------
*/
class JoinImpl extends Operation {
private final Logger logger = LoggerFactory.getLogger(JoinImpl.class);
/**
* configuration definition
*/
private enum CONFIG {
JOIN_KSOURCE_NAME("join.ks.name"), SOURCE_THROUGH("join.source.through"), TARGET_THROUGH("join.target.through"),
WIN_BEFORE("join.beforeMs"), WIN_AFTER("join.afterMs"), WIN_RETENTION("join.retentionMs"),
OUTPUT_STRATEGY("join.output.strategy"), OUTPUT_ADD_VALUE_FIELDS("join.output.fields.value.add"),
ADD_VALUE_FIELD_INTERVAL("join.output.fields.value.add.interval");
private String value;
CONFIG(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
private final String joinKSourceName;
private final String sourceThrough;
private final String targetThrough;
private final long beforeMs;
private final long afterMs;
private final long retentionMs;
private final boolean isCover;
private final ImmutableList<String> addValueFields;
private final String addValueFieldInterval;
JoinImpl(Properties properties) {
super(properties);
this.joinKSourceName = nonNullEmpty(properties, CONFIG.JOIN_KSOURCE_NAME.getValue());
this.sourceThrough = properties.getProperty(CONFIG.SOURCE_THROUGH.getValue());
this.targetThrough = properties.getProperty(CONFIG.TARGET_THROUGH.getValue());
String _beforeMs = properties.getProperty(CONFIG.WIN_BEFORE.getValue(), "0");
this.beforeMs = _beforeMs.isEmpty() ? 0L : Long.valueOf(_beforeMs);
String _afterMs = properties.getProperty(CONFIG.WIN_AFTER.getValue(), "0");
this.afterMs = _afterMs.isEmpty() ? 0L : Long.valueOf(_afterMs);
String _retentionMs = properties.getProperty(CONFIG.WIN_RETENTION.getValue(), "1");
long retentionMs = _retentionMs.isEmpty() ? 1L : Long.valueOf(_retentionMs);
if (retentionMs < beforeMs + afterMs) {
logger.warn("join window retention time cannot be smaller than before and after sum.");
this.retentionMs = (beforeMs + afterMs) + 1;
} else this.retentionMs = retentionMs;
String _outputStrategy = properties.getProperty(CONFIG.OUTPUT_STRATEGY.getValue(), "cover");
_outputStrategy = _outputStrategy.isEmpty() ? "cover" : _outputStrategy;
switch (_outputStrategy) {
case "uncover":
this.isCover = false;
break;
case "cover":
this.isCover = true;
break;
default:
logger.warn(concat(" ", CONFIG.OUTPUT_STRATEGY.getValue(), "value:", _outputStrategy,
"not support..."));
this.isCover = true;
}
String _addValueFields = properties.getProperty(CONFIG.OUTPUT_ADD_VALUE_FIELDS.getValue());
this.addValueFields = isNullOrEmpty(_addValueFields) ? ImmutableList.of() : split(_addValueFields, COMMA);
String _addValueFieldInterval = properties.getProperty(CONFIG.ADD_VALUE_FIELD_INTERVAL.getValue(), COMMA);
this.addValueFieldInterval = _addValueFieldInterval.isEmpty() ? COMMA : _addValueFieldInterval;
}
/**
* process impl
* <p>
* if json value read fail,will drop
* 支持以下方式:
* <p>
* KTable [join,leftJoin,outerJoin] KTable
* <p>
* KStream [join,leftJoin,outerJoin] KStream
* <p>
* KStream [join,leftJoin] KTable
*
* @param kSources kStream or kTable
* @return kStream or kTable
*/
@SuppressWarnings("unchecked")
@Override
Object processImpl(Object... kSources) {
Object source = kSources[0], other = kSources[1];
if (!isNullOrEmpty(sourceThrough)) source = through(source, sourceThrough);
if (!isNullOrEmpty(targetThrough)) other = through(other, targetThrough);
Class clazz = source.getClass();
Method handle;
final ValueJoiner<String, String, String> joiner = (value1, value2) -> {
try {
return mergeValue(value1, value2);
} catch (IOException | RuntimeException e) {
logger.error(concat(NEWLINE, "merge value error and return value...", "value:" + value1,
"otherValue:" + value2), e);
}
return value1;
};
try {
if (source instanceof KTable) {
if ((other instanceof KTable)) {// table--table
if (!tableStoreName.isEmpty()) {
handle = clazz.getDeclaredMethod(_operator,
KTable.class, ValueJoiner.class, Serde.class, String.class);
return handle.invoke(source, other, joiner, Serdes.String(), tableStoreName);
} else {
handle = clazz.getDeclaredMethod(_operator, KTable.class, ValueJoiner.class);
return handle.invoke(source, other, joiner);
}
} else throw new KConfigException(concat(" ",
kSourceName + " is table and", joinKSourceName, "is not table,any joins can not support..."));
}
if (other instanceof KTable) { //stream--table
if ("outerJoin".equals(_operator)) throw new KConfigException(concat(" ", kSourceName,
"is stream and", joinKSourceName, "is table,outerJoin can not support..."));
handle = clazz.getDeclaredMethod(_operator, KTable.class, ValueJoiner.class, Serde.class, Serde.class);
return handle.invoke(source, other, joiner, Serdes.String(), Serdes.String());
}
//stream--stream
handle = clazz.getDeclaredMethod(_operator, KStream.class, ValueJoiner.class, JoinWindows.class,
Serde.class, Serde.class, Serde.class);
return handle.invoke(source, other, joiner, JoinWindows.of(beforeMs).after(afterMs).until(retentionMs),
Serdes.String(), Serdes.String(), Serdes.String());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
logger.error(e.getMessage(), e);
throw new KRunException(e);
}
}
/**
* process for join
*/
@Override
public void process(Map<String, Object> kSources) {
if (!kSources.containsKey(kSourceName) || !kSources.containsKey(joinKSourceName))
throw new KConfigException(concat(" ", kSourceName, "or", joinKSourceName, "does not exit..."));
kSources.put(kSourceName, processImpl(kSources.get(kSourceName), kSources.get(joinKSourceName)));
}
/**
* merge value and filter by specific fields
* <p>
* 如果有同名key,则优先是否值追加,相同值只保留一个,不同值间隔符分隔
* <p>
* 如果有重复key且是不覆盖,则会输出key,key1,即重复key后面添加“1”
*
* @param value json value
* @param otherValue json value
* @return json value
*/
@SuppressWarnings("unchecked")
private String mergeValue(String value, String otherValue) throws IOException {
Map<String, Object> valM = isNullOrEmpty(value) ? Collections.emptyMap() :
KJson.readValue(value);
Map<String, Object> otherValM = isNullOrEmpty(otherValue) ? Collections.emptyMap() :
KJson.readValue(otherValue);
Map<String, Object> resultMap = new HashMap<>(valM.size() + otherValM.size());
resultMap.putAll(valM);
otherValM.forEach((k, v) -> {
if (valM.containsKey(k)) {
if (addValueFields.contains(k)) {
Object v1 = valM.get(k), v2 = otherValM.get(k);
Object val = Objects.equals(v1, v2) ? v1 : String.valueOf(v1) +
addValueFieldInterval + v2;
resultMap.put(k, val);
} else if (!isCover) {
resultMap.put(k + 1, v);
} else {
resultMap.put(k, v);
}
} else resultMap.put(k, v);
});
return KJson.writeValueAsString(resultMap);
}
}
| 42.627976 | 140 | 0.533617 |
ceae63ba96346743d405f34b80e96380b80ba751 | 1,274 | /**
*
*/
package cl.zpricing.avant.web.chart;
import javax.servlet.http.HttpServletRequest;
/**
* <b>Descripci�n de la Clase</b>
* Clase utilizada para poder generar y guardar la ruta de un archivo xml de un
* grafico
*
* Registro de versiones:
* <ul>
* <li>1.0 08-01-2009 Oliver Cordero: versi�n inicial.</li>
* </ul>
* <P>
* <B>Todos los derechos reservados por ZhetaPricing.</B>
* <P>
*/
public class ArchivoGrafico {
private String nombre;
private HttpServletRequest request;
public ArchivoGrafico(HttpServletRequest request, String nombre) {
//GregorianCalendar.getInstance().getTime().getTime()
this.request = request;
this.nombre = request.getSession().getId()+nombre;
}
/**
* Entrega la ruta del archivo que se debe usar en el codigo java
* @return ruta interna del grafico
*/
public String rutaGraficoInterna(){
if(request.getContextPath().compareTo("/")!=0)
return "webapps"+request.getContextPath()+"/grafico/"+nombre+".xml";
else
return "webapps/grafico/"+nombre+".xml";
}
/**
* Entrega la ruta del archivo que se debe usar en el JSP
* @return ruta externa del grafico
*/
public String rutaGraficoExterna(){
return "/grafico/"+nombre+".xml";
}
}
| 25.48 | 80 | 0.66248 |
b2e30fd836001097ccbc0aaa18f8f6f70ccb6260 | 497 | package model;
public class UserCommand extends Command {
public UserCommand(final Cell cell, final CommandType type, final int value) {
super(cell, type, value);
}
@Override
public boolean is_user_command() {
return true;
}
@Override
public void execute() {
throw new IllegalArgumentException();
}
@Override
public void unexecute() {
throw new IllegalArgumentException();
}
}
| 15.53125 | 83 | 0.585513 |
162e79e91a16a1d1fccd471daa9c917fcdc13ff7 | 1,444 | package io.cem.modules.cem.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import io.cem.modules.cem.dao.AlarmRecordDao;
import io.cem.modules.cem.entity.AlarmRecordEntity;
import io.cem.modules.cem.service.AlarmRecordService;
@Service("alarmRecordService")
public class AlarmRecordServiceImpl implements AlarmRecordService {
@Autowired
private AlarmRecordDao alarmRecordDao;
@Override
public AlarmRecordEntity queryObject(Integer id){
return alarmRecordDao.queryObject(id);
}
@Override
public List<AlarmRecordEntity> queryList(Map<String, Object> map){
return alarmRecordDao.queryList(map);
}
@Override
public List<AlarmRecordEntity> queryAlarmRecordList(Map<String, Object> map){
return alarmRecordDao.queryAlarmRecordList(map);
}
@Override
public int queryTotal(Map<String, Object> map){
return alarmRecordDao.queryTotal(map);
}
@Override
public void save(AlarmRecordEntity alarmRecord){
alarmRecordDao.save(alarmRecord);
}
@Override
public void update(AlarmRecordEntity alarmRecord){
alarmRecordDao.update(alarmRecord);
}
@Override
public void operate(Integer id){alarmRecordDao.operate(id);}
@Override
public void delete(Integer id){
alarmRecordDao.delete(id);
}
@Override
public void deleteBatch(Integer[] ids){
alarmRecordDao.deleteBatch(ids);
}
}
| 22.215385 | 78 | 0.786011 |
5953bf92c332a70a050fd2313a7b49d3014627b4 | 7,183 | package visualiser.Controllers;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import network.Messages.Enums.RequestToJoinEnum;
import javafx.scene.media.AudioClip;
import network.Messages.HostGame;
import org.json.JSONArray;
import org.json.JSONObject;
import shared.utils.JsonReader;
import visualiser.app.MatchBrowserSingleton;
import visualiser.model.RaceConnection;
import visualiser.network.HttpMatchBrowserClient;
import visualiser.network.MatchBrowserLobbyInterface;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Observable;
import java.util.Observer;
/**
* Controller for the Lobby for entering games
*/
public class LobbyController extends Controller {
private @FXML TableView<RaceConnection> lobbyTable;
private @FXML TableColumn<RaceConnection, String> gameNameColumn;
private @FXML TableColumn<RaceConnection, String> hostNameColumn;
private @FXML TableColumn<RaceConnection, String> statusColumn;
private @FXML Button joinGameBtn;
private @FXML Button spectateButton;
private @FXML TextField addressFld;
private @FXML TextField portFld;
private ObservableList<RaceConnection> allConnections;
private ObservableList<RaceConnection> customConnections;
private AudioClip sound;
//the socket for match browser
private HttpMatchBrowserClient httpMatchBrowserClient;
public void initialize() {
httpMatchBrowserClient = new HttpMatchBrowserClient();
httpMatchBrowserClient.connections.addListener(new ListChangeListener<RaceConnection>() {
@Override
public void onChanged(Change<? extends RaceConnection> c) {
refreshTable();
}
});
new Thread(httpMatchBrowserClient, "Match Client").start();
// set up the connection table
customConnections = FXCollections.observableArrayList();
allConnections = FXCollections.observableArrayList();
//connections.add(new RaceConnection("localhost", 4942, "Local Game"));
lobbyTable.setItems(allConnections);
gameNameColumn.setCellValueFactory(cellData -> cellData.getValue().gamenameProperty());
hostNameColumn.setCellValueFactory(cellData -> cellData.getValue().hostnameProperty());
statusColumn.setCellValueFactory(cellData -> cellData.getValue().statusProperty());
lobbyTable.getSelectionModel().selectedItemProperty().addListener((obs, prev, curr) -> {
if (curr != null && curr.statusProperty().getValue().equals("Ready")) {
joinGameBtn.setDisable(false);
spectateButton.setDisable(false);
} else {
joinGameBtn.setDisable(true);
spectateButton.setDisable(true);
}
});
joinGameBtn.setDisable(true);
spectateButton.setDisable(true);
receiveMatchData();
}
/**
* Refreshes the connections in the lobby
*/
public void refreshBtnPressed(){
sound = new AudioClip(this.getClass().getResource("/visualiser/sounds/buttonpress.wav").toExternalForm());
sound.play();
refreshTable();
}
private void refreshTable() {
allConnections.clear();
addCustomGames();
addServerGames();
for(RaceConnection connection: allConnections) {
connection.check();
}
try {
if (lobbyTable.getSelectionModel().getSelectedItem().statusProperty().getValue().equals("Ready")) {
joinGameBtn.setDisable(false);
spectateButton.setDisable(false);
} else {
joinGameBtn.setDisable(true);
spectateButton.setDisable(true);
}
} catch (Exception ignored){}
}
/**
* Connect to a connection.
* @param joinType How the client wishes to join (e.g., participant).
* @throws IOException socket error
*/
public void connectSocket(RequestToJoinEnum joinType) throws IOException {
httpMatchBrowserClient.interrupt();
RaceConnection connection = lobbyTable.getSelectionModel().getSelectedItem();
Socket socket = new Socket(connection.getHostname(), connection.getPort());
InGameLobbyController iglc = (InGameLobbyController)loadScene("gameLobby.fxml");
iglc.enterGameLobby(socket, false, joinType);
}
/**
* Requests to join the game as a participant.
* @throws IOException socket error.
*/
public void connectParticipate() throws IOException {
connectSocket(RequestToJoinEnum.PARTICIPANT);
}
/**
* Requests to join the game as a spectator.
* @throws IOException socket error.
*/
public void connectSpectate() throws IOException {
connectSocket(RequestToJoinEnum.SPECTATOR);
}
public void menuBtnPressed() throws IOException {
sound = new AudioClip(this.getClass().getResource("/visualiser/sounds/buttonpress.wav").toExternalForm());
sound.play();
httpMatchBrowserClient.interrupt();
loadScene("title.fxml");
}
/**
* adds a new connection
*/
public void addConnectionPressed(){
sound = new AudioClip(this.getClass().getResource("/visualiser/sounds/buttonpress.wav").toExternalForm());
sound.play();
String hostName = addressFld.getText();
String portString = portFld.getText();
try {
int port = Integer.parseInt(portString);
customConnections.add(new RaceConnection(hostName, port, "Boat Game"));
addressFld.clear();
portFld.clear();
refreshTable();
} catch (NumberFormatException e) {
System.err.println("Port number entered is not a number");
}
}
public void receiveMatchData(){
/*
matchBrowserLobbyInterface = new MatchBrowserLobbyInterface();
try {
matchBrowserLobbyInterface.startReceivingHostData(new DatagramSocket(4941));
Observer o = new Observer() {
@Override
public void update(Observable o, Object arg) {
refreshBtnPressed();
}
};
matchBrowserLobbyInterface.addObserver(o);
} catch (SocketException e) {
System.err.println("Socket 4941 in use");
}*/
}
/**
* Adds the games received from the server
*/
private void addServerGames() {
allConnections.addAll(httpMatchBrowserClient.connections);
/*
for (HostGame game : matchBrowserLobbyInterface.getGames()) {
connections.add(new RaceConnection(game.getIp(), 4942, "Boat Game"));
}*/
}
private void addCustomGames() {
allConnections.addAll(customConnections);
}
}
| 35.736318 | 114 | 0.667688 |
16e98f04dbf2f617b58c9ef595649177c6ac75a0 | 304 | package io.github.vampirestudios.obsidian.api.bedrock;
import com.google.gson.annotations.SerializedName;
public class BlockModelInformation {
@SerializedName("textures")
public String textures;
@SerializedName("textures")
public Texture texturesElement;
public String sound;
}
| 19 | 54 | 0.763158 |
03a6c1f04d59caa3a135ba5b00cd87ad7da627bc | 2,565 | package com.sqring.auth.filter;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author www.zhouwenfang.com
* @version 1.0.0
* @ClassName AuthenticationFilter.java
* @Description 请求资源前,先通过此 过滤器进行用户信息解析和校验 转发
* @createTime 2021年05月16日
*/
@Component // 不要少了
public class AuthenticationFilter extends ZuulFilter {
Logger logger = LoggerFactory.getLogger(getClass());
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
// 如果解析到令牌就会封装到OAuth2Authentication对象
if( !(authentication instanceof OAuth2Authentication)) {
return null;
}
logger.info("网关获取到认证对象:" + authentication);
// 用户名,没有其他用户信息
Object principal = authentication.getPrincipal();
// 获取用户所拥有的权限
Collection<? extends GrantedAuthority> authorities
= authentication.getAuthorities();
Set<String> authoritySet = AuthorityUtils.authorityListToSet(authorities);
// 请求详情
Object details = authentication.getDetails();
Map<String, Object> result = new HashMap<>();
result.put("principal", principal);
result.put("authorities", authoritySet);
result.put("details", details);
// 获取当前请求上下文
RequestContext context = RequestContext.getCurrentContext();
// 将用户信息和权限信息转成json,再通过base64进行编码
String base64 = Base64Utils.encodeToString(JSON.toJSONString(result).getBytes());
// 添加到请求头
context.addZuulRequestHeader("auth-token", base64);
return null;
}
}
| 31.280488 | 89 | 0.708382 |
541606f9ef54beb2875e78c47d44f67261842daa | 5,336 | package Recursion;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class MazeGenerator {
public static final int LEFT = 0;
public static final int RIGHT = 1;
public static final int UP = 2;
public static final int DOWN = 3;
public static final char s = '.';//'\u2591';
public static final char t = '#';//'\u2588';
public static int ROW_START = 0;
public static final int COL_START = 1;
public final static int rows = 13;
public final static int columns = 13;
public static int move = 0;
public static char[][] maze;
public MazeGenerator() {
maze = new char[rows][columns];
initialization();
}
public static void starter () throws Exception {
while (ROW_START == 0) {
int x = (int) (Math.random()*rows)-1;
if (x%2 == 1 && x > 1)
ROW_START = x;
}
generation(ROW_START, COL_START, (int) Math.round(Math.random()), 0);
boolean changedStart = false;
boolean changedEnd = false;
while (changedStart == false) {
int i = (int) (Math.random()*rows);
if (maze[i][1] == s) {
maze[i][0] = s;
changedStart = true;
}
}
while (changedEnd == false) {
int i = (int) (Math.random()*rows);
if (maze[i][columns-2] == s) {
maze[i][columns-1] = s;
changedEnd = true;
}
}
writeMazeFile();
}
public static boolean generation (int row, int column, int which, int howmuch) {
move++;
maze[row][column] = s;
if (which == 0 && move > 1)
maze[row][column-howmuch] = s;
else if (which == 1 && move > 1)
maze[row-howmuch][column] = s;
if (row == ROW_START && column == COL_START && move > 1) {
System.out.println("Maze finished");
return false;
} else {
while (!noMovesLeft(row, column)){
switch ((int) (Math.random()*4)) {
case LEFT:
if (validMove(row, column-2)) {
if (generation(row, column-2, 0, -1)) {
return true;
}
}
break;
case RIGHT:
if (validMove(row, column+2)) {
if (generation(row, column+2, 0, 1)) {
return true;
}
}
break;
case UP:
if (validMove(row - 2, column)) {
if (generation(row - 2, column, 1, -1)) {
return true;
}
}
break;
case DOWN:
if (validMove(row + 2, column)) {
if (generation(row + 2, column, 1, 1)) {
return true;
}
}
break;
}
}
}
return false;
}
public static void initialization () {
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
maze[i][j] = t;
}
}
}
public static boolean noMovesLeft (int row, int column) {
return !validMove(row+2, column) && !validMove(row-2, column) && !validMove(row, column+2) && !validMove(row, column-2);
}
public static boolean validMove (int row, int column) {
return row >= 1 && column >= 1 && row < rows && column < columns && maze[row][column] == t;
}
public static void printMaze() {
for (char[] row : maze) {
for (char c : row) {
System.out.print(c);
}
System.out.println();
}
System.out.println();
}
public static void writeMazeFile() throws Exception {
//Getting the output stream of a file for writing
File file = new File ("maze.txt");
//Take the input from the console
BufferedWriter out = new BufferedWriter (new FileWriter(file));
out.write(String.valueOf(rows));
out.newLine();
out.write(String.valueOf(columns));
out.newLine();
for (char[] row : maze) {
String st = new String (row);
out.write(st);
out.newLine();
}
out.close();
}
} | 25.2891 | 128 | 0.390367 |
03ea1e615daf69e98b6c298443628cecc1fc6b14 | 3,454 | /* 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.flowable.dmn.engine.impl.deployer;
import java.util.List;
import java.util.Map;
import org.flowable.common.engine.api.repository.EngineResource;
import org.flowable.dmn.engine.impl.parser.DmnParse;
import org.flowable.dmn.engine.impl.persistence.entity.DecisionEntity;
import org.flowable.dmn.engine.impl.persistence.entity.DmnDeploymentEntity;
import org.flowable.dmn.model.Decision;
import org.flowable.dmn.model.DecisionService;
import org.flowable.dmn.model.DmnDefinition;
/**
* An intermediate representation of a DeploymentEntity which keeps track of all of the entity's DefinitionEntities and resources and processes associated with each
* DefinitionEntity - all produced by parsing the deployment.
*
* The DefinitionEntities are expected to be "not fully set-up" - they may be inconsistent with the DeploymentEntity and/or the persisted versions, and if the deployment is new, they will not yet
* be persisted.
*/
public class ParsedDeployment {
protected DmnDeploymentEntity deploymentEntity;
protected List<DecisionEntity> decisions;
protected Map<DecisionEntity, DmnParse> mapDecisionsToParses;
protected Map<DecisionEntity, EngineResource> mapDecisionsToResources;
public ParsedDeployment(
DmnDeploymentEntity entity, List<DecisionEntity> decisions,
Map<DecisionEntity, DmnParse> mapDecisionsToParses,
Map<DecisionEntity, EngineResource> mapDecisionsToResources) {
this.deploymentEntity = entity;
this.decisions = decisions;
this.mapDecisionsToParses = mapDecisionsToParses;
this.mapDecisionsToResources = mapDecisionsToResources;
}
public DmnDeploymentEntity getDeployment() {
return deploymentEntity;
}
public List<DecisionEntity> getAllDecisions() {
return decisions;
}
public EngineResource getResourceForDecision(DecisionEntity decision) {
return mapDecisionsToResources.get(decision);
}
public DmnParse getDmnParseForDecision(DecisionEntity decision) {
return mapDecisionsToParses.get(decision);
}
public DmnDefinition getDmnDefinitionForDecision(DecisionEntity decision) {
DmnParse parse = getDmnParseForDecision(decision);
return (parse == null ? null : parse.getDmnDefinition());
}
public DecisionService getDecisionServiceForDecisionEntity(DecisionEntity decisionEntity) {
DmnDefinition dmnDefinition = getDmnDefinitionForDecision(decisionEntity);
return (dmnDefinition == null ? null : dmnDefinition.getDecisionServiceById(decisionEntity.getKey()));
}
public Decision getDecisionForDecisionEntity(DecisionEntity decisionEntity) {
DmnDefinition dmnDefinition = getDmnDefinitionForDecision(decisionEntity);
return (dmnDefinition == null ? null : dmnDefinition.getDecisionById(decisionEntity.getKey()));
}
}
| 40.162791 | 195 | 0.761436 |
bc796ceb9ff52f2e0c0ad9a487d68d14c486b487 | 2,261 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkg2examen2_luisenriquez;
import java.io.Serializable;
import java.util.ArrayList;
/**
*
* @author Luis Enriquez
*/
class Usuario extends Persona implements Serializable {
String user;
String pass;
ArrayList<Privado> chats = new ArrayList();
ArrayList<Grupo> grupos = new ArrayList();
ArrayList<Usuario> amigos = new ArrayList();
ArrayList<Usuario> solis = new ArrayList();
public Usuario(String user, String pass, String nombre, String apellido, String telefono) {
super(nombre, apellido, telefono);
this.user = user;
this.pass = pass;
}
public ArrayList<Grupo> getGrupos() {
return grupos;
}
public void setGrupos(ArrayList<Grupo> grupos) {
this.grupos = grupos;
}
public ArrayList<Usuario> getSolis() {
return solis;
}
public void setSolis(ArrayList<Usuario> solis) {
this.solis = solis;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public ArrayList<Privado> getChats() {
return chats;
}
public void setChats(ArrayList<Privado> chats) {
this.chats = chats;
}
public ArrayList<Usuario> getAmigos() {
return amigos;
}
public void setAmigos(ArrayList<Usuario> amigos) {
this.amigos = amigos;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
@Override
public String toString() {
return "[" + user + "]";
}
}
| 20.743119 | 95 | 0.609907 |
fadbf40081d5123d2075f5f4b6ccb9e7bc84ae94 | 2,832 | /*
* Copyright 2020 lujing
*
* 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.github.mofa3.client.okhttp3;
import com.fasterxml.jackson.core.type.TypeReference;
import okhttp3.Cookie;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.File;
import java.io.InputStream;
import java.util.List;
/**
* TODO
*
* @author baizhang
* @version: v 0.1 IOkHttpResponse.java, 2019-07-30 22:46 Exp $
*/
public interface IOkHttpResponse {
/**
* http状态码 200 404 500...
*
* @return http code
*/
int httpCode();
/**
* 请求是否成功
*
* @return request isSuccessful
*/
boolean success();
/**
* http 状态码msg
*
* @return status msg
*/
String message();
/**
* 是否重定向
*
* @return boolean value
*/
boolean redirect();
/**
* 响应header
*
* @return Headers
*/
Headers headers();
/**
* contentType
*
* @return MediaType
*/
MediaType contentType();
/**
* 返回内容长度
*
* @return length
*/
long contentLength();
/**
* cookie
*
* @return list cookie
*/
List<Cookie> cookies();
/**
* 结果以string返回
*
* @return String
*/
String toStr();
/**
* 结果以byte返回
*
* @return byte[]
*/
byte[] toByte();
/**
* 结果以stream返回
*
* @return stream
*/
InputStream toStream();
/**
* 结果以指定Bean对象返回
*
* @param claxx 转换类型
* @param <T> 泛型
* @return BeanType
*/
<T> T toBean(Class<T> claxx);
/**
* 结果以jackson Type返回
*
* @param typeReference jackson Type
* @param <T> 泛型
* @return BeanType
*/
<T> T toJsonType(TypeReference<?> typeReference);
/**
* 结果以List Bean返回
*
* @param claxx 转换类型
* @param <T> 泛型
* @return list
*/
<T> List<T> toList(Class<T> claxx);
/**
* 返回结果写入文件
* 一般用于文件下载,文件接收
*
* @param file file
*/
void toFile(File file);
/**
* rawResponse
*
* @return Response
*/
Response rawResponse();
/**
* rawBody
*
* @return ResponseBody
*/
ResponseBody rawBody();
} | 17.590062 | 75 | 0.555085 |
327aa4531ef2c6b103c844f74c854b5dca9a996f | 1,572 | package io.quarkiverse.micrometer.registry.signalfx;
import java.util.Map;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
import org.eclipse.microprofile.config.Config;
import org.jboss.logging.Logger;
import io.micrometer.core.instrument.Clock;
import io.micrometer.signalfx.SignalFxConfig;
import io.micrometer.signalfx.SignalFxMeterRegistry;
import io.micrometer.signalfx.SignalFxNamingConvention;
import io.quarkus.arc.DefaultBean;
import io.quarkus.micrometer.runtime.export.ConfigAdapter;
@Singleton
public class SignalFxMeterRegistryProvider {
private static final Logger log = Logger.getLogger(SignalFxMeterRegistryProvider.class);
static final String PREFIX = "quarkus.micrometer.export.signalfx.";
static final String PUBLISH = "signalfx.publish";
static final String ENABLED = "signalfx.enabled";
@Produces
@Singleton
@DefaultBean
public SignalFxConfig configure(Config config) {
final Map<String, String> properties = ConfigAdapter.captureProperties(config, PREFIX);
return ConfigAdapter.validate(new SignalFxConfig() {
@Override
public String get(String key) {
return properties.get(key);
}
});
}
@Produces
@DefaultBean
public SignalFxNamingConvention namingConvention() {
return new SignalFxNamingConvention();
}
@Produces
@Singleton
public SignalFxMeterRegistry registry(SignalFxConfig config, Clock clock) {
return new SignalFxMeterRegistry(config, clock);
}
}
| 30.230769 | 95 | 0.739186 |
aada61c771cddd7aa58531b1ab0308dd7c8b9bd5 | 2,285 | package com.twistezo.controller;
import com.twistezo.model.BorrowedDate;
import com.twistezo.model.Car;
import com.twistezo.model.Customer;
import com.twistezo.service.BorrowedDateService;
import com.twistezo.service.CarService;
import com.twistezo.service.CustomerService;
import com.twistezo.service.MailService;
import it.ozimov.springboot.mail.configuration.EnableEmailTools;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
@Controller
@EnableEmailTools
@SessionAttributes({ "customer", "borrowedDate" })
public class BookResume {
private CarService carService;
private BorrowedDateService borrowedDateService;
private CustomerService customerService;
private MailService mailService;
private Car carById;
public BookResume(CarService carService, BorrowedDateService borrowedDateService, CustomerService customerService,
MailService mailService) {
this.carService = carService;
this.borrowedDateService = borrowedDateService;
this.customerService = customerService;
this.mailService = mailService;
}
@RequestMapping(value = "bookResume{car_id}", method = RequestMethod.GET)
public String showCustomerResume(Model model, Customer customer, BorrowedDate borrowedDate,
@RequestParam(value = "car_id") Long carId) {
carById = carService.findById(carId);
model.addAttribute("borrowedDate", borrowedDate);
model.addAttribute("cust", customer);
model.addAttribute("carById", carById);
return "bookResume";
}
@RequestMapping(value = "bookResume", method = RequestMethod.POST)
public String completeAll(Customer customer, BorrowedDate borrowedDate, SessionStatus status) {
borrowedDateService.save(borrowedDate);
customerService.save(customer);
mailService.sendMail(customer, borrowedDate, carById);
status.setComplete();
return "redirect:/";
}
}
| 40.803571 | 118 | 0.766302 |
ef067c9e45484326dac61aeadd48632fef2069aa | 1,034 | package com.ruoyi.system.mapper;
import java.util.List;
import com.ruoyi.system.domain.EduTeacher;
/**
* 老师Mapper接口
*
* @author huangcankun
* @date 2021-01-24
*/
public interface EduTeacherMapper
{
/**
* 查询老师
*
* @param id 老师ID
* @return 老师
*/
public EduTeacher selectEduTeacherById(Long id);
/**
* 查询老师列表
*
* @param eduTeacher 老师
* @return 老师集合
*/
public List<EduTeacher> selectEduTeacherList(EduTeacher eduTeacher);
/**
* 新增老师
*
* @param eduTeacher 老师
* @return 结果
*/
public int insertEduTeacher(EduTeacher eduTeacher);
/**
* 修改老师
*
* @param eduTeacher 老师
* @return 结果
*/
public int updateEduTeacher(EduTeacher eduTeacher);
/**
* 删除老师
*
* @param id 老师ID
* @return 结果
*/
public int deleteEduTeacherById(Long id);
/**
* 批量删除老师
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteEduTeacherByIds(Long[] ids);
}
| 16.677419 | 72 | 0.56383 |
391d35ed98bc94c50c01b3289cb3ef3610a1cc4c | 8,682 | package com.chess.game;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static com.chess.game.GameStatus.*;
import static com.chess.game.PieceStatus.*;
import static com.chess.game.PieceType.*;
import static com.chess.game.PlayerType.BLACK;
import static com.chess.game.PlayerType.WHITE;
import static org.junit.jupiter.api.Assertions.*;
@DisplayName("체스규칙")
class ChessRuleTest {
ChessBoardSetting chessBoardSetting;
ChessBoard chessBoard;
ChessRule chessRule;
@BeforeEach
void init() {
chessBoardSetting = new ChessBoardSetting();
chessBoard = new ChessBoard(new ChessRule(new ChessGameNotation()), new ChessBoardSetting(), new ChessPromotionManager());
chessRule = new ChessRule(new ChessGameNotation());
}
@Test
@DisplayName("체크메이트")
void checkmate_king() {
King whiteKing = (King)chessBoard.searchPiece(Position.of(7, 4));
Pawn whitePawn1 = (Pawn)chessBoard.searchPiece(Position.of(6, 5));
Pawn whitePawn2 = (Pawn)chessBoard.searchPiece(Position.of(6, 6));
Pawn blackPawn = (Pawn)chessBoard.searchPiece(Position.of(1, 4));
Queen blackQueen = (Queen)chessBoard.searchPiece(Position.of(0, 3));
whitePawn1.move(chessBoard, WHITE, Position.of(6, 5), Position.of(5, 5));
blackPawn.move(chessBoard, BLACK, Position.of(1, 4), Position.of(3, 4));
whitePawn2.move(chessBoard, WHITE, Position.of(6, 6), Position.of(4, 6));
blackQueen.move(chessBoard, BLACK, Position.of(0, 3), Position.of(4, 7));
assertTrue(whiteKing.isCheckmate(chessBoard));
}
@Test
@DisplayName("스테일메이트")
void stalemate_king() {
List<AbstractPiece> blackPieces = chessBoard.searchPlayerPieces(BLACK);
List<AbstractPiece> whitePieces = chessBoard.searchPlayerPieces(WHITE);
for(AbstractPiece blackPiece : blackPieces) {
if(blackPiece.getPieceType() != KING && blackPiece.getPieceType() != QUEEN) {
chessBoard.deletePiece(blackPiece);
}
}
for(AbstractPiece whitePiece : whitePieces) {
if(whitePiece.getPieceType() != KING) {
chessBoard.deletePiece(whitePiece);
}
}
King whiteKing = (King)chessBoard.searchPiece(Position.of(7, 4));
Queen blackQueen = (Queen)chessBoard.searchPiece(Position.of(0, 3));
whiteKing.move(chessBoard, WHITE, Position.of(7, 3), Position.of(7, 4));
whiteKing.move(chessBoard, WHITE, Position.of(7, 4), Position.of(7, 5));
whiteKing.move(chessBoard, WHITE, Position.of(7, 5), Position.of(7, 6));
whiteKing.move(chessBoard, WHITE, Position.of(7, 6), Position.of(7, 7));
blackQueen.move(chessBoard, BLACK, Position.of(0, 3), Position.of(6, 3));
blackQueen.move(chessBoard, BLACK, Position.of(6, 3), Position.of(6, 5));
assertTrue(whiteKing.isStalemate(chessBoard));
}
@Test
@DisplayName("킹만_남은경우")
void only_king() {
List<AbstractPiece> blackPieces = chessBoard.searchPlayerPieces(BLACK);
List<AbstractPiece> whitePieces = chessBoard.searchPlayerPieces(WHITE);
for(AbstractPiece blackPiece : blackPieces) {
if(blackPiece.getPieceType() != KING) {
chessBoard.deletePiece(blackPiece);
}
}
for(AbstractPiece whitePiece : whitePieces) {
if(whitePiece.getPieceType() != KING) {
chessBoard.deletePiece(whitePiece);
}
}
GameResult result = chessRule.judge(WHITE, chessBoard, chessBoard.searchPlayerKing(WHITE), ONE_MOVE);
assertEquals(LACK_OF_CHESS_PIECES, result.getGameStatus());
}
@Test
@DisplayName("킹과_나이트가_남은경우")
void is_only_king_and_knight() {
List<AbstractPiece> blackPieces = chessBoard.searchPlayerPieces(BLACK);
List<AbstractPiece> whitePieces = chessBoard.searchPlayerPieces(WHITE);
List<Knight> whiteKnights = new ArrayList<>();
// 블랙 킹만 남기기
for(AbstractPiece blackPiece : blackPieces) {
if(blackPiece.getPieceType() != KING) {
chessBoard.deletePiece(blackPiece);
}
}
// 화이트 킹과 나이트2개만 남기기
for(AbstractPiece whitePiece : whitePieces) {
if(whitePiece.getPieceType() != KING) {
if(whitePiece.getPieceType() == KNIGHT) {
whiteKnights.add((Knight)whitePiece);
} else {
chessBoard.deletePiece(whitePiece);
}
}
}
// 화이트 나이트 1개 삭제
chessBoard.deletePiece(whiteKnights.get(0));
GameResult result = chessRule.judge(WHITE, chessBoard, chessBoard.searchPlayerKing(WHITE), ONE_MOVE);
assertEquals(LACK_OF_CHESS_PIECES, result.getGameStatus());
}
@Test
@DisplayName("킹과_비숍이_남은경우")
void is_only_king_and_bishop() {
List<AbstractPiece> blackPieces = chessBoard.searchPlayerPieces(BLACK);
List<AbstractPiece> whitePieces = chessBoard.searchPlayerPieces(WHITE);
List<Bishop> whiteBishops = new ArrayList<>();
// 블랙 킹만 남기기
for(AbstractPiece blackPiece : blackPieces) {
if(blackPiece.getPieceType() != KING) {
chessBoard.deletePiece(blackPiece);
}
}
// 화이트 킹과 나이트2개만 남기기
for(AbstractPiece whitePiece : whitePieces) {
if(whitePiece.getPieceType() != KING) {
if(whitePiece.getPieceType() == BISHOP) {
whiteBishops.add((Bishop)whitePiece);
} else {
chessBoard.deletePiece(whitePiece);
}
}
}
// 화이트 나이트 1개 삭제
chessBoard.deletePiece(whiteBishops.get(0));
GameResult result = chessRule.judge(WHITE, chessBoard, chessBoard.searchPlayerKing(WHITE), ONE_MOVE);
assertEquals(LACK_OF_CHESS_PIECES, result.getGameStatus());
}
@Test
@DisplayName("킹과_비숍이_남고_양측의_비숍이_같은_색인_경우")
void is_only_king_and_bishop_is_same_color() {
List<AbstractPiece> blackPieces = chessBoard.searchPlayerPieces(BLACK);
List<AbstractPiece> whitePieces = chessBoard.searchPlayerPieces(WHITE);
List<Bishop> blackBishops = new ArrayList<>();
List<Bishop> whiteBishops = new ArrayList<>();
// 블랙 킹과 나이트2개만 남기기
for(AbstractPiece blackPiece : blackPieces) {
if(blackPiece.getPieceType() != KING) {
if(blackPiece.getPieceType() == BISHOP) {
blackBishops.add((Bishop)blackPiece);
} else {
chessBoard.deletePiece(blackPiece);
}
}
}
// 화이트 킹과 나이트2개만 남기기
for(AbstractPiece whitePiece : whitePieces) {
if(whitePiece.getPieceType() != KING) {
if(whitePiece.getPieceType() == BISHOP) {
whiteBishops.add((Bishop)whitePiece);
} else {
chessBoard.deletePiece(whitePiece);
}
}
}
// 블랙 나이트 1개, 화이트 나이트 1개 삭제
chessBoard.deletePiece(blackBishops.get(0));
chessBoard.deletePiece(whiteBishops.get(1));
GameResult result = chessRule.judge(WHITE, chessBoard, chessBoard.searchPlayerKing(WHITE), ONE_MOVE);
assertEquals(LACK_OF_CHESS_PIECES, result.getGameStatus());
}
@Test
@DisplayName("50수_규칙")
void fifty_move_rule() {
for(int i=0; i<50; i++) {
chessRule.judge(WHITE, chessBoard, chessBoard.searchPlayerKing(WHITE), ONE_MOVE);
}
GameResult result = chessRule.judge(WHITE, chessBoard, chessBoard.searchPlayerKing(WHITE), ONE_MOVE);
assertEquals(FIFTY_MOVE_RULE, result.getGameStatus());
}
@Test
@DisplayName("3회_동형반복")
void Three_isomorphic_repetitions_of_chess() {
Knight knight = (Knight)chessBoard.searchPiece(Position.of(7, 1));
chessBoard.put(WHITE, KNIGHT, Position.of(7, 1), Position.of(5, 0));
chessBoard.put(WHITE, KNIGHT, Position.of(5, 0), Position.of(7, 1));
chessBoard.put(WHITE, KNIGHT, Position.of(7, 1), Position.of(5, 0));
chessBoard.put(WHITE, KNIGHT, Position.of(5, 0), Position.of(7, 1));
chessBoard.put(WHITE, KNIGHT, Position.of(7, 1), Position.of(5, 0));
GameResult result = chessBoard.put(WHITE, KNIGHT, Position.of(5, 0), Position.of(7, 1));
assertEquals(THREE_ISOMORPHIC_REPETITIONS, result.getGameStatus());
}
} | 37.422414 | 130 | 0.628311 |
6fab09f58cab1d85194a9691b50bfed2a4fd4180 | 9,307 | package edu.utah.ece.async.sboldesigner.sbol;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import javax.xml.namespace.QName;
import org.joda.time.DateTime;
import org.sbolstandard.core2.Activity;
import org.sbolstandard.core2.Annotation;
import org.sbolstandard.core2.Association;
import org.sbolstandard.core2.CombinatorialDerivation;
import org.sbolstandard.core2.ComponentDefinition;
import org.sbolstandard.core2.GenericTopLevel;
import org.sbolstandard.core2.Identified;
import org.sbolstandard.core2.SBOLConversionException;
import org.sbolstandard.core2.SBOLDocument;
import org.sbolstandard.core2.SBOLValidationException;
import org.sbolstandard.core2.SBOLWriter;
import org.sbolstandard.core2.TopLevel;
import org.sbolstandard.core2.Usage;
import edu.utah.ece.async.sboldesigner.sbol.editor.SBOLEditorPreferences;
public class ProvenanceUtil {
/**
* Adds an SBOLDesignerActivity -> SBOLDesignerAgent to the wasDerivedFrom
* of every TopLevel that doesn't have an Activity. If an
* SBOLDesignerActivity already exists on the root, updates the end time.
*/
public static void createProvenance(SBOLDocument doc, ComponentDefinition root) throws SBOLValidationException {
createProvenance(doc, root, null);
}
private static final URI SEQUENCE_EDITOR = URI.create("http://sbols.org/v2#sequenceEditor");
/**
* Same as others, except usage will get added as a usage of the Activity.
*/
public static void createProvenance(SBOLDocument doc, ComponentDefinition root, Identified usage)
throws SBOLValidationException {
// Create or get the activity
String activityId = root.getDisplayId() + "_SBOLDesignerActivity";
Activity activity = null;
for (Activity a : doc.getActivities()) {
if (root.getWasGeneratedBys().contains(a.getIdentity()) && a.getDisplayId().equals(activityId)) {
activity = a;
break;
}
}
if (activity == null) {
activity = doc.createActivity(activityId, "1");
}
// Set the ended at time
activity.setEndedAtTime(DateTime.now());
// Set the usage
if (usage != null) {
String usageId = usage.getDisplayId() + "_Usage";
if (activity.getUsage(usageId) == null) {
Usage used = activity.createUsage(usageId, usage.getIdentity());
used.addRole(SEQUENCE_EDITOR);
}
}
// Set the creator
String creator = SBOLEditorPreferences.INSTANCE.getUserInfo().getName();
boolean hasCreator = false;
for (Annotation a : activity.getAnnotations()) {
if (a.getQName().getLocalPart().equals("creator") && a.isStringValue()
&& a.getStringValue().equals(creator)) {
hasCreator = true;
break;
}
}
if (!hasCreator) {
activity.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"), creator);
}
// Create the qualifiedAssociation
URI designerURI = URI.create("https://synbiohub.org/public/SBOL_Software/SBOLDesigner/3.0");
String designerPrefix = "https://synbiohub.org/public/SBOL_Software/SBOLDesigner/";
boolean hasAssociation = false;
for (Association a : activity.getAssociations()) {
if (a.getAgentURI() != null && a.getAgentURI().toString().startsWith(designerPrefix)) {
hasAssociation = true;
break;
}
}
if (!hasAssociation) {
Association association = activity.createAssociation("Association", designerURI);
association.addRole(SEQUENCE_EDITOR);
}
// Link with all TopLevels
for (TopLevel tl : doc.getTopLevels()) {
// check if in namespace
if (SBOLUtils.notInNamespace(tl) || tl instanceof Activity || tl instanceof CombinatorialDerivation) {
continue;
}
boolean hasActivity = false;
// Check if hasActivity
for (URI uri : tl.getWasGeneratedBys()) {
TopLevel generatedBy = doc.getTopLevel(uri);
if (generatedBy != null && generatedBy.getDisplayId().equals(activity.getDisplayId())
&& generatedBy instanceof Activity) {
hasActivity = true;
}
}
// Attach if there is no existing Activity
if (!hasActivity) {
tl.addWasGeneratedBy(activity.getIdentity());
}
}
}
/*
* The old broken version of createProvenance.
*/
private void addSBOLDesignerAnnotation(ComponentDefinition cd, SBOLDocument design) throws SBOLValidationException {
// get/create SBOLDesigner agent
URI designerURI = URI.create("https://synbiohub.org/public/SBOL_Software/SBOLDesigner/2.2");
// unused because designerURI will be dereferenced on SynBioHub
// designerURI = createSBOLDesignerAgent().getIdentity();
// get/create the activity
URI activityURI = URI
.create(design.getDefaultURIprefix() + cd.getDisplayId() + "_SBOLDesigner" + "/" + cd.getVersion());
GenericTopLevel oldActivity = design.getGenericTopLevel(activityURI);
if (oldActivity != null) {
design.removeGenericTopLevel(oldActivity);
}
GenericTopLevel partActivity = design.createGenericTopLevel(design.getDefaultURIprefix(),
cd.getDisplayId() + "_SBOLDesigner", cd.getVersion(),
new QName("http://www.w3.org/ns/prov#", "Activity", "prov"));
String creator = SBOLEditorPreferences.INSTANCE.getUserInfo().getName();
partActivity.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"), creator);
partActivity.createAnnotation(new QName("http://www.w3.org/ns/prov#", "endedAtTime", "prov"),
ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT));
// create the qualified usage annotation
Annotation agentAnnotation = new Annotation(new QName("http://www.w3.org/ns/prov#", "agent", "prov"),
designerURI);
partActivity.createAnnotation(new QName("http://www.w3.org/ns/prov#", "qualifiedAssociation", "prov"),
new QName("http://www.w3.org/ns/prov#", "Association", "prov"),
URI.create(partActivity.getIdentity().toString() + "/association"),
new ArrayList<Annotation>(Arrays.asList(agentAnnotation)));
// link the cd/part to partActivity
Annotation prev = null;
for (Annotation a : cd.getAnnotations()) {
if (a.getQName().getLocalPart().equals("wasGeneratedBy") && a.isURIValue()
&& a.getURIValue().equals(designerURI)) {
prev = a;
}
}
if (prev != null) {
cd.removeAnnotation(prev);
}
cd.createAnnotation(new QName("http://www.w3.org/ns/prov#", "wasGeneratedBy", "prov"),
partActivity.getIdentity());
}
/*
* The reference implementation for generating the SBOLDesigner Agent.
*/
private static GenericTopLevel createSBOLDesignerAgent(SBOLDocument design) throws SBOLValidationException {
GenericTopLevel designerAgent = design
.getGenericTopLevel(URI.create("https://synbiohub.org/public/SBOL_Software/SBOLDesigner/3.0"));
if (designerAgent == null) {
designerAgent = design.createGenericTopLevel("http://www.async.ece.utah.edu", "SBOLDesigner", "3.0",
new QName("http://www.w3.org/ns/prov#", "Agent", "prov"));
designerAgent.setName("SBOLDesigner CAD Tool");
designerAgent.setDescription(
"SBOLDesigner is a simple, biologist-friendly CAD software tool for creating and manipulating the sequences of genetic constructs using the Synthetic Biology Open Language (SBOL) 2 data model. Throughout the design process, SBOL Visual symbols, a system of schematic glyphs, provide standardized visualizations of individual parts. SBOLDesigner completes a workflow for users of genetic design automation tools. It combines a simple user interface with the power of the SBOL standard and serves as a launchpad for more detailed designs involving simulations and experiments. Some new features in SBOLDesigner are SynBioHub integration, local repositories, importing of parts/sequences from existing files, import and export of GenBank and FASTA files, extended role ontology support, the ability to partially open designs with multiple root ComponentDefinitions, backward compatibility with SBOL 1.1, and versioning.");
designerAgent.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"),
"Michael Zhang");
designerAgent.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"),
"Chris Myers");
designerAgent.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"),
"Michal Galdzicki");
designerAgent.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"),
"Bryan Bartley");
designerAgent.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"),
"Sean Sleight");
designerAgent.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"),
"Evren Sirin");
designerAgent.createAnnotation(new QName("http://purl.org/dc/elements/1.1/", "creator", "dc"),
"John Gennari");
}
return designerAgent;
}
public static void main(String[] args) throws SBOLValidationException, IOException, SBOLConversionException {
SBOLDocument doc = new SBOLDocument();
createSBOLDesignerAgent(doc);
SBOLWriter.write(doc, new File("C:/Users/Michael/Desktop/SBOLDesignerAgent.xml"));
}
}
| 42.304545 | 925 | 0.718169 |
614cc04c2ed2fc3cc7f5dfc605cd8b3775a1aa3e | 15,228 | package com.hyphenate.chatuidemo.ui;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMucSharedFile;
import com.hyphenate.chatuidemo.R;
import com.hyphenate.easeui.model.EaseCompat;
import com.hyphenate.util.PathUtil;
import com.hyphenate.util.TextFormater;
import com.hyphenate.util.UriUtils;
import com.hyphenate.util.VersionUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class SharedFilesActivity extends BaseActivity {
private static final int REQUEST_CODE_SELECT_FILE = 1;
private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
private int pageSize = 10;
private int pageNum = 1;
private String groupId;
EMGroup group;
private List<EMMucSharedFile> fileList;
private FilesAdapter adapter;
private boolean hasMoreData;
private boolean isLoading;
private ProgressBar loadmorePB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_files);
groupId = getIntent().getStringExtra("groupId");
group = EMClient.getInstance().groupManager().getGroup(groupId);
fileList = new ArrayList<>();
listView = (ListView) findViewById(R.id.list_view);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more);
registerForContextMenu(listView);
showFileList(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showFile(fileList.get(position));
}
});
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int lasPos = view.getLastVisiblePosition();
if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
&& hasMoreData
&& !isLoading
&& lasPos == fileList.size() -1){
showFileList(false);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
showFileList(true);
}
});
}
private void showFileList(final boolean isRefresh) {
isLoading = true;
if(isRefresh){
pageNum = 1;
swipeRefreshLayout.setRefreshing(true);
}else{
pageNum++;
loadmorePB.setVisibility(View.VISIBLE);
}
EMClient.getInstance().groupManager().asyncFetchGroupSharedFileList(groupId, pageNum, pageSize, new EMValueCallBack<List<EMMucSharedFile>>() {
@Override
public void onSuccess(final List<EMMucSharedFile> value) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(isRefresh) {
swipeRefreshLayout.setRefreshing(false);
}else{
loadmorePB.setVisibility(View.INVISIBLE);
}
isLoading = false;
if(isRefresh)
fileList.clear();
fileList.addAll(value);
if(value.size() == pageSize){
hasMoreData = true;
}else{
hasMoreData = false;
}
if(adapter == null){
adapter = new FilesAdapter(SharedFilesActivity.this, 1, fileList);
listView.setAdapter(adapter);
}else{
adapter.notifyDataSetChanged();
}
}
});
}
@Override
public void onError(int error, String errorMsg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(SharedFilesActivity.this, "Load files fail", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* If local file doesn't exits, download it first.
* else show file directly
* @param file
*/
private void showFile(EMMucSharedFile file){
final File localFile = new File(PathUtil.getInstance().getFilePath(), file.getFileName());
if(localFile.exists()){
openFile(localFile);
return;
}
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Downloading...");
pd.setCanceledOnTouchOutside(false);
pd.show();
EMClient.getInstance().groupManager().asyncDownloadGroupSharedFile(
groupId,
file.getFileId(),
localFile.getAbsolutePath(),
new EMCallBack() {
@Override
public void onSuccess() {
runOnUiThread(new Runnable() {
@Override
public void run() {
pd.dismiss();
openFile(localFile);
}
});
}
@Override
public void onError(int code, final String error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
pd.dismiss();
Toast.makeText(SharedFilesActivity.this, "Download file fails, " + error, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onProgress(int progress, String status) {
}
}
);
}
private void openFile(File file){
if(file != null && file.exists()){
EaseCompat.openFile(file, this);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("Delete File");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Deleting...");
pd.setCanceledOnTouchOutside(false);
pd.show();
final int position = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
EMClient.getInstance().groupManager().asyncDeleteGroupSharedFile(
groupId,
fileList.get(position).getFileId(),
new EMCallBack() {
@Override
public void onSuccess() {
runOnUiThread(new Runnable() {
@Override
public void run() {
pd.dismiss();
fileList.remove(position);
adapter.notifyDataSetChanged();
}
});
}
@Override
public void onError(int code, final String error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
pd.dismiss();
Toast.makeText(SharedFilesActivity.this, "Delete file fails, " + error, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onProgress(int progress, String status) {
}
}
);
return super.onContextItemSelected(item);
}
/**
* upload file button clicked
* @param view
*/
public void uploadFile(View view){
selectFileFromLocal();
}
/**
* select file
*/
protected void selectFileFromLocal() {
EaseCompat.openImage(this, REQUEST_CODE_SELECT_FILE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_CODE_SELECT_FILE){
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
if(VersionUtils.isTargetQ(this)) {
uploadFileWithUri(uri);
}else {
sendByPath(uri);
}
}
}
}
}
}
private void sendByPath(Uri uri) {
String path = EaseCompat.getPath(this, uri);
if(TextUtils.isEmpty(path)) {
Toast.makeText(this, R.string.File_does_not_exist, Toast.LENGTH_SHORT).show();
return;
}
uploadFileWithUri(Uri.parse(path));
}
private void uploadFileWithUri(Uri uri) {
if(!UriUtils.isFileExistByUri(this, uri)) {
Toast.makeText(this, R.string.File_does_not_exist, Toast.LENGTH_SHORT).show();
return;
}
final ProgressDialog pd = new ProgressDialog(this);
pd.setCanceledOnTouchOutside(false);
pd.setMessage("Uploading...");
pd.show();
EMClient.getInstance().groupManager().asyncUploadGroupSharedFile(groupId, uri.toString(), new EMCallBack() {
@Override
public void onSuccess() {
runOnUiThread(new Runnable() {
@Override
public void run() {
pd.dismiss();
if(adapter != null){
fileList.clear();
fileList.addAll(group.getShareFileList());
adapter.notifyDataSetChanged();
Toast.makeText(SharedFilesActivity.this, "Upload success", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onError(int code, final String error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
pd.dismiss();
Toast.makeText(SharedFilesActivity.this, "Upload fail, " + error, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onProgress(int progress, String status) {
}
});
}
@Nullable
private String getFilePath(Uri uri) {
String filePath = null;
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
filePath = cursor.getString(column_index);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
filePath = uri.getPath();
}
if (filePath == null) {
return null;
}
return filePath;
}
private static class FilesAdapter extends ArrayAdapter<EMMucSharedFile> {
private Context mContext;
private LayoutInflater inflater;
List<EMMucSharedFile> list;
public FilesAdapter(@NonNull Context context, int resource, @NonNull List<EMMucSharedFile> objects) {
super(context, resource, objects);
mContext = context;
this.inflater = LayoutInflater.from(context);
list = objects;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = View.inflate(mContext, R.layout.em_shared_file_row, null);
holder.tv_file_name = (TextView) convertView.findViewById(R.id.tv_file_name);
holder.tv_file_size = (TextView) convertView.findViewById(R.id.tv_file_size);
holder.tv_update_time = (TextView) convertView.findViewById(R.id.tv_update_time);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv_file_name.setText(getItem(position).getFileName());
holder.tv_file_size.setText(TextFormater.getDataSize(getItem(position).getFileSize()));
holder.tv_update_time.setText(new Date(getItem(position).getFileUpdateTime()).toString());
return convertView;
}
}
private static class ViewHolder {
TextView tv_file_name;
TextView tv_file_size;
TextView tv_update_time;
}
}
| 35.25 | 150 | 0.53533 |
eb011aa485f4c6ceb9ab1a3064904b50584fcc7c | 2,702 | package com.example.shequtest.module;
import android.os.Parcel;
import android.os.Parcelable;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobRelation;
public class Knowledge extends BmobObject implements Parcelable {
private String content;
private MyUser author;
private BmobFile picture;
private String interest;//趣味知识
private String type;//测试类别
private String title;
private BmobRelation record;//学习记录
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public MyUser getAuthor() {
return author;
}
public void setAuthor(MyUser author) {
this.author = author;
}
public BmobFile getPicture() {
return picture;
}
public void setPicture(BmobFile picture) {
this.picture = picture;
}
public String getInterest() {
return interest;
}
public void setInterest(String interest) {
this.interest = interest;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BmobRelation getRecord() {
return record;
}
public void setRecord(BmobRelation record) {
this.record = record;
}
public Knowledge(String content , String interest, String type, String title) {
super();
this.content = content;
this.interest = interest;
this.type = type;
this.title=title;
}
public Knowledge() {
super();
}
public Knowledge(Parcel source) {
content = source.readString();
interest=source.readString();
type = source.readString();
title=source.readString();
}
/**
* 这里默认返回0即可
*/
@Override
public int describeContents() {
return 0;
}
/**
* 把值写*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(content);
dest.writeString(interest);
dest.writeString(type);
dest.writeString(title);
}
public static final Creator<Knowledge> CREATOR = new Creator<Knowledge>() {
/**
* 供外部类反序列化本类数组使用
*/
@Override
public Knowledge[] newArray(int size) {
return new Knowledge[size];
}
@Override
public Knowledge createFromParcel(Parcel source) {
return new Knowledge(source);
}
};
}
| 20.784615 | 83 | 0.599186 |
f4c55d6257d52bd3e46744f6c043315f93aba073 | 4,388 | /*
* Copyright (c) 2021 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.integrations.source.mysql.helpers;
import com.fasterxml.jackson.databind.JsonNode;
import io.airbyte.commons.functional.CheckedConsumer;
import io.airbyte.commons.json.Jsons;
import io.airbyte.db.jdbc.JdbcDatabase;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper class for MySqlSource used to check cdc configuration in case of:
* <p>
* 1. adding new source and checking operations #getCheckOperations method.
* </p>
* <p>
* 2. checking whether binlog required from saved cdc offset is available on mysql server
* #checkBinlog method
* </p>
*/
public class CdcConfigurationHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(CdcConfigurationHelper.class);
private static final String CDC_OFFSET = "mysql_cdc_offset";
private static final String LOG_BIN = "log_bin";
private static final String BINLOG_FORMAT = "binlog_format";
private static final String BINLOG_ROW_IMAGE = "binlog_row_image";
/**
* Method will check whether required binlog is available on mysql server
*
* @param offset - saved cdc offset with required binlog file
* @param database - database
*/
public static void checkBinlog(final JsonNode offset, final JdbcDatabase database) {
final Optional<String> binlogOptional = getBinlog(offset);
binlogOptional.ifPresent(binlog -> {
if (isBinlogAvailable(binlog, database)) {
LOGGER.info("""
Binlog %s is available""".formatted(binlog));
} else {
final String error =
"""
Binlog %s is not available. This is a critical error, it means that requested binlog is not present on mysql server. To fix data synchronization you need to reset your data. Please check binlog retention policy configurations."""
.formatted(binlog);
LOGGER.error(error);
throw new RuntimeException("""
Binlog %s is not available.""".formatted(binlog));
}
});
}
/**
* Method will get required configurations for cdc sync
*
* @return list of List<CheckedConsumer<JdbcDatabase, Exception>>
*/
public static List<CheckedConsumer<JdbcDatabase, Exception>> getCheckOperations() {
return List.of(getCheckOperation(LOG_BIN, "ON"),
getCheckOperation(BINLOG_FORMAT, "ROW"),
getCheckOperation(BINLOG_ROW_IMAGE, "FULL"));
}
private static boolean isBinlogAvailable(final String binlog, final JdbcDatabase database) {
if (binlog.isEmpty()) {
return false;
}
try (final Stream<String> binlogs = database.unsafeResultSetQuery(
connection -> connection.createStatement().executeQuery("SHOW BINARY LOGS"),
resultSet -> resultSet.getString("Log_name"))) {
return binlogs.anyMatch(e -> e.equals(binlog));
} catch (final SQLException e) {
LOGGER.error("Can not get binlog list. Error: ", e);
throw new RuntimeException(e);
}
}
private static Optional<String> getBinlog(final JsonNode offset) {
final JsonNode node = offset.get(CDC_OFFSET);
final Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
final Map.Entry<String, JsonNode> jsonField = fields.next();
return Optional.ofNullable(Jsons.deserialize(jsonField.getValue().asText()).path("file").asText());
}
return Optional.empty();
}
private static CheckedConsumer<JdbcDatabase, Exception> getCheckOperation(final String name, final String value) {
return database -> {
final List<String> result = database.queryStrings(
connection -> connection.createStatement().executeQuery(String.format("show variables where Variable_name = '%s'", name)),
resultSet -> resultSet.getString("Value"));
if (result.size() != 1) {
throw new RuntimeException("Could not query the variable " + name);
}
final String resultValue = result.get(0);
if (!resultValue.equalsIgnoreCase(value)) {
throw new RuntimeException(String.format("The variable \"%s\" should be set to \"%s\", but it is \"%s\"", name, value, resultValue));
}
};
}
}
| 37.504274 | 241 | 0.691659 |
b67dc091e7e26db16e86b28d3e0503f5005fad08 | 1,741 | package wang.bannong.gk5.ntm.rpc.service.api.apis;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import wang.bannong.gk5.ntm.common.exception.NtmException;
import wang.bannong.gk5.ntm.common.model.NtmInnerRequest;
import wang.bannong.gk5.ntm.common.model.NtmResult;
import wang.bannong.gk5.ntm.rpc.biz.NtmApiMgr;
import wang.bannong.gk5.ntm.rpc.service.BaseInnerService;
import wang.bannong.gk5.util.Constant;
@Slf4j
@Service
public class InnerApiMoveDict implements BaseInnerService {
@Autowired
private NtmApiMgr ntmApiMgr;
@Override
public NtmResult api(NtmInnerRequest innerRequest) {
String apiIds = innerRequest.get("apiIds");
if (StringUtils.isBlank(apiIds)) {
return NtmResult.fail("请先选择接口API");
}
String dictId = innerRequest.get("dictId");
if (StringUtils.isBlank(dictId)) {
return NtmResult.fail("请选择目的目录");
}
try {
return ntmApiMgr.moveDict(Splitter.on(Constant.COMMA)
.trimResults()
.splitToList(apiIds)
.stream()
.map(i -> Long.valueOf(i))
.collect(Collectors.toList()), Long.valueOf(dictId));
} catch (Exception e) {
log.error("新增接口定义报错,apiIds={},dictId={},异常信息:", apiIds, dictId, e);
throw new NtmException(e);
}
}
} | 35.530612 | 99 | 0.615164 |
9849545af35aba79d456f419cfe75913ff957ac5 | 3,253 |
/*-
* ============LICENSE_START==========================================
* OPENECOMP - DCAE
* ===================================================================
* Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
* ===================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END============================================
*/
/**
*/
package org.openecomp.ncomp.openstack.location;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Hypervisor Service</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.openecomp.ncomp.openstack.location.HypervisorService#getHost <em>Host</em>}</li>
* <li>{@link org.openecomp.ncomp.openstack.location.HypervisorService#getId <em>Id</em>}</li>
* </ul>
*
* @see org.openecomp.ncomp.openstack.location.LocationPackage#getHypervisorService()
* @model
* @generated
*/
public interface HypervisorService extends EObject {
/**
* Returns the value of the '<em><b>Host</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Host</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Host</em>' attribute.
* @see #setHost(String)
* @see org.openecomp.ncomp.openstack.location.LocationPackage#getHypervisorService_Host()
* @model unique="false"
* @generated
*/
String getHost();
/**
* Sets the value of the '{@link org.openecomp.ncomp.openstack.location.HypervisorService#getHost <em>Host</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Host</em>' attribute.
* @see #getHost()
* @generated
*/
void setHost(String value);
/**
* Returns the value of the '<em><b>Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Id</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Id</em>' attribute.
* @see #setId(int)
* @see org.openecomp.ncomp.openstack.location.LocationPackage#getHypervisorService_Id()
* @model unique="false"
* @generated
*/
int getId();
/**
* Sets the value of the '{@link org.openecomp.ncomp.openstack.location.HypervisorService#getId <em>Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Id</em>' attribute.
* @see #getId()
* @generated
*/
void setId(int value);
} // HypervisorService
| 32.858586 | 125 | 0.610821 |
325f79346b0a74d4aec647fbc2a7b7a5d30539dc | 2,012 | package org.example;
public class Employee extends Object{
private String EmployeeFirstName;
private String EmployeeLastName;
private Integer EmployeeId;
private String EmployeeDeptId;
public Employee()
{
super();
}
public Employee(String EmployeeFirstName, String EmployeeLastName, Integer EmployeeId, String EmployeeDeptId)
{
this.EmployeeFirstName = EmployeeFirstName;
this.EmployeeLastName = EmployeeLastName;
this.EmployeeId = EmployeeId;
this.EmployeeDeptId = EmployeeDeptId;
}
public String getEmployeeFirstName()
{
return this.EmployeeFirstName;
}
public String getEmployeeLastName()
{
return this.EmployeeLastName;
}
public Integer getEmployeeId()
{
return this.EmployeeId;
}
public String getEmployeeDeptId()
{
return this.EmployeeDeptId;
}
public void setEmployeeDeptId(String Dept_Id)
{
this.EmployeeDeptId =Dept_Id;
}
@Override
public String toString()
{
return "EmpFirstName:"+this.getEmployeeFirstName() +" EmpLastname:" + this.getEmployeeLastName()+
" EmpId:"+ this.getEmployeeId() + " DeptId:"+this.getEmployeeDeptId();
}
@Override
public boolean equals(Object obj)
{
if(this == obj)
return true;
if(obj instanceof Employee)
{
Employee otherEmp = (Employee) obj;
if(this.getEmployeeFirstName().equals(otherEmp.getEmployeeFirstName()) == false)
return false;
if(this.getEmployeeLastName().equals(otherEmp.getEmployeeLastName()) == false)
return false;
if(this.getEmployeeId().equals(otherEmp.getEmployeeId()) == false)
return false;
if(this.getEmployeeDeptId().equals(otherEmp.getEmployeeDeptId()) == false)
return false;
return true;
}
return false;
}
}
| 24.536585 | 113 | 0.618787 |
c35e8fddadf809adefaae8c72e306e4f774c8caf | 282 | package complie;
import com.depth.ap_annoation.Api;
/**
* <pre>
* Tip:
*
*
* Created by ACap on 2021/4/15 13:48
* </pre>
*/
@Api(method = "DemoMathodName")
public class DemoApi {
public DemoApi() { //调用Make Project开始生成
DemoApiGenerate.DemoMathodName();
}
}
| 14.842105 | 43 | 0.631206 |
0f98a4b8d16c14c7ec395e8e5e9a3ab8efb86c44 | 3,128 | /*
* To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
//package Clases;
//
///**
// *
// * @author zgame
// */
//public class PrbMultilista {
//
// /**
// * @param args the command line arguments
// */
// public static void main(String[] args)
// {
// Nodo r=null;
//
// //CREA UN NODO PARA CADA PAIS
// Nodo p1 = new Nodo(null,"Fracia");
// Nodo p2 = new Nodo(null,"Afganistan");
// Nodo p3 = new Nodo(null,"Mexico");
//
// //CREA UN NODO PARA CADA ESTADO
// Nodo e1 = new Nodo(null,"Edo Mexico");
// Nodo e2 = new Nodo(null,"Jalisco");
// Nodo e3 = new Nodo(null,"Guerrero");
//
// //CREA UN NODO PARA CADA MUNICIIO
// Nodo m1 = new Nodo(null,"Xonacatlan");
// Nodo m2 = new Nodo(null,"Toluca");
// Nodo m3 = new Nodo(null,"Valle de Bravo");
//
// //INSERTA LOS DATOS DE LOS PAISES
//
// System.out.println("---INSERTA LOS PAISES---");
//
// String []etqs = new String[1];//ARREGLO DE ETIQUETAS
//
// etqs[0]="Francia";
// r=Multilistas.inserta(r,p1,0,etqs,);
// etqs[0]="Afganistan";
// r=Multilistas.inserta(r,p2,0,etqs);
// etqs[0]="Mexico";
// r=Multilistas.inserta(r,p3,0,etqs);
//
// //System.out.println(Multilistas.desp(r, 0));
//
//
// //INSERTA LOS DATOS DE LOS ESTADOS
// System.out.println("---INSERTA LOS ESTADOS---");
//
// etqs = new String[2];
// etqs[0]="Mexico";//ACCEDE AL PAIS MEXICO
//
// etqs[1] = "Edo Mexico";
// r=Multilistas.inserta(r,e1,0,etqs);
// etqs[1]="Jalisco";
// r=Multilistas.inserta(r,e2,0,etqs);
// etqs[1]="Guerrero";
// r=Multilistas.inserta(r,e3,0,etqs);
//
// //System.out.println(Multilistas.desp(r,0));
//
//
// System.out.println("---INSERTA LAS MUNICIPIOS---");
// etqs = new String[3];
// etqs[0]="Mexico";
// etqs[1] = "Edo Mexico";
//
// etqs[2]="Xonacatlan";
// r=Multilistas.inserta(r,m1,0,etqs);
// etqs[2]="Toluca";
// r=Multilistas.inserta(r,m2,0,etqs);
// etqs[2]="Valle de Bravo";
// r=Multilistas.inserta(r,m3,0,etqs);
//
// //System.out.println(Multilistas.desp(r,0));
//
//
// String prueba = "ñ";
// System.out.println(prueba.codePointAt(0));
//
// String prueba2="Ñ";
// System.out.println(prueba2.codePointAt(0));
//
//
// String prueba3=" IVAN LOPEZ CARRANZA ";
// String replaceAll = prueba3.replaceAll("\\s{2,}", " ").trim();
//
// System.out.println(replaceAll);
// //System.out.println("---BUSCA UN ELEMENTO DENTRO DE LA MULTILISTA---");
//
// //Multilistas.busca(r,"Jalisco");
//
// }
//
//}
| 30.970297 | 82 | 0.497762 |
718ba54bcbe2017e0be75dd7190cd033969619a3 | 1,422 | import java.util.Scanner;
import java.util.ArrayList;
public class PT1 {
public static void main(String[] args) {
ArrayList<String> Blog = new ArrayList<String>();
Scanner in = new Scanner(System.in);
char key;
String keyword,ch;
ok:
while(true) {
System.out.print("請輸入 \'i\', \'o\', \'r\'或\'q\': ");
key = in.next().charAt(0);
ch = in.nextLine();
switch(key) {
case'q':
in.close();
System.out.print("謝謝光臨 :)");
break ok;
case'i':
System.out.print("請輸入要加入的新關鍵字: ");
keyword = in.nextLine();
Blog.add(keyword);
System.out.println("已加入新關鍵字");
break;
case'r':
System.out.print("請輸入要刪除的關鍵字: ");
keyword = in.nextLine();
if(Blog.contains(keyword) == false) {
System.out.println("沒有 \""+keyword+"\" 這個關鍵字");
while(true) {
System.out.print("是否儲存此關鍵字(y/n)? ");
key = in.next().charAt(0);
ch = in.nextLine();
if(key == 'y') {
Blog.add(keyword);
System.out.println("已加入新關鍵字");
break;
}
else if(key == 'n') {
break;
}
else {
System.out.println("阿哩嗎豪啦別鬧了行不?!");
continue;
}
}
}
else {
Blog.remove(keyword);
System.out.println("已刪除該關鍵字");
}
break;
case'o':
System.out.println(Blog);
System.out.println("以上為目前所有的關鍵字");
break;
default:
System.out.println("請輸入正確的字元");
break;
}
}
}
}
| 20.608696 | 55 | 0.54571 |
7e13b259c472a216b094a696e807a8bf536677dc | 2,681 | /*
* Copyright (c) 2017. Jamie Thompson <[email protected]>
*/
package com.github.bishabosha.cuppajoe.examples.sequences;
import com.github.bishabosha.cuppajoe.collections.mutable.sequences.NonRecursiveSequence;
import com.github.bishabosha.cuppajoe.collections.mutable.sequences.RecursiveSequence;
import com.github.bishabosha.cuppajoe.collections.mutable.sequences.Sequence;
import java.util.function.Supplier;
public class SequenceOf {
public static Sequence<Integer> randomPalindromes(int minValue) {
return new NonRecursiveSequence<>(x -> (int) (minValue / Math.random()))
.filter(PredicateFor.isPalindromeInteger());
}
public static Sequence<Long> fibonacci() {
return new RecursiveSequence<>(xs -> {
if (xs.isEmpty()) {
return (long) 1;
}
if (xs.size() == 1) {
return (long) 1;
}
return xs.get(xs.size() - 1) + xs.get(xs.size() - 2);
});
}
public static Sequence<Long> primes() {
Supplier<Long> counter = new Supplier<>() {
long count = 1;
@Override
public Long get() {
return count += 2;
}
};
return new RecursiveSequence<>(xs -> {
if (0 == xs.size()) {
return (long) 2;
}
while (true) {
var value = counter.get();
var sqrt = Math.sqrt(value);
if (!PredicateFor.isMultipleOf(xs, x -> x > sqrt).test(value)) {
return value;
}
}
});
}
public static Sequence<Long> range(long start, long end) {
return range(start, start > end ? -1 : 1, end);
}
public static Sequence<Long> range(long start, long interval, long end) {
return new NonRecursiveSequence<>(x -> start + (x - 1) * interval)
.takeWhile(end <= start ? x -> x >= end : x -> x <= end);
}
public static Sequence<Long> naturals() {
return new NonRecursiveSequence<>(Long::valueOf);
}
public static Sequence<Long> integers() {
return new RecursiveSequence<>(x -> (long) x.size());
}
public static Sequence<Long> exponentials(int baseTerm) {
return new NonRecursiveSequence<>(x -> (long) Math.pow(baseTerm, x));
}
public static Sequence<Long> powers(int power) {
return new NonRecursiveSequence<>(x -> (long) Math.pow(x, power));
}
public static Sequence<Long> squares() {
return powers(2);
}
public static Sequence<Long> cubes() {
return powers(3);
}
}
| 30.816092 | 89 | 0.565088 |
db453f859e3da9fc79d25093d738fe809382edbb | 760 | package com.a.platform.member.message;
import com.a.platform.member.model.bo.MemberBO;
import java.io.Serializable;
/**
* 会员注册发送消息
*
* @author weixing.yang
* @version 1.0
* @date 2019/10/22 17:18
*/
public class MemberRegisterMsg implements Serializable {
private static final long serialVersionUID = 1913944052387917137L;
private MemberBO member;
private String uuid;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public MemberBO getMember() {
return member;
}
public void setMember(MemberBO member) {
this.member = member;
}
}
| 17.272727 | 70 | 0.657895 |
4bd8483bd099ebeac226abc3bfa942e0b5279457 | 8,349 | /*
* Copyright 2017 EntIT Software LLC, a Micro Focus company, L.P.
* 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.hp.octane.integrations.services.vulnerabilities.fod.dto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.hp.octane.integrations.OctaneSDK;
import com.hp.octane.integrations.dto.configuration.CIProxyConfiguration;
import com.hp.octane.integrations.exceptions.PermanentException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
import java.util.function.Predicate;
/**
* Created by hijaziy on 7/30/2017.
*/
public class FODConnector implements FODSource {
private static final Logger logger = LogManager.getLogger(FODConnector.class);
private CloseableHttpClient httpClient;
private String access_token;
private long accessTokenTime;
private final FODConfig fodConfig;
public FODConnector(FODConfig fodConfig) {
this.fodConfig = fodConfig;
}
public void initConnection(OctaneSDK.SDKServicesConfigurer configurer) {
logger.debug("init FOD connector");
try {
CIProxyConfiguration proxyConfiguration = configurer.pluginServices.getProxyConfiguration(new URL(this.fodConfig.authURL));
if (proxyConfiguration != null) {
logger.warn("FOD connection needs proxy");
HttpClientBuilder clientBuilder = HttpClients.custom();
String proxyHost = proxyConfiguration.getHost();
Integer proxyPortNumber = proxyConfiguration.getPort();
clientBuilder.setProxy(new HttpHost(proxyHost, proxyPortNumber));
httpClient = clientBuilder.build();
} else {
logger.warn("FOD connection does not need proxy");
httpClient = HttpClients.createDefault();
}
getAccessToken();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
@Override
public <T extends FODEntityCollection> T getAllFODEntities(String rawURL, Class<T> targetClass, Predicate<T> whenToStopFetch) {
try {
T fetchedEnts = targetClass.newInstance();
boolean allIsFetched = false;
boolean shouldStopFetching = false;
while (!allIsFetched) {
try {
int offset = fetchedEnts.items.size();
String indexedURL = addOffsetToURL(rawURL, offset);
String rawResponse = getRawResponseFromFOD(indexedURL);
//Deserialize.
T entityCollection = new ObjectMapper().readValue(rawResponse,
TypeFactory.defaultInstance().constructType((fetchedEnts).getClass()));
if (whenToStopFetch != null) {
shouldStopFetching = whenToStopFetch.test(entityCollection);
}
fetchedEnts.items.addAll(entityCollection.items);
fetchedEnts.totalCount = fetchedEnts.items.size();
allIsFetched = (fetchedEnts.totalCount == entityCollection.totalCount) || shouldStopFetching;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
return fetchedEnts;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
@Override
public <T> T getSpeceficFODEntity(String rawURL, Class<T> targetClass) {
try {
T fetchedEntityInstance = targetClass.newInstance();
String rawResponse = getRawResponseFromFOD(rawURL);
//Deserialize.
T entityFetched = new ObjectMapper().readValue(rawResponse,
TypeFactory.defaultInstance().constructType((fetchedEntityInstance).getClass()));
return entityFetched;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String addOffsetToURL(String rawURL, int offset) {
String offsetDirective = "offset=" + String.valueOf(offset);
if (!rawURL.contains("?")) {
return rawURL + "?" + offsetDirective;
}
return rawURL + "&" + offsetDirective;
}
private String getRawResponseFromFOD(String url) {
//URL encode
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", "Bearer " + getUpdatedAccessToken());
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Cookie", "__zlcmid=hTgaa94NtAdw5T; FoD=1725197834.36895.0000");
httpGet.setHeader("Accept-Encoding", "gzip, deflate, br");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 401) {
getAccessToken();
//retry.
response = httpClient.execute(httpGet);
}
return isToString(response.getEntity().getContent());
} catch (IOException e) {
e.printStackTrace();
getAccessToken();
//retry.
try {
response = httpClient.execute(httpGet);
return isToString(response.getEntity().getContent());
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
HttpClientUtils.closeQuietly(response);
}
}
return null;
}
private String getUpdatedAccessToken() {
long currentTime = new Date().getTime();
long delta = getTimeToRefreshToken();
if (currentTime - accessTokenTime >= delta) {
getAccessToken();
}
return access_token;
}
private void getAccessToken() {
HttpPost post = new HttpPost(fodConfig.authURL);
HttpEntity content = new StringEntity(fodConfig.getAuthBody(), ContentType.APPLICATION_FORM_URLENCODED);
post.setEntity(content);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != 200 &&
response.getStatusLine().getStatusCode() != 201) {
throw new PermanentException("Cannot authenticate:" +response.getStatusLine().getReasonPhrase());
}
String secToken = isToString(response.getEntity().getContent());
HashMap secTokeAsMap = new ObjectMapper().readValue(secToken, HashMap.class);
access_token = secTokeAsMap.get("access_token").toString();
accessTokenTime = new Date().getTime();
} catch (IOException e) {
e.printStackTrace();
if(response != null) {
EntityUtils.consumeQuietly(response.getEntity());
HttpClientUtils.closeQuietly(response);
}
throw new PermanentException("Cannot authenticate:" + e.getMessage());
} finally {
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
HttpClientUtils.closeQuietly(response);
}
}
}
static String isToString(InputStream is) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(Charset.forName("UTF-8").name());
}
@Override
public String getEntitiesURL() {
return fodConfig.entitiesURL;
}
public static Long getTimeToRefreshToken() {
//String fortifyPollDelayStr = siteParamsService.getParam(FODConstants.TIME_TO_REFRESH_FORTIFY_TOKEN_MINUTES);
return 60L * 1000 * 60;
}
}
| 32.360465 | 128 | 0.734459 |
6bae853d6e15a0bc7f9158144d679ee580eef8ed | 6,778 | /*
* 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.drill.exec.physical.resultSet.model.single;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.expr.TypeHelper;
import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
import org.apache.drill.exec.record.VectorContainer;
import org.apache.drill.exec.record.metadata.ColumnMetadata;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.exec.record.metadata.VariantMetadata;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.drill.exec.vector.complex.AbstractMapVector;
import org.apache.drill.exec.vector.complex.ListVector;
import org.apache.drill.exec.vector.complex.RepeatedListVector;
import org.apache.drill.exec.vector.complex.UnionVector;
/**
* Build (materialize) as set of vectors based on a provided
* metadata schema. The vectors are bundled into a
* {@link VectorContainer} which is the end product of this
* builder.
* <p>
* Vectors are built recursively by walking the tree that defines a
* row's structure. For a classic relational tuple, the tree has just
* a root and a set of primitives. But, once we add array (repeated),
* variant (LIST, UNION) and tuple (MAP) columns, the tree grows
* quite complex.
*/
public class BuildVectorsFromMetadata {
private final BufferAllocator allocator;
public BuildVectorsFromMetadata(BufferAllocator allocator) {
this.allocator = allocator;
}
public VectorContainer build(TupleMetadata schema) {
final VectorContainer container = new VectorContainer(allocator);
for (int i = 0; i < schema.size(); i++) {
container.add(buildVector(schema.metadata(i)));
}
// Build the row set from a matching triple of schema, container and
// column models.
container.buildSchema(SelectionVectorMode.NONE);
return container;
}
private ValueVector buildVector(ColumnMetadata metadata) {
switch (metadata.structureType()) {
case TUPLE:
return buildMap(metadata);
case VARIANT:
if (metadata.isArray()) {
return builList(metadata);
} else {
return buildUnion(metadata);
}
case MULTI_ARRAY:
return buildRepeatedList(metadata);
default:
return TypeHelper.getNewVector(metadata.schema(), allocator, null);
}
}
private ValueVector buildRepeatedList(ColumnMetadata metadata) {
final RepeatedListVector listVector = new RepeatedListVector(metadata.emptySchema(), allocator, null);
if (metadata.childSchema() != null) {
final ValueVector child = buildVector(metadata.childSchema());
listVector.setChildVector(child);
}
return listVector;
}
/**
* Build a map column including the members of the map given a map
* column schema.
*
* @param schema the schema of the map column
* @return the completed map vector column model
*/
private AbstractMapVector buildMap(ColumnMetadata schema) {
// Creating the map vector will create its contained vectors if we
// give it a materialized field with children. So, instead pass a clone
// without children so we can add the children as we add vectors.
final AbstractMapVector mapVector = (AbstractMapVector) TypeHelper.getNewVector(schema.emptySchema(), allocator, null);
populateMap(mapVector, schema.mapSchema(), false);
return mapVector;
}
/**
* Create the contents building the model as we go.
*
* @param mapVector the vector to populate
* @param mapSchema description of the map
*/
private void populateMap(AbstractMapVector mapVector,
TupleMetadata mapSchema, boolean inUnion) {
for (int i = 0; i < mapSchema.size(); i++) {
final ColumnMetadata childSchema = mapSchema.metadata(i);
// Check for union-compatible types. But, maps must be required.
if (inUnion && ! childSchema.isMap() && childSchema.mode() == DataMode.REQUIRED) {
throw new IllegalArgumentException("Map members in a list or union must not be non-nullable");
}
mapVector.putChild(childSchema.name(), buildVector(childSchema));
}
}
private ValueVector buildUnion(ColumnMetadata metadata) {
final ValueVector vector = TypeHelper.getNewVector(metadata.emptySchema(), allocator, null);
populateUnion((UnionVector) vector, metadata.variantSchema());
return vector;
}
private void populateUnion(UnionVector unionVector,
VariantMetadata variantSchema) {
for (final MinorType type : variantSchema.types()) {
final ValueVector childVector = unionVector.getMember(type);
switch (type) {
case LIST:
populateList((ListVector) childVector,
variantSchema.member(MinorType.LIST).variantSchema());
break;
case MAP:
// Force the map to require nullable or repeated types.
// Not perfect; does not extend down to maps within maps.
// Since this code is used in testing, not adding that complexity
// for now.
populateMap((AbstractMapVector) childVector,
variantSchema.member(MinorType.MAP).mapSchema(),
true);
break;
default:
// Nothing additional needed
}
}
}
private ValueVector builList(ColumnMetadata metadata) {
final ValueVector vector = TypeHelper.getNewVector(metadata.emptySchema(), allocator, null);
populateList((ListVector) vector, metadata.variantSchema());
return vector;
}
private void populateList(ListVector vector, VariantMetadata variantSchema) {
if (variantSchema.size() == 0) {
return;
} else if (variantSchema.size() == 1) {
final ColumnMetadata subtype = variantSchema.listSubtype();
final ValueVector childVector = buildVector(subtype);
vector.setChildVector(childVector);
} else {
populateUnion(vector.fullPromoteToUnion(), variantSchema);
}
}
}
| 36.637838 | 123 | 0.721009 |
d0f660576c221b36be3a0085758c3b51e1fbef23 | 2,397 | /**
* This class is generated by jOOQ
*/
package org.jooq.test.ase.generatedclasses.tables.records;
/**
* This class is generated by jOOQ.
*/
@java.lang.SuppressWarnings("all")
public class VLibraryRecord extends org.jooq.impl.TableRecordImpl<org.jooq.test.ase.generatedclasses.tables.records.VLibraryRecord> implements org.jooq.Record2<java.lang.String, java.lang.String> {
private static final long serialVersionUID = 1575894708;
/**
* The table column <code>dbo.v_library.author</code>
*/
public void setAuthor(java.lang.String value) {
setValue(org.jooq.test.ase.generatedclasses.tables.VLibrary.AUTHOR, value);
}
/**
* The table column <code>dbo.v_library.author</code>
*/
public java.lang.String getAuthor() {
return getValue(org.jooq.test.ase.generatedclasses.tables.VLibrary.AUTHOR);
}
/**
* The table column <code>dbo.v_library.title</code>
*/
public void setTitle(java.lang.String value) {
setValue(org.jooq.test.ase.generatedclasses.tables.VLibrary.TITLE, value);
}
/**
* The table column <code>dbo.v_library.title</code>
*/
public java.lang.String getTitle() {
return getValue(org.jooq.test.ase.generatedclasses.tables.VLibrary.TITLE);
}
/**
* Create a detached VLibraryRecord
*/
public VLibraryRecord() {
super(org.jooq.test.ase.generatedclasses.tables.VLibrary.V_LIBRARY);
}
// -------------------------------------------------------------------------
// Record2 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row2<java.lang.String, java.lang.String> fieldsRow() {
return org.jooq.impl.DSL.row(field1(), field2());
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row2<java.lang.String, java.lang.String> valuesRow() {
return org.jooq.impl.DSL.row(value1(), value2());
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field1() {
return org.jooq.test.ase.generatedclasses.tables.VLibrary.AUTHOR;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field2() {
return org.jooq.test.ase.generatedclasses.tables.VLibrary.TITLE;
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value1() {
return getAuthor();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value2() {
return getTitle();
}
}
| 23.732673 | 197 | 0.65582 |
c0b7ef4fe2ab993fb3d49ebe803cd733ae05fe95 | 5,357 | //Autogenerated
package com.vision4j.completion;
import com.google.protobuf.ByteString;
import com.vision4j.completion.grpc.CompletionInput;
import com.vision4j.utils.*;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import com.vision4j.completion.grpc.CompletionGrpc;
import com.vision4j.completion.grpc.Image;
import com.vision4j.completion.grpc.CompletedImage;
import javax.imageio.ImageIO;
public class GrpcCompletion implements Completion {
private final CompletionGrpc.CompletionBlockingStub completionStub;
public GrpcCompletion(ManagedChannel channel) {
this.completionStub = CompletionGrpc.newBlockingStub(channel);
}
public GrpcCompletion(String host, int port) {
this(ManagedChannelBuilder.forAddress(host, port).usePlaintext().build());
}
public GrpcCompletion() {
this("localhost", 50053);
}
@Override()
public CompletionResult complete(InputStream image, InputStream mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(InputStream image, File mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(InputStream image, byte[] mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), mask);
}
@Override()
public CompletionResult complete(InputStream image, URL mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(File image, InputStream mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(File image, File mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(File image, byte[] mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), mask);
}
@Override()
public CompletionResult complete(File image, URL mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(byte[] image, InputStream mask) throws IOException {
return this.complete(image, VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(byte[] image, File mask) throws IOException {
return this.complete(image, VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(byte[] image, byte[] mask) throws IOException {
Image serializedimage = this.prepareGrpcBytes(image);
Image serializedmask = this.prepareGrpcBytes(mask);
CompletionInput.Builder completionInputBuilder = CompletionInput.newBuilder();
completionInputBuilder.setImage(serializedimage);
completionInputBuilder.setMask(serializedmask);
CompletionInput completionInput = completionInputBuilder.build();
CompletedImage completedimage = completionStub.complete(completionInput);
return this.convert(completedimage);
}
@Override()
public CompletionResult complete(byte[] image, URL mask) throws IOException {
return this.complete(image, VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(URL image, InputStream mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(URL image, File mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
@Override()
public CompletionResult complete(URL image, byte[] mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), mask);
}
@Override()
public CompletionResult complete(URL image, URL mask) throws IOException {
return this.complete(VisionUtils.toByteArray(image), VisionUtils.toByteArray(mask));
}
private CompletionResult convert(CompletedImage completedimage) throws IOException {
byte[] result = completedimage.getResult().toByteArray();
BufferedImage resultImage = ImageIO.read(new ByteArrayInputStream(result));
return new CompletionResult(resultImage);
}
private Image prepareGrpcBytes(byte[] image) throws IOException {
SimpleImageInfo simpleImageInfo = new SimpleImageInfo(image);
ByteString imageData = ByteString.copyFrom(image);
Image.Builder imageBuilder = Image.newBuilder();
imageBuilder.setWidth(simpleImageInfo.getWidth());
imageBuilder.setHeight(simpleImageInfo.getHeight());
imageBuilder.setChannels(3);
imageBuilder.setImageData(imageData);
return imageBuilder.build();
}
}
| 37.725352 | 94 | 0.73474 |
444203be94474fc45d3391b959113a540af50bae | 9,503 | package acmi.l2.clientmod.l2pe;
import static acmi.l2.clientmod.io.UnrealPackage.ObjectFlag.HasStack;
import static acmi.l2.clientmod.io.UnrealPackage.ObjectFlag.Standalone;
import static acmi.l2.clientmod.unreal.UnrealSerializerFactory.IS_STRUCT;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import acmi.l2.clientmod.io.ObjectOutput;
import acmi.l2.clientmod.io.ObjectOutputStream;
import acmi.l2.clientmod.io.RandomAccess;
import acmi.l2.clientmod.io.RandomAccessFile;
import acmi.l2.clientmod.io.UnrealPackage;
import acmi.l2.clientmod.unreal.UnrealRuntimeContext;
import acmi.l2.clientmod.unreal.UnrealSerializerFactory;
import acmi.l2.clientmod.unreal.properties.L2Property;
import acmi.l2.clientmod.unreal.properties.PropertiesUtil;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
public class Util {
private Util() {
throw new RuntimeException();
}
public static final boolean SAVE_DEFAULTS = System.getProperty("L2pe.saveDefaults", "false").equalsIgnoreCase("true");
public static final boolean SHOW_STACKTRACE = System.getProperty("L2pe.showStackTrace", "false").equalsIgnoreCase("true");
public static void createClass(UnrealSerializerFactory serializer, UnrealPackage up, String objName, String objSuperClass, int flags, List<L2Property> properties) {
flags |= Standalone.getMask();
Stream.of(up.getPackageName(), "System")
.filter(s -> up.nameReference(s) < 0)
.forEach(up::addNameEntries);
if (up.objectReferenceByName("Core.Object", IS_STRUCT) == 0)
up.addImportEntries(Collections.singletonMap("Core.Object", "Core.Class"));
up.addExportEntry(
objName,
null,
objSuperClass,
new byte[0],
flags);
UnrealPackage.ExportEntry entry = up.getExportTable().get(up.getExportTable().size() - 1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutput<UnrealRuntimeContext> dataOutput = new ObjectOutputStream<>(baos, up.getFile().getCharset(), serializer, new UnrealRuntimeContext(entry, serializer));
dataOutput.writeCompactInt(up.objectReferenceByName(objSuperClass, IS_STRUCT));
dataOutput.writeCompactInt(0);
dataOutput.writeCompactInt(0);
dataOutput.writeCompactInt(0);
dataOutput.writeCompactInt(up.nameReference(entry.getObjectName().getName()));
dataOutput.writeCompactInt(0);
dataOutput.writeInt(-1);
dataOutput.writeInt(-1);
dataOutput.writeInt(0);
dataOutput.writeLong(0x0080000000000040L);
dataOutput.writeLong(-1L);
dataOutput.writeShort(-1);
dataOutput.writeInt(0);
dataOutput.writeInt(0x00000212);
dataOutput.writeBytes(new byte[16]);
dataOutput.writeCompactInt(2);
dataOutput.writeCompactInt(entry.getObjectReference());
dataOutput.writeInt(1);
dataOutput.writeInt(0);
dataOutput.writeCompactInt(entry.getObjectSuperClass().getObjectReference());
dataOutput.writeInt(1);
dataOutput.writeInt(0);
Set<String> packages = new HashSet<>(Arrays.asList("Core", "Engine", up.getPackageName()));
dataOutput.writeCompactInt(packages.size());
for (String packageName : packages)
dataOutput.writeCompactInt(up.nameReference(packageName));
dataOutput.writeCompactInt(up.objectReferenceByName("Core.Object", IS_STRUCT));
dataOutput.writeCompactInt(up.nameReference("System"));
dataOutput.writeCompactInt(0);
PropertiesUtil.writeProperties(dataOutput, properties);
entry.setObjectRawData(baos.toByteArray());
}
public static void createObject(UnrealSerializerFactory serializer, UnrealPackage up, String objName, String objClass, int flags, boolean hasStack, List<L2Property> properties) {
if (hasStack)
flags |= HasStack.getMask();
up.addExportEntry(
objName,
objClass,
null,
new byte[0],
flags);
UnrealPackage.ExportEntry entry = up.getExportTable().get(up.getExportTable().size() - 1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutput<UnrealRuntimeContext> dataOutput = new ObjectOutputStream<>(baos, up.getFile().getCharset(), serializer, new UnrealRuntimeContext(entry, serializer));
if (hasStack) {
int classRef = up.objectReferenceByName(objClass, IS_STRUCT);
if (classRef == 0) {
up.addImportEntries(Collections.singletonMap(objClass, "Core.Class"));
classRef = up.objectReferenceByName(objClass, IS_STRUCT);
}
dataOutput.writeCompactInt(classRef);
dataOutput.writeCompactInt(classRef);
dataOutput.writeLong(-1);
dataOutput.writeInt(0);
dataOutput.writeCompactInt(-1);
}
PropertiesUtil.writeProperties(dataOutput, properties);
entry.setObjectRawData(baos.toByteArray());
}
public static void createBackup() {
final MainWndController mainWnd = Controllers.getMainWndController();
if(!mainWnd.isBackupEnable() || !mainWnd.isPackageSelected()) {
return;
}
final RandomAccess ra = mainWnd.getUnrealPackage().getFile();
if (ra instanceof RandomAccessFile) {
final RandomAccessFile raf = (RandomAccessFile) ra;
final File source = new File(raf.getPath());
final String time = DateTimeFormatter.ofPattern("yyyy_MM_dd-HH_mm_ss").format(LocalDateTime.now());
String path = source.getPath();
path = path.substring(0, path.lastIndexOf(File.separatorChar));
final File backup = new File(path, source.getName() + "_" + time);
try {
Files.copy(source.toPath(), backup.toPath());
} catch(IOException e) {
showException("Failed to create backup", e);
}
}
}
public static File getPackageFile(UnrealPackage.Entry<?> entry) throws IOException {
final MainWndController mainWnd = Controllers.getMainWndController();
final File root = mainWnd.getInitialDirectory().getParentFile();
final String entryPath = entry.getObjectFullName();
final String packageName = entryPath.substring(0, entryPath.indexOf('.'));
return Files.walk(root.toPath())
.filter(p -> p.toFile().isFile())
.map(p -> p.toFile())
.filter(f -> f.getName().contains(".") && f.getName().substring(0, f.getName().lastIndexOf('.')).equalsIgnoreCase(packageName))
.findAny()
.orElseThrow(IOException::new);
}
public static void showException(String text, Throwable ex) {
Platform.runLater(() -> {
if (SHOW_STACKTRACE) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(null);
alert.setContentText(text);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String exceptionText = sw.toString();
Label label = new Label("Exception stacktrace:");
TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
alert.getDialogPane().setExpandableContent(expContent);
alert.showAndWait();
} else {
Throwable t = getTop(ex);
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(t.getClass().getSimpleName());
alert.setHeaderText(text);
alert.setContentText(t.getMessage());
alert.showAndWait();
}
});
}
private static Throwable getTop(Throwable t) {
while (t.getCause() != null)
t = t.getCause();
return t;
}
public static <T> void sort(ListView<T> list) {
Platform.runLater(() -> Collections.sort(list.getItems(), new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
return o1.toString().compareTo(o2.toString());
}
}));
}
public static <T> void selectItem(ComboBox<T> comboBox, T select) {
for(T item : comboBox.getItems()) {
if(!item.equals(select)) {
continue;
}
comboBox.getSelectionModel().select(item);
break;
}
}
}
| 39.595833 | 182 | 0.666526 |
503df38d5b48925c80c6aba9f8a1851820db443e | 6,167 | /*
* Copyright 2011-2013, by Vladimir Kostyukov and Contributors.
*
* This file is part of la4j project (http://la4j.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s): -
*
*/
package org.la4j.decomposition;
import org.junit.Test;
import org.la4j.LinearAlgebra;
public class QRDecompositorTest extends AbstractDecompositorTest {
@Override
public LinearAlgebra.DecompositorFactory decompositorFactory() {
return LinearAlgebra.QR;
}
@Test
public void testDecompose_1x1() {
double[][] input = new double[][]{
{15.0}
};
double[][][] output = new double[][][]{
{
{-1.0}
},
{
{-15.0}
}
};
performTest(input, output);
}
@Test
public void testDecompose_2x2() {
double[][] input = new double[][]{
{5.0, 10.0},
{70.0, 11.0}
};
double[][][] output = new double[][][]{
{
{-0.071, 0.997},
{-0.997, -0.071}
},
{
{-70.178, -11.685},
{0.0, 9.191}
}
};
performTest(input, output);
}
@Test
public void testDecompose_4x1() {
double[][] input = new double[][]{
{8.0},
{2.0},
{-10.0},
{54.0}
};
double[][][] output = new double[][][]{
{
{-0.144},
{-0.036},
{0.180},
{-0.972}
},
{
{-55.534}
}
};
performTest(input, output);
}
@Test
public void testDecompose_3x2() {
double[][] input = new double[][]{
{65.0, 4.0},
{9.0, 12.0},
{32.0, 42.0}
};
double[][][] output = new double[][][]{
{
{-0.890, 0.455},
{-0.123, -0.246},
{-0.438, -0.856}
},
{
{-73.007, -23.450},
{0.000, -37.069}
}
};
performTest(input, output);
}
@Test
public void testDecompose_3x3() {
double[][] input = new double[][]{
{-8.0, 0.0, 0.0},
{0.0, -4.0, -6.0},
{0.0, 0.0, -2.0}
};
double[][][] output = new double[][][]{
{
{-1.0, 0.0, 0.0},
{0.0, -1.0, 0.0},
{0.0, 0.0, -1.0}
},
{
{8.0, 0.0, 0.0},
{0.0, 4.0, 6.0},
{0.0, 0.0, 2.0}
}
};
performTest(input, output);
}
@Test
public void testDecompose_3x3_2() {
double[][] input = new double[][]{
{-2.0, 6.0, 14.0},
{-10.0, -9.0, 6.0},
{12.0, 16.0, 100.0}
};
double[][][] output = new double[][][]{
{
{-0.127, 0.920, 0.371},
{-0.635, 0.212, -0.743},
{0.762, 0.330, -0.557}
},
{
{15.748, 17.145, 70.612},
{0.0, 8.891, 47.167},
{0.0, 0.0, -54.966}
}
};
performTest(input, output);
}
@Test
public void testDecompose_4x3() {
double[][] input = new double[][]{
{51.0, 4.0, 19.0},
{7.0, 17.0, 77.0},
{5.0, 6.0, 7.0},
{100.0, 1.0, -10.0}
};
double[][][] output = new double[][][]{
{
{-0.453, -0.121, 0.364},
{-0.062, -0.928, 0.236},
{-0.044, -0.323, -0.887},
{-0.888, 0.143, -0.158}
},
{
{-112.583, -4.024, -4.823},
{0.0, -18.050, -77.428},
{0.0, 0.0, 20.509}
}
};
performTest(input, output);
}
@Test
public void testDecompose_5x5() {
double[][] input = new double[][]{
{14.0, 66.0, 11.0, 4.0, 61.0},
{10.0, 22.0, 54.0, -1.0, 1.0},
{-19.0, 26.0, 4.0, 44.0, 14.0},
{87.0, -1.0, 34.0, 29.0, -2.0},
{18.0, 43.0, 51.0, 39.0, 16.0}
};
double[][][] output = new double[][][]{
{
{-0.151, -0.754, -0.520, 0.358, 0.097},
{-0.108, -0.242, 0.739, 0.388, 0.483},
{0.205, -0.342, -0.001, -0.771, 0.496},
{-0.941, 0.173, -0.088, -0.211, 0.180},
{-0.195, -0.475, 0.419, -0.287, -0.692}
},
{
{-92.466, -14.459, -48.602, -26.334, -7.700},
{0.0, -84.599, -41.067, -31.363, -58.992},
{0.0, 0.0, 52.549, 10.907, -24.128},
{0.0, 0.0, 0.0, -50.189, 7.268},
{0.0, 0.0, 0.0, 0.0, 1.908}
}
};
performTest(input, output);
}
}
| 29.649038 | 75 | 0.349116 |
0e4a9bea8fced2a581500bee17ead2a58afa1537 | 770 | package org.springframework.cloud.kubernetes.it;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SimpleCoreApplication {
@GetMapping("/greeting")
public Greeting home() {
return new Greeting("Hello Spring Boot");
}
public static void main(String[] args) {
SpringApplication.run(SimpleCoreApplication.class, args);
}
public static class Greeting {
private final String message;
public Greeting(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
}
| 22 | 68 | 0.779221 |
9c2e9799e4c13d23c5697d2610a6899282f02d01 | 393 | package misc;
public class CheckNumberInString {
public static void main(String[] args) {
String str = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.";
Boolean flag = false;
for(int i = 0; i < str.length(); i++) {
flag = Character.isDigit(str.charAt(i));
if(flag) {
System.out.println(str + "\n ==> contains number"); break;
}
}
}
}
| 24.5625 | 95 | 0.643766 |
acf57cd00ef71377038da04b54a31db82cff1c63 | 5,081 | class _HEDyC5l {
}
class OAts_b {
public static void oh7zVcTVqfrd (String[] g9C4Im1IKj9V_) {
boolean[] Icy = !!-( new f0_X().zauOBQKBDbytD())[ !T().Axk];
boolean KNdsPkCEKwdiwU;
;
{
int[] qHyh;
-new tZ1()._jmpRzsai;
int GpdnXLjFAbsrGG;
while ( !yg().N) ;
{
;
}
return;
;
if ( new Jqb0ezU[ true.Ek8v7gyc9n()][ this[ new boolean[ new void[ CCJ().ty2rcCPz()].gwqHfdoH()].BejuJcSz()]]) return;
while ( null.ztD5umfyh) {
ukR bK251pghuii;
}
if ( true.K56WVujvc1H1()) 2962[ -( K()[ -false.l]).fLbFlAe1R()];
boolean[] Nd90SiwT;
}
void vyNIgnzQW = new u()[ Ux()[ -8713.yB3]];
boolean[] pFWp2QO4 = !wA.TY2bmfUCY3O3dT();
void[] IJi3vtJQ3tq;
boolean[][][][] k8 = --this[ !new Xpos1mkZP().CN7vz3dG];
while ( !-true[ ( !!!!!!!!JI7nz[ false.FmdO1LTd]).sveL]) return;
boolean pD7Rftza0G8jJ;
--new void[ !-!( true[ !!!false.wQN])[ false[ -this[ u8nX4d.t6m2HYCL()]]]].s58();
boolean[] HURNr;
iJ17jmP JQ = true[ kW4ShEfqO5().RP8hu()];
boolean[][] c7Y_9N9Us6rYlc;
{
void[] Wm6ZRsD;
void j5;
void[][][] JvRB7mgXAJa;
RRd15fnP4ttmat[][] yB;
}
void[][][] uB7Ufc_GZx8CaQ;
if ( new boolean[ BJJ().TUSE5Xzr][ !!new UUleZGURwyT4vR().sGj43IT]) if ( -86.MGpKB5D) return;
}
public int RJ;
public int zUhf7;
public UEoc ZHxDwi7QgtAGWc () {
while ( !!!-false[ -this[ !!---!false.K0J8H]]) return;
while ( !!false[ -null.lv]) while ( -46[ new GCV_h9Bu8TnBEq[ -!!!!null.So()][ -( !--( 87485.xSWp6VBTQ).ZlDPG5bRYA).Yt_Q4JiQ]]) while ( null[ -!new void[ true[ TxEhM().Mul()]].LXYatjjyjcM3]) ;
if ( -e0Eq1cSvduJwYz.ttFpHyE4NoxKK0) new boolean[ true.RqMwkWnRxhXD()].yJ;
int[] S6fTZ4PwVPct = -true.wCnfMFtWUDWSAk = !!88315.FA();
ENGtJ51Y2a0MpW c;
fGj a8N24FlnMMRSi;
void[][] h4 = -false.t7kqlGJ9yJ = this.shJ_OYur2;
void j6l = true.J0lHczs028daK();
!null.HaOq13Ro6;
boolean[] UrWXmWuQ_DrZ;
;
xkHJXsgod7 R;
boolean lEQ1qGut;
boolean[] vxUhz;
return new tPwkKBijw().FqG0vRZ4iSDx;
int _Cgk6O4wWndm;
false[ !( !new lfsw[ -this.pDgeBDCoGFc()][ !!!null.ibncs669A0Gl()]).X];
void[] YH = null[ XPnwevN().RMdld()];
boolean[][] e02iQDKrZ5;
}
public QbLoS7izKfp[][] wmRfU8lLO8yI () throws NrZJW1RV_ {
J7iOU VbODvTU;
if ( -( -!--!--656139631.y604YaLG9o())[ --false.WI()]) while ( -omhvOW7().Rk2h61N44) while ( !this[ this[ !!-!-LFgav().q2aD]]) if ( !!16.q8k5dL) while ( 9.gk8UjSkqmHztWo) while ( !new void[ null.AJuyOOGo()].Org()) if ( this[ false.b]) return;else while ( --this.RL6wB4O()) true.YA();
return !this.Kgk();
void[][][] dmSvwE = !--VYHLtpJWRMO[ this.pb()] = Kh6d7OW.Ld7OQsgYSy4rKq();
!false.NCPdSBkwo3jx5h;
{
if ( -!this.nCt65FQO0t) {
boolean[][][][][][][][][][][] GBNEUw;
}
;
return;
void[] Vyswu9zK3KRvLX;
int[][] MUDyyT93XKnOJe;
e9[ -!eoTCh4gnmpe.YN];
;
boolean[] M3GM948YEzwv;
;
int[] EwedoCNwm;
}
{
yNxQrLd1_Ay ut;
while ( -new xWoQH()[ true.jIfdMCt2r3Bg]) while ( !LeKdfm().Y0Dgzwd0q()) if ( !new int[ !( X0hic4F_nR.wdGen4())[ !-!2889475.qWW]][ false[ -false.TPIpCRimVmh]]) while ( 73.fRtBfLg6JMX5oc) while ( qKKk0rugY()[ 39.eeZtlCNgyDF()]) return;
;
}
}
public static void j9LUCE (String[] byQoAlsk) throws _5 {
while ( false.JjNPfxPYh8bE()) return;
int[] TS = CuXzexfO93Dg().xj() = JwHv5vAAo()[ SJZ2GVVgYK3()[ !( -!-!( --true[ false.Hoib]).ojd8sqekjZw())[ null.xWeOFnA6]]];
}
public void[][][] O4QjA3VX () throws GU9eAHzE {
{
l6_NZ[ -null[ !!!!new void[ 980147520.ofg6UOGSRfCW].d6Jl]];
boolean WhVkOFZZ;
;
void[][] K2Evrx;
if ( -!939.h1oGn2jBAcGjaW) ;
int[][] Ut;
boolean lJbVIDp2Bvp;
while ( pFG7RIw34R().HQug) while ( !-null.H2mayigHdyk()) ;
while ( new boolean[ -!M6veYUV().kLafJLmf].uI5YOeGd1QD) ;
;
{
void[][][][][] qIu;
}
int LROltWphpJ0;
}
while ( eYmOvTfILoAO().BtONvPkJT7O9V()) !-new boolean[ HTEUy.SJpzrCTfPbr].B7phCoF3();
null.OH1;
Tp2ROF2wdyx OX9;
{
e7sJVU6zh2 rO;
int[][][] HbE9jIYbn;
{
XU1ifnmxQx C;
}
}
}
public static void jJ (String[] Ojn3c4XCp) {
boolean qAW1YIe9HjZ6R4 = new boolean[ dP0oTp7Bh_IMCI().ZDYGjgKx6ezAg9()].AzF = this.i8gclmluEbbyW5;
}
public boolean[][] NCEu1;
}
class WWr_op {
}
| 37.360294 | 292 | 0.505609 |
2bf1e9daff84b1b5a255b7676fd2bb6dab00e909 | 6,013 | package work.innov8.todoplus.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
import work.innov8.todoplus.model.User;
/**
* Created by yogesh on 14/3/17.
*/
public class LoginDBHelper extends SQLiteOpenHelper {
// Database Information
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "login.db";
private static LoginDBHelper loginDBHelper;
public static final String SQL_CREATE_TABLE_ENTRIES =
"CREATE TABLE " + LoginContract.LoginEntry.TABLE_NAME + " (" +
LoginContract.LoginEntry._ID + " INTEGER PRIMARY KEY," +
LoginContract.LoginEntry.COLUMN_NAME_EMAIL + " TEXT," +
LoginContract.LoginEntry.COLUMN_NAME_PASSWORD + " TEXT" +
" );";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + LoginContract.LoginEntry.TABLE_NAME;
public LoginDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static LoginDBHelper getLoginDBHelperInstance(Context context) {
if (loginDBHelper == null) {
loginDBHelper = new LoginDBHelper(context);
}
return loginDBHelper;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_TABLE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
onCreate(sqLiteDatabase);
}
public long insert(User user) {
SQLiteDatabase db = this.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues contentValues = new ContentValues();
contentValues.put(LoginContract.LoginEntry.COLUMN_NAME_EMAIL, user.getEmail());
contentValues.put(LoginContract.LoginEntry.COLUMN_NAME_PASSWORD, user.getPassword());
// Insert the new row, returning the primary key value of the new row
long id = db.insert(LoginContract.LoginEntry.TABLE_NAME, null, contentValues);
return id;
}
public int delete(String email) {
SQLiteDatabase db = this.getWritableDatabase();
// Define 'where' part of query.
String selection = LoginContract.LoginEntry.COLUMN_NAME_EMAIL + " = ?";
// Specify arguments in placeholder order.
String[] selectionArgs = {String.valueOf(email)};
// Issue SQL statement.
return db.delete(LoginContract.LoginEntry.TABLE_NAME, selection, selectionArgs);
}
public List<User> getAllUser() {
List<User> userList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] fields = {
LoginContract.LoginEntry._ID,
LoginContract.LoginEntry.COLUMN_NAME_EMAIL,
LoginContract.LoginEntry.COLUMN_NAME_PASSWORD,
};
Cursor cursor = db.query(
LoginContract.LoginEntry.TABLE_NAME, // The table to query
fields, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
TaskContract.TaskEntry._ID + " ASC" // The sort order
);
while (cursor.moveToNext()) {
int id = cursor.getColumnIndex(LoginContract.LoginEntry._ID);
int emailIndex = cursor.getColumnIndex(LoginContract.LoginEntry.COLUMN_NAME_EMAIL);
int passwordIndex = cursor.getColumnIndex(LoginContract.LoginEntry.COLUMN_NAME_PASSWORD);
String email = cursor.getString(emailIndex);
String password = cursor.getString(passwordIndex);
User user = new User(id, email, password);
userList.add(user);
}
return userList;
}
public String getPasswordEntry(String email) {
SQLiteDatabase db = this.getWritableDatabase();
String[] selectionArgs = {String.valueOf(email)};
Cursor cursor = db.query(
LoginContract.LoginEntry.TABLE_NAME,
null,
LoginContract.LoginEntry.COLUMN_NAME_EMAIL + "=?",
new String[]{email},
null,
null,
LoginContract.LoginEntry._ID);
if (cursor.getCount() < 1) // Email doesn't Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex(LoginContract.LoginEntry.COLUMN_NAME_PASSWORD));
cursor.close();
return password;
}
public void update(User user) {
SQLiteDatabase db = this.getWritableDatabase();
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put(LoginContract.LoginEntry.COLUMN_NAME_EMAIL, user.getEmail());
updatedValues.put(LoginContract.LoginEntry.COLUMN_NAME_PASSWORD, user.getPassword());
// Which row to update, based on the ID
String selection = LoginContract.LoginEntry.COLUMN_NAME_EMAIL + " = ?";
String[] selectionArgs = {String.valueOf(user.getEmail())};
db.update(LoginContract.LoginEntry.TABLE_NAME, updatedValues, selection, selectionArgs);
}
}
| 40.086667 | 113 | 0.617495 |
095be6664c869c78b30e2051f9a1ec2046d37f8a | 5,774 | package gg.fel.cvut.cz.data.updatable;
import bwta.BWTA;
import com.google.common.collect.ImmutableSet;
import gg.fel.cvut.cz.counters.BWReplayCounter;
import gg.fel.cvut.cz.data.AContainer;
import gg.fel.cvut.cz.data.IUpdatableContainer;
import gg.fel.cvut.cz.data.readonly.Game;
import gg.fel.cvut.cz.enums.GameTypeEnum;
import gg.fel.cvut.cz.facades.managers.UpdateManager;
import gg.fel.cvut.cz.facades.strategies.UpdateStrategy;
import gg.fel.cvut.cz.wrappers.WBaseLocation;
import gg.fel.cvut.cz.wrappers.WChokePoint;
import gg.fel.cvut.cz.wrappers.WGame;
import gg.fel.cvut.cz.wrappers.WPlayer;
import gg.fel.cvut.cz.wrappers.WRegion;
import gg.fel.cvut.cz.wrappers.WTilePosition;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
//TODO implement creator
public class UpdatableGame extends Game implements
IUpdatableContainer<WGame, Game> {
private final transient WGame wrapped;
public UpdatableGame(BWReplayCounter bwCounter, WGame wrapped) {
super(bwCounter);
this.wrapped = wrapped;
}
@Override
public WGame getWrappedSCInstance() {
return wrapped;
}
@Override
public void update(UpdateManager internalUpdaterFacade, int currentFrame) {
try {
lock.writeLock().lock();
//updates
if (players.propertyHasNotBeenAdded()) {
players.addProperty(ImmutableSet.copyOf(wrapped.getScInstance().getPlayers().stream()
.map(WPlayer::getOrCreateWrapper)
.map(internalUpdaterFacade::getDataContainer)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet())), 0);
}
if (gameType.propertyHasNotBeenAdded()) {
this.gameType
.addProperty(GameTypeEnum.Unknown.getOurType(wrapped.getScInstance().getGameType()), 0);
}
frameCount.addProperty(wrapped.getScInstance().getFrameCount(), currentFrame);
FPS.addProperty(wrapped.getScInstance().getFPS(), currentFrame);
averageFPS.addProperty(wrapped.getScInstance().getAverageFPS(), currentFrame);
elapsedTime.addProperty(wrapped.getScInstance().elapsedTime(), currentFrame);
if (regions.propertyHasNotBeenAdded()) {
regions.addProperty(ImmutableSet.copyOf(BWTA.getRegions().stream()
.map(WRegion::getOrCreateWrapper)
.map(internalUpdaterFacade::getDataContainer)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet())), 0);
}
if (chokePoints.propertyHasNotBeenAdded()) {
chokePoints.addProperty(ImmutableSet.copyOf(BWTA.getChokepoints().stream()
.map(WChokePoint::getOrCreateWrapper)
.map(internalUpdaterFacade::getDataContainer)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet())), 0);
}
if (baseLocations.propertyHasNotBeenAdded()) {
baseLocations.addProperty(ImmutableSet.copyOf(BWTA.getBaseLocations().stream()
.map(WBaseLocation::getOrCreateWrapper)
.map(internalUpdaterFacade::getDataContainer)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet())), 0);
}
if (startLocations.propertyHasNotBeenAdded()) {
startLocations.addProperty(ImmutableSet.copyOf(BWTA.getStartLocations().stream()
.map(WBaseLocation::getOrCreateWrapper)
.map(internalUpdaterFacade::getDataContainer)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet())), 0);
}
if (mapWidth.propertyHasNotBeenAdded()) {
mapWidth.addProperty(wrapped.getScInstance().mapWidth(), 0);
}
if (mapHeight.propertyHasNotBeenAdded()) {
mapHeight.addProperty(wrapped.getScInstance().mapHeight(), 0);
}
if (mapName.propertyHasNotBeenAdded()) {
mapName.addProperty(wrapped.getScInstance().mapName(), 0);
}
if (grid.propertyHasNotBeenAdded()) {
grid.addProperty(ImmutableSet.copyOf(
IntStream.range(0, wrapped.getScInstance().mapWidth()).boxed()
.flatMap(i -> IntStream.range(0, wrapped.getScInstance().mapHeight())
.boxed().map(j -> new bwapi.TilePosition(i, j)))
.filter(bwapi.TilePosition::isValid)
.map(WTilePosition::getOrCreateWrapper)
.map(internalUpdaterFacade::getDataContainer)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet())), 0);
}
//updated in frame
updatedInFrame = currentFrame;
} finally {
lock.writeLock().unlock();
}
}
@Override
public UpdatableGame getContainer() {
return this;
}
@Override
public Stream<? extends AContainer> getReferencedContainers(int currentFrame) {
return Stream.of(players.getValueInFrame(currentFrame),
regions.getValueInFrame(currentFrame),
chokePoints.getValueInFrame(currentFrame),
baseLocations.getValueInFrame(currentFrame),
startLocations.getValueInFrame(currentFrame),
grid.getValueInFrame(currentFrame))
.filter(Optional::isPresent)
.map(Optional::get)
.flatMap(Collection::stream);
}
@Override
public void update(UpdateManager updateManager, UpdateStrategy updateStrategy) {
updateManager.update(this, updateStrategy);
}
@Override
public boolean shouldBeUpdated(UpdateStrategy updateStrategy, int depth, int currentFrame) {
return updateStrategy.shouldBeUpdated(this, deltaOfUpdate(currentFrame), depth);
}
}
| 38.238411 | 100 | 0.682369 |
b093c0c7cf7c09fb290e2214b0a8245caa00016c | 6,372 | /*
* 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.servicecomb.serviceregistry.client;
import java.util.List;
import java.util.Map;
import org.apache.servicecomb.foundation.vertx.AsyncResultCallback;
import org.apache.servicecomb.serviceregistry.api.registry.Microservice;
import org.apache.servicecomb.serviceregistry.api.registry.MicroserviceInstance;
import org.apache.servicecomb.serviceregistry.api.registry.MicroserviceInstanceStatus;
import org.apache.servicecomb.serviceregistry.api.registry.ServiceCenterInfo;
import org.apache.servicecomb.serviceregistry.api.response.GetSchemaResponse;
import org.apache.servicecomb.serviceregistry.api.response.HeartbeatResponse;
import org.apache.servicecomb.serviceregistry.api.response.MicroserviceInstanceChangedEvent;
import org.apache.servicecomb.serviceregistry.client.http.Holder;
import org.apache.servicecomb.serviceregistry.client.http.MicroserviceInstances;
public interface ServiceRegistryClient {
void init();
/**
* get all microservices
*/
List<Microservice> getAllMicroservices();
/**
*
* 获取微服务唯一标识
*/
String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment);
/**
*
* 注册微服务静态信息
*/
String registerMicroservice(Microservice microservice);
/**
*
* 根据微服务唯一标识查询微服务静态信息
*/
Microservice getMicroservice(String microserviceId);
/**
* <p>
* if connect to normal ServiceCenter, same with the method
* {@linkplain org.apache.servicecomb.serviceregistry.client.ServiceRegistryClient#getMicroservice(String)}
* if connect to ServiceCenter Aggregator, not only contain the target ServiceCenter but also other ServiceCenter clusters
* </p>
*/
Microservice getAggregatedMicroservice(String microserviceId);
/**
* 更新微服务properties
*/
boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties);
/**
*
* 判定schema是否已经注册
*/
boolean isSchemaExist(String microserviceId, String schemaId);
/**
*
* 注册schema
*/
boolean registerSchema(String microserviceId, String schemaId, String schemaContent);
/**
*
* 获取schema内容
*/
String getSchema(String microserviceId, String schemaId);
/**
* <p>
* if connect to normal ServiceCenter, same with the method
* {@linkplain org.apache.servicecomb.serviceregistry.client.ServiceRegistryClient#getSchema(String, String)}
* if connect to ServiceCenter Aggregator, not only contain the target ServiceCenter but also other ServiceCenter clusters
* </p>
*/
String getAggregatedSchema(String microserviceId, String schemaId);
/**
*
* 批量获取schemas内容
*/
Holder<List<GetSchemaResponse>> getSchemas(String microserviceId);
/**
*
* 注册微服务实例
*/
String registerMicroserviceInstance(MicroserviceInstance instance);
/**
*
* 根据多个微服务唯一标识查询所有微服务实例信息
*/
List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId);
/**
* 更新微服务实例properties
*/
boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties);
/**
*
* 去注册微服务实例
*/
boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId);
/**
*
* 服务端返回失败,表示需要重新注册,重新watch
*/
HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId);
/**
*
* watch实例变化
*/
void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback);
/**
*
* watch实例变化
*/
void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose);
/**
*
* 按照app+interface+version查询实例endpoints信息
*/
List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule);
/**
*
* 按照app+interface+version+revision查询实例endpoints信息
*/
MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision);
/**
* 通过serviceId, instanceId 获取instance对象。
* @param serviceId
* @param instanceId
* @return MicroserviceInstance
*/
MicroserviceInstance findServiceInstance(String serviceId, String instanceId);
/**
* get ServiceCenterVersionInfo
*/
ServiceCenterInfo getServiceCenterInfo();
/**
* 修改微服务实例状态
* @param microserviceId
* @param microserviceInstanceId
* @return
* @deprecated use {@link #updateMicroserviceInstanceStatus(String, String, MicroserviceInstanceStatus)} instead
*/
@Deprecated
default boolean undateMicroserviceInstanceStatus(String microserviceId, String microserviceInstanceId,
String status) {
MicroserviceInstanceStatus instanceStatus;
try {
instanceStatus = MicroserviceInstanceStatus.valueOf(status);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid status: " + status);
}
return updateMicroserviceInstanceStatus(microserviceId, microserviceInstanceId, instanceStatus);
}
/**
* Update the instance status registered in service center.
* @param microserviceId the microserviceId of the instance
* @param instanceId the instanceId of the instance
* @param status update to this status
* @return whether this operation success
*/
boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status);
}
| 30.932039 | 127 | 0.753923 |
b883e8f6f2d0ca7d5130beb56a203f5ebb3acc07 | 12,370 | package com.chaschev.microbe.samples;
//import gnu.trove.list.array.TIntArrayList;
//import gnu.trove.map.hash.TIntIntHashMap;
import com.chaschev.microbe.*;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TIntIntHashMap;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* User: Admin
* Date: 19.11.11
*/
public class MemConsumptionTest {
public static final Logger logger = LoggerFactory.getLogger(MemConsumptionTest.class);
public static void main(String[] args) {
MemConsumptionTest mem = new MemConsumptionTest();
mem.arrayListVsLinkedList();
// mem.testStringMemoryConsumption();
// mem.testObjectMemoryConsumption();
// mem.testByteMemoryConsumption();
// mem.test20ByteMemoryConsumption();
// mem.test20byteMemoryConsumption();
// mem.testMapsMemoryConsumption();
// mem.testByteArrayMemoryConsumption();
// mem.testDoubleMemoryConsumption();
// mem.testStringsMemoryConsumption();
}
public void testStringMemoryConsumption() {
final int numberOfTrials = 25;
new Microbe(numberOfTrials, "testStringMemoryConsumption", new TrialFactory() {
@Override
public Microbe.Trial create(final int trialIndex) {
return new AbstractTrial() {
int n = 5000;
String[] holder = new String[n];
int lFrom = 1500;
int lTo = 2000;
Random random = new Random(1);
long totalLength = 0;
int currentTo = (lTo - lFrom) * trialIndex / numberOfTrials + lFrom + 1;
public Measurements run(int index) {
for (int i = 0; i < n; i++) {
holder[i] = RandomStringUtils.random(random.nextInt(currentTo - lFrom) + lFrom);
totalLength += holder[i].length();
}
return new MeasurementsImpl();
}
public void addResultsAfterCompletion(Measurements result) {
result.addCoordinates(new float[]{(float) result.getMemory() / totalLength}, new String[]{"bytes per char"});
}
};
}
}).runTrials();
}
//16
public void testObjectMemoryConsumption() {
new Microbe(50, "testObjectMemoryConsumption",
new MemConsumptionTrialFactory<Object>(
new ObjectFactory<Object>() {
@Override
public Object create(int trialIndex) {
return new Object();
}
},
Object.class, 500000)
).runTrials();
}
//16
public void testByteMemoryConsumption() {
new Microbe(50, "testByteMemoryConsumption",
new MemConsumptionTrialFactory<Byte>(
new ObjectFactory<Byte>() {
@Override
public Byte create(int trialIndex) {
return new Byte((byte) trialIndex);
}
},
Byte.class, 500000)
).runTrials();
}
static class ByteFields20 {
Byte b00 = new Byte((byte) 1);
Byte b01 = new Byte((byte) 1);
Byte b02 = new Byte((byte) 1);
Byte b03 = new Byte((byte) 1);
Byte b04 = new Byte((byte) 1);
Byte b05 = new Byte((byte) 1);
Byte b06 = new Byte((byte) 1);
Byte b07 = new Byte((byte) 1);
Byte b08 = new Byte((byte) 1);
Byte b09 = new Byte((byte) 1);
Byte b10 = new Byte((byte) 1);
Byte b11 = new Byte((byte) 1);
Byte b12 = new Byte((byte) 1);
Byte b13 = new Byte((byte) 1);
Byte b14 = new Byte((byte) 1);
Byte b15 = new Byte((byte) 1);
Byte b16 = new Byte((byte) 1);
Byte b17 = new Byte((byte) 1);
Byte b18 = new Byte((byte) 1);
Byte b19 = new Byte((byte) 1);
}
static class ByteFields20_2 {
byte b00 = 1;
byte b01 = 2;
byte b02 = 3;
byte b03 = 4;
byte b04 = 5;
byte b05 = 6;
byte b06 = 7;
byte b07 = 8;
byte b08 = 9;
byte b09 = 1;
byte b10 = 2;
byte b11 = 3;
byte b12 = 4;
byte b13 = 5;
byte b14 = 6;
byte b15 = 7;
byte b16 = 8;
byte b17 = 9;
byte b18 = 0;
byte b19 = 1;
}
@Test
public void test(){
}
//408 bytes = 8 + 20 fields * (16 + 4 bytes)
public void test20ByteMemoryConsumption() {
new Microbe(50, "test20ByteMemoryConsumption",
new MemConsumptionTrialFactory<ByteFields20>(
new ObjectFactory<ByteFields20>() {
@Override
public ByteFields20 create(int trialIndex) {
return new ByteFields20();
}
},
ByteFields20.class, 50000)
).runTrials();
}
//28 bytes = 8 + 20 fields * 1 byte
public void test20byteMemoryConsumption() {
new Microbe(50, "test20byteMemoryConsumption",
new MemConsumptionTrialFactory<ByteFields20_2>(
new ObjectFactory<ByteFields20_2>() {
@Override
public ByteFields20_2 create(int trialIndex) {
return new ByteFields20_2();
}
},
ByteFields20_2.class, 50000)
).runTrials();
}
public void arrayListVsLinkedList() {
final int listSize = 20000;
//2003K, 25.4s
new Microbe(20,"linkedList",
new MemConsumptionTrialFactory<List>(
new ObjectFactory<List>() {
@Override
public List create(int trialIndex) {
List<Integer> integers = new LinkedList<Integer>();
for (int i = trialIndex; i < trialIndex + listSize; i++) {
integers.add(i * i + trialIndex);
}
return integers;
}
@Override
public boolean isGranular() {
return true;
}
@Override
public int granularity(int trialIndex) {
return listSize;
}
},
List.class, 50)
).runTrials();
//1085K, 24.5s
new Microbe(20,"arrayList",
new MemConsumptionTrialFactory<List>(
new ObjectFactory<List>() {
@Override
public List create(int trialIndex) {
List<Integer> integers = new ArrayList<Integer>(listSize);
for (int i = trialIndex; i < trialIndex + listSize; i++) {
integers.add(i * i + trialIndex);
}
return integers;
}
@Override
public boolean isGranular() {
return true;
}
@Override
public int granularity(int trialIndex) {
return listSize;
}
},
List.class, 50)
)
.runTrials();
System.gc();
//327K, 15.3s
new Microbe(20, "TIntArrayList",
new MemConsumptionTrialFactory<TIntArrayList>(
new ObjectFactory<TIntArrayList>() {
@Override
public TIntArrayList create(int trialIndex) {
TIntArrayList integers = new TIntArrayList(listSize);
for (int i = trialIndex; i < trialIndex + listSize; i++) {
integers.add(i * i + trialIndex);
}
return integers;
}
@Override
public boolean isGranular() {
return true;
}
@Override
public int granularity(int trialIndex) {
return listSize;
}
},
TIntArrayList.class, 50)
).runTrials();
}
public void testMapsMemoryConsumption() {
//231561 = 9000 * (8 + 21)
new Microbe(50, "TIntIntHashMap",
new MemConsumptionTrialFactory<TIntIntHashMap>(
new ObjectFactory<TIntIntHashMap>() {
@Override
public TIntIntHashMap create(int trialIndex) {
TIntIntHashMap map = new TIntIntHashMap();
for (int i = trialIndex; i < trialIndex + 9000; i++) {
map.put(i, i * i + trialIndex);
}
return map;
}
},
TIntIntHashMap.class, 50)
).runTrials();
//567338
new Microbe(50, "HashMap<Integer, Integer>",
new MemConsumptionTrialFactory<Map>(
new ObjectFactory<Map>() {
@Override
public Map<Integer, Integer> create(int trialIndex) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = trialIndex; i < trialIndex + 9000; i++) {
map.put(i, i * i + trialIndex);
}
return map;
}
},
Map.class, 50)
).runTrials();
}
//1036 = 1024 + 8
public void testByteArrayMemoryConsumption() {
new Microbe(50, "testByteArrayMemoryConsumption",
new MemConsumptionTrialFactory<byte[]>(
new ObjectFactory<byte[]>() {
@Override
public byte[] create(int trialIndex) {
return new byte[1024];
}
},
byte[].class, 50000)
).runTrials();
}
public void testDoubleMemoryConsumption() {
//16
new Microbe(50, "testDoubleMemoryConsumption",
new MemConsumptionTrialFactory<Double>(
new ObjectFactory<Double>() {
@Override
public Double create(int trialIndex) {
return new Double(trialIndex);
}
},
Double.class, 200000)
).runTrials();
}
public void testStringsMemoryConsumption() {
int[] lengths = new int[]{0, 1, 6, 10, 20, 50, 100, 2000};
for (final int length : lengths) {
System.out.println("string[" + length + "]");
new Microbe(20, "testStringsMemoryConsumption",
new MemConsumptionTrialFactory<String>(
new ObjectFactory<String>() {
@Override
public String create(int trialIndex) {
return RandomStringUtils.random(length, true, false);
}
},
String.class, 2000000 / (length + 1)
)
).runTrials();
}
//16
}
}
| 33.523035 | 133 | 0.448181 |
5cd8b982c8bcbac10eaf7dbaef92ad8572c7edc3 | 293 | package org.hzz.annotas;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@MyParent
public @interface MyBefore {
}
| 22.538462 | 44 | 0.825939 |
2168d325f5621279461dc79ed994f102eaeed267 | 1,098 | package com.bazaarvoice.emodb.auth;
import org.apache.shiro.authz.Permission;
/**
* Interface for performing authorization internally within the system. Unlike SecurityManager this interface is
* intended to be used primarily in contexts where the user is not authenticated. The interface is intentionally
* limited to discourage bypassing the SecurityManager when dealing with authenticated users.
*
* Internal systems are encouraged to identify relationships such as resource ownership with IDs instead of
* secret credentials like API keys for the following reasons:
*
* <ul>
* <li>If the API key for a user is changed the ID remains constant.</li>
* <li>They can safely log and store the ID of a user without risk of leaking plaintext credentials.</li>
* </ul>
*/
public interface InternalAuthorizer {
boolean hasPermissionById(String id, String permission);
boolean hasPermissionById(String id, Permission permission);
boolean hasPermissionsById(String id, String... permissions);
boolean hasPermissionsById(String id, Permission... permissions);
}
| 39.214286 | 113 | 0.769581 |
42d458000b6cdf30dd9b1a140f5e278eb2f00a26 | 1,392 | /**
* File generated by the ThingML IDE
* /!\Do not edit this file/!\
* In case of a bug in the generated code,
* please submit an issue on our GitHub
**/
package org.thingml.generated.messages;
import no.sintef.jasm.*;
import no.sintef.jasm.ext.*;
import java.util.*;
import java.nio.*;
public class DrawRect_bisyheightMessageType extends EventType {
public DrawRect_bisyheightMessageType(short code) {super("drawRect_bisyheight", code);
}
public DrawRect_bisyheightMessageType() {
super("drawRect_bisyheight", (short) 5);
}
public Event instantiate(final byte var17, final int y, final int height) { return new DrawRect_bisyheightMessage(this, var17, y, height); }
public Event instantiate(Map<String, Object> params) {return instantiate((Byte) params.get("var17"), (Integer) params.get("y"), (Integer) params.get("height"));
}
public class DrawRect_bisyheightMessage extends Event implements java.io.Serializable {
public final byte var17;
public final int y;
public final int height;
public String toString(){
return "drawRect_bisyheight (" + "var17: " + var17 + ", " + "y: " + y + ", " + "height: " + height + ")";
}
protected DrawRect_bisyheightMessage(EventType type, final byte var17, final int y, final int height) {
super(type);
this.var17 = var17;
this.y = y;
this.height = height;
}
public Event clone() {
return instantiate(this.var17, this.y, this.height);
}}
}
| 28.408163 | 160 | 0.729885 |
bbaf602604cd5bc273c413d37a7f48fbb99dc5cf | 878 | package com.codeborne.selenide.conditions;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.Driver;
import org.openqa.selenium.WebElement;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public class Not extends Condition {
private final Condition condition;
public Not(Condition originalCondition, boolean absentElementMatchesCondition) {
super("not " + originalCondition.getName(), absentElementMatchesCondition);
this.condition = originalCondition;
}
@Override
public boolean apply(Driver driver, WebElement element) {
return !condition.apply(driver, element);
}
@Override
public String actualValue(Driver driver, WebElement element) {
return condition.actualValue(driver, element);
}
@Override
public String toString() {
return "not " + condition.toString();
}
}
| 26.606061 | 82 | 0.773349 |
6b45703855da6b01aff3ef00127e2b9ba41b1088 | 2,758 | package com.pandaq.rxpanda.requests.okhttp.io;
import static com.pandaq.rxpanda.log.HttpLoggingInterceptor.IO_FLAG_HEADER;
import android.text.TextUtils;
import com.pandaq.rxpanda.api.Api;
import com.pandaq.rxpanda.callbacks.TransmitCallback;
import com.pandaq.rxpanda.requests.Request;
import com.pandaq.rxpanda.utils.CastUtils;
import java.util.LinkedHashMap;
import java.util.Map;
import io.reactivex.rxjava3.annotations.NonNull;
/**
* Created by huxinyu on 2019/7/11.
* Email : [email protected]
* Description :
*/
public abstract class IORequest<R extends IORequest<R>> extends Request<R> {
// http api,兼容 rxJava 观察者模式,需要返回观察对象时,将请求转换成 Retrofit 去请求
protected Api mApi;
protected String url = "";
// request tag
protected Object tag;
protected Map<String, String> localParams = new LinkedHashMap<>();//请求参数
/**
* set request‘s tag,use to manage the request
*
* @param tag request's tag
* @return Request Object
*/
public R tag(@NonNull Object tag) {
this.tag = tag;
return CastUtils.cast(this);
}
public IORequest(String url) {
if (!TextUtils.isEmpty(url)) {
this.url = url;
}
clientBuilder = null;
addHeader(IO_FLAG_HEADER, "IORequest ignore print log !!!");
}
protected abstract <T extends TransmitCallback> void execute(T callback);
/**
* 添加请求参数
*
* @param paramKey
* @param paramValue
* @return
*/
public R addParam(String paramKey, String paramValue) {
if (paramKey != null && paramValue != null) {
this.localParams.put(paramKey, paramValue);
}
return CastUtils.cast(this);
}
/**
* 添加请求参数
*
* @param params
* @return
*/
public R addParams(Map<String, String> params) {
if (params != null) {
this.localParams.putAll(params);
}
return CastUtils.cast(this);
}
/**
* 移除请求参数
*
* @param paramKey
* @return
*/
public R removeParam(String paramKey) {
if (paramKey != null) {
this.localParams.remove(paramKey);
}
return CastUtils.cast(this);
}
/**
* 设置请求参数
*
* @param params
* @return
*/
public R params(Map<String, String> params) {
if (params != null) {
this.localParams = params;
}
return CastUtils.cast(this);
}
@Override
protected void injectLocalParams() {
super.injectLocalParams();
if (getGlobalConfig().getGlobalParams() != null) {
localParams.putAll(getGlobalConfig().getGlobalParams());
}
mApi = getCommonRetrofit().create(Api.class);
}
}
| 23.982609 | 77 | 0.604061 |
d48acc11d0b9aa2f54d33c1439ade37ee928ab1e | 2,704 | package com.github.dantin.cubic.protocol.room;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.util.ArrayList;
import java.util.List;
@JsonDeserialize(builder = Route.Builder.class)
public class Route {
private static final String ID_FIELD = "id";
private static final String ROOM_FIELD = "room";
private static final String STREAMS_FIELD = "streams";
private final String id;
private final String name;
private final List<Stream> streams;
private Route(Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.streams = builder.streams;
}
public static Builder builder() {
return new Builder();
}
@JsonGetter(ID_FIELD)
public String getId() {
return id;
}
@JsonGetter(ROOM_FIELD)
public String getName() {
return name;
}
@JsonGetter(STREAMS_FIELD)
public List<Stream> getStreams() {
return streams;
}
@JsonPOJOBuilder(buildMethodName = "build", withPrefix = "")
public static final class Builder implements com.github.dantin.cubic.base.Builder<Route> {
private String id;
private String name;
private List<Stream> streams;
Builder() {
this.streams = new ArrayList<>();
}
@JsonSetter(ID_FIELD)
public Builder id(String id) {
this.id = id;
return this;
}
@JsonSetter(ROOM_FIELD)
public Builder name(String name) {
this.name = name;
return this;
}
@JsonSetter(STREAMS_FIELD)
public Builder streams(List<Stream> streams) {
this.streams = streams;
return this;
}
public Builder addStream(Stream stream) {
if (!java.util.Objects.isNull(stream)) {
this.streams.add(stream);
}
return this;
}
@Override
public Route build() {
return new Route(this);
}
}
@Override
public int hashCode() {
return Objects.hashCode(id, name, streams);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Route)) {
return false;
}
Route o = (Route) obj;
return Objects.equal(id, o.id)
&& Objects.equal(name, o.name)
&& Objects.equal(streams, o.streams);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("id", id)
.add("name", name)
.add("stream", streams)
.toString();
}
}
| 22.915254 | 92 | 0.659393 |
f787a652002a7b1cba9e85c3cc468612d3f5cc99 | 1,766 | /*
* Copyright 2006-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.osgi.web.deployer;
import org.springframework.osgi.OsgiException;
/**
* Exception thrown when the deployment or undeployment process of an OSGi war
* fails.
*
* @author Costin Leau
*/
public class OsgiWarDeploymentException extends OsgiException {
private static final long serialVersionUID = 1888946061050974077L;
/**
* Constructs a new <code>OsgiWarDeploymentException</code> instance.
*
*/
public OsgiWarDeploymentException() {
super();
}
/**
* Constructs a new <code>OsgiWarDeploymentException</code> instance.
*
* @param message
* @param cause
*/
public OsgiWarDeploymentException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new <code>OsgiWarDeploymentException</code> instance.
*
* @param message
*/
public OsgiWarDeploymentException(String message) {
super(message);
}
/**
* Constructs a new <code>OsgiWarDeploymentException</code> instance.
*
* @param cause
*/
public OsgiWarDeploymentException(Throwable cause) {
super(cause);
}
}
| 25.970588 | 79 | 0.698754 |
8ef83b6a0e609f0e87558307a7461c5b9566e798 | 6,268 | package com.thankjava.toolkit3d.core.http.httpclient.async.core;
import com.thankjava.toolkit3d.bean.http.async.AsyncHeaders;
import com.thankjava.toolkit3d.bean.http.async.AsyncHttpMethod;
import com.thankjava.toolkit3d.bean.http.async.AsyncParameters;
import com.thankjava.toolkit3d.bean.http.async.AsyncRequest;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* 负责构建HttpRequestBase对象
* <p>Function: RequestBuilder</p>
* <p>Description: </p>
*
* @author [email protected]
* @version 1.0
* @date 2016年12月12日 下午4:44:39
*/
public class RequestBuilder {
/**
* 创建请求信息
*
* @param asyncRequest
* @return
*/
public static HttpRequestBase builderRequest(AsyncRequest asyncRequest) {
return getRequest(asyncRequest);
}
private static HttpRequestBase addEntityParams(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase, AsyncRequest asyncRequest) {
AsyncParameters parameter = asyncRequest.getParameter();
if (parameter != null) {
// 如果bodyString 和valuePair 同时存在,且请求类型为entityParams时,valuePair将需要转化为uri参数
if (parameter.getNameValuePair() != null && parameter.getBodyString() != null) {
HttpRequestBase httpRequestBase = (HttpRequestBase) httpEntityEnclosingRequestBase;
try {
httpRequestBase.setURI(new URIBuilder(httpRequestBase.getURI()).setCharset(StandardCharsets.UTF_8).addParameters(parameter.getNameValuePair()).build());
} catch (URISyntaxException e) {
e.printStackTrace();
}
} else {
if (parameter.getNameValuePair() != null) {
try {
httpEntityEnclosingRequestBase.setEntity(new UrlEncodedFormEntity(parameter.getNameValuePair(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
if (parameter.getBodyString() != null) {
httpEntityEnclosingRequestBase.setEntity(
new StringEntity(parameter.getBodyString(),
parameter.getContentType()
)
);
}
if (parameter.getByteData() != null) {
EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setBinary(parameter.getByteData());
if (parameter.getCharset() != null) {
entityBuilder.setContentEncoding(parameter.getCharset());
}
entityBuilder.setContentType(parameter.getContentType());
httpEntityEnclosingRequestBase.setEntity(entityBuilder.build());
} else if (parameter.getFile() != null) {
EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setFile(parameter.getFile());
if (parameter.getCharset() != null) {
entityBuilder.setContentEncoding(parameter.getCharset());
}
entityBuilder.setContentType(parameter.getContentType());
httpEntityEnclosingRequestBase.setEntity(entityBuilder.build());
}
}
return httpEntityEnclosingRequestBase;
}
private static HttpRequestBase addBaseParams(HttpRequestBase httpRequestBase, AsyncRequest asyncRequest) {
AsyncParameters parameter = asyncRequest.getParameter();
if (parameter != null && parameter.getNameValuePair() != null) {
try {
httpRequestBase.setURI(new URIBuilder(httpRequestBase.getURI()).addParameters(parameter.getNameValuePair()).build());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return httpRequestBase;
}
private static HttpRequestBase getRequest(AsyncRequest asyncRequest) {
AsyncHttpMethod asyncHttpMethod = asyncRequest.getAsyncHttpMethod();
HttpRequestBase requestBase;
boolean useEntity = false;
switch (asyncHttpMethod) {
case get:
requestBase = new HttpGet(asyncRequest.getUrl());
break;
case post:
requestBase = new HttpPost(asyncRequest.getUrl());
useEntity = true;
break;
case patch:
requestBase = new HttpPatch(asyncRequest.getUrl());
useEntity = true;
break;
case delete:
requestBase = new HttpDelete(asyncRequest.getUrl());
break;
case head:
requestBase = new HttpHead(asyncRequest.getUrl());
case options:
requestBase = new HttpOptions(asyncRequest.getUrl());
case put:
requestBase = new HttpPut(asyncRequest.getUrl());
useEntity = true;
break;
case trace:
requestBase = new HttpTrace(asyncRequest.getUrl());
default:
return new HttpGet(asyncRequest.getUrl());
}
AsyncHeaders header = asyncRequest.getHeader();
if (header != null) {
requestBase.setHeaders(header.toHeaderArray());
}
if (useEntity) {
requestBase = addEntityParams((HttpEntityEnclosingRequestBase) requestBase, asyncRequest);
} else {
requestBase = addBaseParams(requestBase, asyncRequest);
}
return requestBase;
}
}
| 36.231214 | 172 | 0.61806 |
26dea1dcd85bf60890d8760b3100f1f9264b59ad | 643 | package com.tanerdiler.microservice.main.repository;
import com.tanerdiler.microservice.main.model.Order;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@Component
@FeignClient("containerized-orders")
public interface OrderServiceClient
{
@GetMapping(value = "/order/api/v1/orders/{orderId}")
Order findById(@PathVariable("orderId") Integer orderId); // never used
@GetMapping(value = "/order/api/v1/orders")
List<Order> findAll();
}
| 30.619048 | 72 | 0.804044 |
59e9fc814972d1be84a7ebca21af205bd4faee6f | 1,941 | package no.f12.agiledeploy.deployer;
import java.io.File;
import no.f12.agiledeploy.deployer.repo.PackageSpecification;
public class DeploymentSpecification {
private PackageSpecification packageSpecification;
private String environment;
private File installBase;
private File packageFile;
public DeploymentSpecification(PackageSpecification ps, String environment, File workingDirectory, File packageFile) {
this.packageSpecification = ps;
this.environment = environment;
this.installBase = workingDirectory;
this.packageFile = packageFile;
}
public PackageSpecification getPackageSpecification() {
return this.packageSpecification;
}
public File getInstallBase() {
return this.installBase;
}
public String getEnvironment() {
return this.environment;
}
public File getPackageFile() {
return this.packageFile;
}
public void setPackageFile(File downloadedFile) {
this.packageFile = downloadedFile;
}
public File getArtifactPath() {
return new File(installBase, this.packageSpecification.getArtifactId());
}
public File getEnvironmentDirectory() {
return new File(getArtifactPath(), this.environment);
}
public File getLogDirectory() {
return new File(getEnvironmentDirectory(), "logs");
}
public File getDataDirectory() {
return new File(getEnvironmentDirectory(), "data");
}
public File getLastInstalledVersionDirectory() {
return new File(getEnvironmentDirectory(), "current");
}
public File getConfigurationDirectory() {
return new File(getLastInstalledVersionDirectory(), "config");
}
public File getBinDirectory() {
return new File(getLastInstalledVersionDirectory(), "bin");
}
public File getEnvironmentPropertiesDirectory() {
return new File(getConfigurationDirectory(), environment);
}
public File getInstallDirectory() {
return new File(new File(getEnvironmentDirectory(), "versions"),
this.packageSpecification.getArtifactFileName());
}
}
| 24.884615 | 119 | 0.773313 |
10b944d97d49ab1a996059904a71290835120ee4 | 2,620 | package per.qy.crawler.entity;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
@Entity
@EntityListeners(AuditingEntityListener.class)
public class WebsiteTask {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(length = 1024)
private String url;//网站url,一般为首页链接
private int maxLevel;//最大爬取层次
private int maxCount;//最大爬取链接数
private int outerLevel;//最大爬取外链层次
private String range;//爬取类型范围
private int taskCount;//任务数
private int finishCount;//爬取完成任务数
private int state = 1;//状态:1=执行中;2=已完成
@CreatedDate
private Date createTime;//创建时间
private Date finishTime;//完成时间
@Transient
private List<String> ranges;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getMaxLevel() {
return maxLevel;
}
public void setMaxLevel(int maxLevel) {
this.maxLevel = maxLevel;
}
public int getMaxCount() {
return maxCount;
}
public void setMaxCount(int maxCount) {
this.maxCount = maxCount;
}
public int getOuterLevel() {
return outerLevel;
}
public void setOuterLevel(int outerLevel) {
this.outerLevel = outerLevel;
}
public String getRange() {
return range;
}
public void setRange(String range) {
this.range = range;
}
public int getTaskCount() {
return taskCount;
}
public void setTaskCount(int taskCount) {
this.taskCount = taskCount;
}
public int getFinishCount() {
return finishCount;
}
public void setFinishCount(int finishCount) {
this.finishCount = finishCount;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getFinishTime() {
return finishTime;
}
public void setFinishTime(Date finishTime) {
this.finishTime = finishTime;
}
public List<String> getRanges() {
return ranges;
}
public void setRanges(List<String> ranges) {
this.ranges = ranges;
}
}
| 20.310078 | 74 | 0.629008 |
f7c271e393419d3e46406d4eda7b26b373b9316e | 1,016 | package com.valentine.gram;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EntityScan(basePackages = {"com.valentine.model","com.valentine.messenger"})
@SpringBootApplication(scanBasePackages = {"com.valentine.gram",
"com.valentine.service", "com.valentine.dao" })
@EnableJpaRepositories("com.valentine.dao")
@EnableTransactionManagement
@EnableConfigurationProperties
public class MainApp {
public static void main(String[] args) {
SpringApplication.run(MainApp.class, args);
}
}
| 39.076923 | 81 | 0.84252 |
313dc4ad2853ef33167ea7ea91cba21c4a6ca309 | 491 | /*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.corba.se.spi.legacy.interceptor;
import com.sun.corba.se.spi.oa.ObjectAdapter;
public interface IORInfoExt
{
public int getServerPort(String type)
throws
UnknownType;
public ObjectAdapter getObjectAdapter();
}
// End of file.
| 12.275 | 79 | 0.629328 |
df35ae97c6f5c87695f91b1aa33ed7623fd13b88 | 315 | package com.foodorderapp.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.foodorderapp.models.entity.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Role findByName(String name);
}
| 24.230769 | 67 | 0.825397 |
439b215e77cf3a64c511d2333b06ace4ace61ab7 | 3,033 | /*
* MIT License
*
* Copyright (c) 2019-2021 Jannis Weis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.github.weisj.darklaf.properties.icons;
import java.awt.*;
import javax.swing.*;
public class TwoIcon implements Icon {
private int iconGap = 2;
private Icon leftIcon;
private Icon rightIcon;
public TwoIcon(final Icon leftIcon, final Icon rightIcon) {
this(leftIcon, rightIcon, 2);
}
public TwoIcon(final Icon leftIcon, final Icon rightIcon, final int iconGap) {
setLeftIcon(leftIcon);
setRightIcon(rightIcon);
this.iconGap = iconGap;
}
public void setIconGap(final int iconGap) {
this.iconGap = iconGap;
}
public void setLeftIcon(final Icon leftIcon) {
this.leftIcon = leftIcon != null ? leftIcon : EmptyIcon.create(0);
}
public void setRightIcon(final Icon rightIcon) {
this.rightIcon = rightIcon != null ? rightIcon : EmptyIcon.create(0);
}
public Icon getLeftIcon() {
return leftIcon;
}
public Icon getRightIcon() {
return rightIcon;
}
@Override
public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
int mid = getIconHeight() / 2;
boolean ltr = c.getComponentOrientation().isLeftToRight();
Icon left = ltr ? leftIcon : rightIcon;
Icon right = ltr ? rightIcon : leftIcon;
int y1 = y + mid - left.getIconHeight() / 2;
int y2 = y + mid - right.getIconHeight() / 2;
leftIcon.paintIcon(c, g, x, y1);
rightIcon.paintIcon(c, g, x + left.getIconWidth() + iconGap, y2);
}
@Override
public int getIconWidth() {
int l = leftIcon.getIconWidth();
int r = rightIcon.getIconWidth();
int gap = 0;
if (l != 0 && r != 0) gap = iconGap;
return l + r + gap;
}
@Override
public int getIconHeight() {
return Math.max(leftIcon.getIconHeight(), rightIcon.getIconHeight());
}
}
| 34.078652 | 100 | 0.671612 |
1fdc466f3a61a651c5a53bcc98a6dcf640027f10 | 394 | package projectEuler;
public class Problem1 {
int target = 999;
int sumDivibleBy(int num){
int n = target/num;
int sum = num*n*(n+1)/2;
return sum;
}
public static void main(String[] args) {
int sum;
Problem1 obj = new Problem1();
sum = obj.sumDivibleBy(3) + obj.sumDivibleBy(5) - obj.sumDivibleBy(15);
System.out.println("Sum divisible by 3 and 5 under 1000: "+sum);
}
}
| 20.736842 | 73 | 0.667513 |
a4fd95b514dd505b3fb9d8c1fb7a3277f1c30845 | 31,980 | /*
* Copyright (c) 2015, 2016 Qualcomm Technologies, Inc.
* All Rights Reserved.
* Confidential and Proprietary - Qualcomm Technologies, Inc.
*/
package org.codeaurora.ims;
import android.os.AsyncResult;
import android.os.SystemProperties;
import android.telecom.VideoProfile;
import android.telecom.Connection.VideoProvider;
import android.telephony.ims.ImsCallProfile;
import com.android.ims.ImsConfig;
import android.telephony.ims.ImsReasonInfo;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.CarrierAppUtils;
import com.android.internal.telephony.DriverCall;
import com.qualcomm.ims.utils.Log;
import org.codeaurora.ims.ImsRilException;
import org.codeaurora.ims.QtiCallConstants;
public class ImsCallUtils {
private static String TAG = "ImsCallUtils";
private static final int MIN_VIDEO_CALL_PHONE_NUMBER_LENGTH = 7;
public static final int CONFIG_TYPE_INVALID = -1;
public static final int CONFIG_TYPE_INT = 1;
public static final int CONFIG_TYPE_STRING = 2;
//TODO: Remove these configs when it is added to the ImsConfig class.
/**
* LTE threshold.
* Handover from LTE to WiFi if LTE < THLTE1 and WiFi >= VOWT_A.
*/
public static final int TH_LTE1 = 56;
/**
* LTE threshold.
* Handover from WiFi to LTE if LTE >= THLTE3 or (WiFi < VOWT_B and LTE >= THLTE2).
*/
public static final int TH_LTE2 = 57;
/**
* LTE threshold.
* Handover from WiFi to LTE if LTE >= THLTE3 or (WiFi < VOWT_B and LTE >= THLTE2).
*/
public static final int TH_LTE3 = 58;
/**
* 1x threshold.
* Handover from 1x to WiFi if 1x < TH1x
*/
public static final int TH_1x = 59;
/**
* WiFi threshold.
* Handover from LTE to WiFi if LTE < THLTE1 and WiFi >= VOWT_A.
*/
public static final int VOWT_A = 60;
/**
* WiFi threshold.
* Handover from WiFi to LTE if LTE >= THLTE3 or (WiFi < VOWT_B and LTE >= THLTE2).
*/
public static final int VOWT_B = 61;
/**
* LTE ePDG timer.
* Device shall not handover back to LTE until the T_ePDG_LTE timer expires.
*/
public static final int T_EPDG_LTE = 62;
/**
* WiFi ePDG timer.
* Device shall not handover back to WiFi until the T_ePDG_WiFi timer expires.
*/
public static final int T_EPDG_WIFI = 63;
/**
* 1x ePDG timer.
* Device shall not re-register on 1x until the T_ePDG_1x timer expires.
*/
public static final int T_EPDG_1X = 64;
/**
* MultiEndpoint status: Enabled (1), or Disabled (0).
* Value is in Integer format.
*/
public static final int VICE_SETTING_ENABLED = 65;
public static final int SESSION_MERGE_STARTED = 1;
public static final int SESSION_MERGE_COMPLETED = 2;
public static final int SESSION_MERGE_FAILED = 3;
/** Checks if a call type is any valid video call type with or without direction
*/
public static boolean isVideoCall(int callType) {
return callType == CallDetails.CALL_TYPE_VT
|| callType == CallDetails.CALL_TYPE_VT_TX
|| callType == CallDetails.CALL_TYPE_VT_RX
|| callType == CallDetails.CALL_TYPE_VT_PAUSE
|| callType == CallDetails.CALL_TYPE_VT_RESUME
|| callType == CallDetails.CALL_TYPE_VT_NODIR;
}
/** Check if call type is valid for lower layers
*/
public static boolean isValidRilModifyCallType(int callType){
return callType == CallDetails.CALL_TYPE_VT
|| callType == CallDetails.CALL_TYPE_VT_TX
|| callType == CallDetails.CALL_TYPE_VT_RX
|| callType == CallDetails.CALL_TYPE_VOICE
|| callType == CallDetails.CALL_TYPE_VT_NODIR;
}
/** Checks if videocall state transitioned to Video Paused state
* @param conn - Current connection object
* @param dc - Latest DriverCallIms instance
*/
public static boolean isVideoPaused(ImsCallSessionImpl conn, DriverCallIms dc) {
int currCallType = conn.getInternalCallType();
DriverCallIms.State currCallState = conn.getInternalState();
int nextCallType = dc.callDetails.call_type;
DriverCallIms.State nextCallState = dc.state;
boolean isHoldingPaused = isVideoCall(currCallType)
&& (currCallState == DriverCallIms.State.HOLDING)
&& isVideoCallTypeWithoutDir(nextCallType)
&& (nextCallState == DriverCallIms.State.ACTIVE);
boolean isActivePaused = (isVideoCall(currCallType)
&& (currCallState == DriverCallIms.State.ACTIVE)
&& isVideoCallTypeWithoutDir(nextCallType)
&& (nextCallState == DriverCallIms.State.ACTIVE));
return isHoldingPaused || isActivePaused;
}
/** Detects active video call
*/
public static boolean canVideoPause(ImsCallSessionImpl conn) {
return isVideoCall(conn.getInternalCallType()) && conn.isCallActive();
}
/** Checks if videocall state transitioned to Video Resumed state
* @param conn - Current connection object
* @param dc - Latest DriverCallIms instance
*/
public static boolean isVideoResumed(ImsCallSessionImpl conn, DriverCallIms dc) {
int currCallType = conn.getInternalCallType();
DriverCallIms.State currCallState = conn.getInternalState();
int nextCallType = dc.callDetails.call_type;
DriverCallIms.State nextCallState = dc.state;
return (isVideoCallTypeWithoutDir(currCallType)
&& (currCallState == DriverCallIms.State.ACTIVE)
&& isVideoCall(nextCallType)
&& (nextCallState == DriverCallIms.State.ACTIVE));
}
/** Checks if AVP Retry needs to be triggered during dialing
* @param conn - Current connection object
* @param dc - Latest DriverCallIms instance
*/
public static boolean isAvpRetryDialing(ImsCallSessionImpl conn, DriverCallIms dc) {
int currCallType = conn.getInternalCallType();
DriverCallIms.State currCallState = conn.getInternalState();
int nextCallType = dc.callDetails.call_type;
DriverCallIms.State nextCallState = dc.state;
boolean dialingAvpRetry = (isVideoCall(currCallType)
&& (currCallState == DriverCallIms.State.DIALING || currCallState == DriverCallIms.State.ALERTING)
&& isVideoCallTypeWithoutDir(nextCallType)
&& nextCallState == DriverCallIms.State.ACTIVE);
return (conn.getImsCallModification().isAvpRetryAllowed() && dialingAvpRetry);
}
/** Checks if AVP Retry needs to be triggered during upgrade
* @param conn - Current connection object
* @param dc - Latest DriverCallIms instance
*/
public static boolean isAvpRetryUpgrade(ImsCallSessionImpl conn, DriverCallIms dc) {
int currCallType = conn.getInternalCallType();
DriverCallIms.State currCallState = conn.getInternalState();
int nextCallType = dc.callDetails.call_type;
DriverCallIms.State nextCallState = dc.state;
boolean upgradeAvpRetry = (currCallType == CallDetails.CALL_TYPE_VOICE
&& currCallState == DriverCallIms.State.ACTIVE
&& isVideoCallTypeWithoutDir(nextCallType)
&& nextCallState == DriverCallIms.State.ACTIVE);
return (conn.getImsCallModification().isAvpRetryAllowed() && upgradeAvpRetry);
}
/** Checks if a call type is video call type with direction
* @param callType
*/
public static boolean isVideoCallTypeWithDir(int callType) {
return callType == CallDetails.CALL_TYPE_VT
|| callType == CallDetails.CALL_TYPE_VT_RX
|| callType == CallDetails.CALL_TYPE_VT_TX;
}
/** Checks if a incoming call is video call
* @param callSession - Current connection object
*/
public static boolean isIncomingVideoCall(ImsCallSessionImpl callSession) {
return (isVideoCall(callSession.getInternalCallType()) &&
(callSession.getInternalState() == DriverCallIms.State.INCOMING ||
callSession.getInternalState() == DriverCallIms.State.WAITING));
}
/** Checks if a call is incoming call
* @param callSession - Current connection object
*/
public static boolean isIncomingCall(ImsCallSessionImpl callSession) {
return (callSession.getInternalState() == DriverCallIms.State.INCOMING ||
callSession.getInternalState() == DriverCallIms.State.WAITING);
}
/** Checks if a call is not CS video call
* @param details - Current call details
*/
public static boolean isNotCsVideoCall(CallDetails details) {
return isVideoCall(details.call_type) &&
(details.call_domain != CallDetails.CALL_DOMAIN_CS);
}
/** Checks if a call type is video call type without direction
* @param callType
*/
public static boolean isVideoCallTypeWithoutDir(int callType) {
return callType == CallDetails.CALL_TYPE_VT_NODIR;
}
public static int convertVideoStateToCallType(int videoState) {
int callType = CallDetails.CALL_TYPE_VOICE;
switch (videoState) {
case VideoProfile.STATE_AUDIO_ONLY:
callType = CallDetails.CALL_TYPE_VOICE;
break;
case VideoProfile.STATE_RX_ENABLED:
callType = CallDetails.CALL_TYPE_VT_RX;
break;
case VideoProfile.STATE_TX_ENABLED:
callType = CallDetails.CALL_TYPE_VT_TX;
break;
case VideoProfile.STATE_BIDIRECTIONAL:
callType = CallDetails.CALL_TYPE_VT;
break;
case VideoProfile.STATE_PAUSED:
callType = CallDetails.CALL_TYPE_VT_NODIR;
break;
}
return callType;
}
public static int convertCallTypeToVideoState(int callType) {
int videoState = VideoProfile.STATE_AUDIO_ONLY;
switch (callType) {
case CallDetails.CALL_TYPE_VOICE:
videoState = VideoProfile.STATE_AUDIO_ONLY;
break;
case CallDetails.CALL_TYPE_VT_RX:
videoState = VideoProfile.STATE_RX_ENABLED;
break;
case CallDetails.CALL_TYPE_VT_TX:
videoState = VideoProfile.STATE_TX_ENABLED;
break;
case CallDetails.CALL_TYPE_VT:
videoState = VideoProfile.STATE_BIDIRECTIONAL;
break;
case CallDetails.CALL_TYPE_VT_PAUSE:
case CallDetails.CALL_TYPE_VT_NODIR:
videoState = VideoProfile.STATE_PAUSED;
break;
}
return videoState;
}
public static int convertToInternalCallType(int imsCallProfileCallType) {
int internalCallType = CallDetails.CALL_TYPE_UNKNOWN;
switch (imsCallProfileCallType) {
case ImsCallProfile.CALL_TYPE_VOICE:
case ImsCallProfile.CALL_TYPE_VOICE_N_VIDEO:
internalCallType = CallDetails.CALL_TYPE_VOICE;
break;
case ImsCallProfile.CALL_TYPE_VT:
case ImsCallProfile.CALL_TYPE_VIDEO_N_VOICE:
internalCallType = CallDetails.CALL_TYPE_VT;
break;
case ImsCallProfile.CALL_TYPE_VT_NODIR:
internalCallType = CallDetails.CALL_TYPE_VT_NODIR;
break;
case ImsCallProfile.CALL_TYPE_VT_TX:
internalCallType = CallDetails.CALL_TYPE_VT_TX;
break;
case ImsCallProfile.CALL_TYPE_VS_RX:
internalCallType = CallDetails.CALL_TYPE_VT_RX;
break;
default:
Log.e(TAG, "convertToInternalCallType invalid calltype " + imsCallProfileCallType);
break;
}
return internalCallType;
}
public static VideoProfile convertToVideoProfile(int callType, int callQuality) {
VideoProfile videoCallProfile = new VideoProfile(
convertCallTypeToVideoState(callType), callQuality);
// TODO in future - add quality to CallDetails
return videoCallProfile;
}
public static int convertImsErrorToUiError(int error) {
if (error == CallModify.E_CANCELLED) {
return VideoProvider.SESSION_MODIFY_REQUEST_TIMED_OUT;
} else if (error == CallModify.E_SUCCESS || error == CallModify.E_UNUSED) {
return VideoProvider.SESSION_MODIFY_REQUEST_SUCCESS;
} else if (error == QtiCallConstants.SESSION_MODIFY_REQUEST_FAILED_LOW_BATTERY) {
return QtiCallConstants.SESSION_MODIFY_REQUEST_FAILED_LOW_BATTERY;
} else {
return VideoProvider.SESSION_MODIFY_REQUEST_FAIL;
}
}
/**
* Utility method to detect if call type has changed
* @return boolean - true if both driver calls are not null and call type has changed
*/
public static boolean hasCallTypeChanged(DriverCallIms dc, DriverCallIms dcUpdate) {
return (dc != null && dcUpdate != null &&
dc.callDetails.call_type != dcUpdate.callDetails.call_type);
}
/**
* Utility method to detect if call type has changed from Video to Volte
* @return boolean - true if both driver calls are not null and call type
* has changed from Video to Volte
*/
public static boolean hasCallTypeChangedToVoice(DriverCallIms dc, DriverCallIms dcUpdate) {
return (dc != null && dcUpdate != null && isVideoCall(dc.callDetails.call_type) &&
dcUpdate.callDetails.call_type == CallDetails.CALL_TYPE_VOICE);
}
/**
* Utility method to get modify call error code from exception
* @return int - session modify request errors. Valid values are
* {@link VideoProvider#SESSION_MODIFY_REQUEST_FAIL},
* {@link VideoProvider#SESSION_MODIFY_REQUEST_INVALID},
* {@link VideoProvider#SESSION_MODIFY_REQUEST_TIMED_OUT},
* {@link VideoProvider#SESSION_MODIFY_REQUEST_REJECTED_BY_REMOTE},
* {@link QtiCallConstants#SESSION_MODIFY_REQUEST_FAILED_LOW_BATTERY}
*
*/
public static int getUiErrorCode(Throwable ex) {
int status = VideoProvider.SESSION_MODIFY_REQUEST_FAIL;
if (ex instanceof ImsRilException) {
ImsRilException imsRilException = (ImsRilException) ex;
status = getUiErrorCode(imsRilException.getErrorCode());
}
return status;
}
public static int getUiErrorCode(int imsErrorCode) {
int status = VideoProvider.SESSION_MODIFY_REQUEST_SUCCESS;
switch (imsErrorCode) {
case ImsQmiIF.E_SUCCESS:
case ImsQmiIF.E_UNUSED:
status = VideoProvider.SESSION_MODIFY_REQUEST_SUCCESS;
break;
case ImsQmiIF.E_CANCELLED:
status = VideoProvider.SESSION_MODIFY_REQUEST_TIMED_OUT;
break;
case ImsQmiIF.E_REJECTED_BY_REMOTE:
status = VideoProvider.SESSION_MODIFY_REQUEST_REJECTED_BY_REMOTE;
break;
case ImsQmiIF.E_INVALID_PARAMETER:
status = VideoProvider.SESSION_MODIFY_REQUEST_INVALID;
break;
case QtiCallConstants.SESSION_MODIFY_REQUEST_FAILED_LOW_BATTERY:
status = QtiCallConstants.SESSION_MODIFY_REQUEST_FAILED_LOW_BATTERY;
break;
default:
status = VideoProvider.SESSION_MODIFY_REQUEST_FAIL;
}
return status;
}
public static boolean isConfigRequestValid(int item, int requestType) {
int configType = CONFIG_TYPE_INVALID;
switch (item) {
case ImsConfig.ConfigConstants.VOCODER_AMRMODESET:
case ImsConfig.ConfigConstants.VOCODER_AMRWBMODESET:
case ImsConfig.ConfigConstants.DOMAIN_NAME:
case ImsConfig.ConfigConstants.LBO_PCSCF_ADDRESS:
case ImsConfig.ConfigConstants.SMS_PSI:
configType = CONFIG_TYPE_STRING;
break;
case ImsConfig.ConfigConstants.SIP_SESSION_TIMER:
case ImsConfig.ConfigConstants.MIN_SE:
case ImsConfig.ConfigConstants.CANCELLATION_TIMER:
case ImsConfig.ConfigConstants.TDELAY:
case ImsConfig.ConfigConstants.SILENT_REDIAL_ENABLE:
case ImsConfig.ConfigConstants.SIP_T1_TIMER:
case ImsConfig.ConfigConstants.SIP_T2_TIMER:
case ImsConfig.ConfigConstants.SIP_TF_TIMER:
case ImsConfig.ConfigConstants.VLT_SETTING_ENABLED:
case ImsConfig.ConfigConstants.LVC_SETTING_ENABLED:
case ImsConfig.ConfigConstants.SMS_FORMAT:
case ImsConfig.ConfigConstants.SMS_OVER_IP:
case ImsConfig.ConfigConstants.PUBLISH_TIMER:
case ImsConfig.ConfigConstants.PUBLISH_TIMER_EXTENDED:
case ImsConfig.ConfigConstants.CAPABILITIES_CACHE_EXPIRATION:
case ImsConfig.ConfigConstants.AVAILABILITY_CACHE_EXPIRATION:
case ImsConfig.ConfigConstants.CAPABILITIES_POLL_INTERVAL:
case ImsConfig.ConfigConstants.SOURCE_THROTTLE_PUBLISH:
case ImsConfig.ConfigConstants.MAX_NUMENTRIES_IN_RCL:
case ImsConfig.ConfigConstants.CAPAB_POLL_LIST_SUB_EXP:
case ImsConfig.ConfigConstants.GZIP_FLAG:
case ImsConfig.ConfigConstants.EAB_SETTING_ENABLED:
case ImsConfig.ConfigConstants.VOICE_OVER_WIFI_ROAMING:
case ImsConfig.ConfigConstants.VOICE_OVER_WIFI_MODE:
case ImsConfig.ConfigConstants.MOBILE_DATA_ENABLED:
case ImsConfig.ConfigConstants.VOLTE_USER_OPT_IN_STATUS:
case ImsConfig.ConfigConstants.KEEP_ALIVE_ENABLED:
case ImsConfig.ConfigConstants.REGISTRATION_RETRY_BASE_TIME_SEC:
case ImsConfig.ConfigConstants.REGISTRATION_RETRY_MAX_TIME_SEC:
case ImsConfig.ConfigConstants.SPEECH_START_PORT:
case ImsConfig.ConfigConstants.SPEECH_END_PORT:
case ImsConfig.ConfigConstants.SIP_INVITE_REQ_RETX_INTERVAL_MSEC:
case ImsConfig.ConfigConstants.SIP_INVITE_RSP_WAIT_TIME_MSEC:
case ImsConfig.ConfigConstants.SIP_INVITE_RSP_RETX_WAIT_TIME_MSEC:
case ImsConfig.ConfigConstants.SIP_NON_INVITE_REQ_RETX_INTERVAL_MSEC:
case ImsConfig.ConfigConstants.SIP_NON_INVITE_TXN_TIMEOUT_TIMER_MSEC:
case ImsConfig.ConfigConstants.SIP_INVITE_RSP_RETX_INTERVAL_MSEC:
case ImsConfig.ConfigConstants.SIP_ACK_RECEIPT_WAIT_TIME_MSEC:
case ImsConfig.ConfigConstants.SIP_ACK_RETX_WAIT_TIME_MSEC:
case ImsConfig.ConfigConstants.SIP_NON_INVITE_REQ_RETX_WAIT_TIME_MSEC:
case ImsConfig.ConfigConstants.SIP_NON_INVITE_RSP_RETX_WAIT_TIME_MSEC:
case ImsConfig.ConfigConstants.AMR_WB_OCTET_ALIGNED_PT:
case ImsConfig.ConfigConstants.AMR_WB_BANDWIDTH_EFFICIENT_PT:
case ImsConfig.ConfigConstants.AMR_OCTET_ALIGNED_PT:
case ImsConfig.ConfigConstants.AMR_BANDWIDTH_EFFICIENT_PT:
case ImsConfig.ConfigConstants.DTMF_WB_PT:
case ImsConfig.ConfigConstants.DTMF_NB_PT:
case ImsConfig.ConfigConstants.AMR_DEFAULT_MODE:
case ImsConfig.ConfigConstants.VIDEO_QUALITY:
case TH_LTE1:
case TH_LTE2:
case TH_LTE3:
case TH_1x:
case VOWT_A:
case VOWT_B:
case T_EPDG_LTE:
case T_EPDG_WIFI:
case T_EPDG_1X:
case VICE_SETTING_ENABLED:
configType = CONFIG_TYPE_INT;
break;
}
return configType == requestType;
}
public static int convertImsConfigToProto(int config) {
switch(config) {
case ImsConfig.ConfigConstants.VOCODER_AMRMODESET:
return ImsQmiIF.CONFIG_ITEM_VOCODER_AMRMODESET;
case ImsConfig.ConfigConstants.VOCODER_AMRWBMODESET:
return ImsQmiIF.CONFIG_ITEM_VOCODER_AMRWBMODESET;
case ImsConfig.ConfigConstants.SIP_SESSION_TIMER:
return ImsQmiIF.CONFIG_ITEM_SIP_SESSION_TIMER;
case ImsConfig.ConfigConstants.MIN_SE:
return ImsQmiIF.CONFIG_ITEM_MIN_SESSION_EXPIRY;
case ImsConfig.ConfigConstants.CANCELLATION_TIMER:
return ImsQmiIF.CONFIG_ITEM_CANCELLATION_TIMER;
case ImsConfig.ConfigConstants.TDELAY:
return ImsQmiIF.CONFIG_ITEM_T_DELAY;
case ImsConfig.ConfigConstants.SILENT_REDIAL_ENABLE:
return ImsQmiIF.CONFIG_ITEM_SILENT_REDIAL_ENABLE;
case ImsConfig.ConfigConstants.SIP_T1_TIMER:
return ImsQmiIF.CONFIG_ITEM_SIP_T1_TIMER;
case ImsConfig.ConfigConstants.SIP_T2_TIMER:
return ImsQmiIF.CONFIG_ITEM_SIP_T2_TIMER;
case ImsConfig.ConfigConstants.SIP_TF_TIMER:
return ImsQmiIF.CONFIG_ITEM_SIP_TF_TIMER;
case ImsConfig.ConfigConstants.VLT_SETTING_ENABLED:
return ImsQmiIF.CONFIG_ITEM_VLT_SETTING_ENABLED;
case ImsConfig.ConfigConstants.LVC_SETTING_ENABLED:
return ImsQmiIF.CONFIG_ITEM_LVC_SETTING_ENABLED;
case ImsConfig.ConfigConstants.DOMAIN_NAME:
return ImsQmiIF.CONFIG_ITEM_DOMAIN_NAME;
case ImsConfig.ConfigConstants.SMS_FORMAT:
return ImsQmiIF.CONFIG_ITEM_SMS_FORMAT;
case ImsConfig.ConfigConstants.SMS_OVER_IP:
return ImsQmiIF.CONFIG_ITEM_SMS_OVER_IP;
case ImsConfig.ConfigConstants.PUBLISH_TIMER:
return ImsQmiIF.CONFIG_ITEM_PUBLISH_TIMER;
case ImsConfig.ConfigConstants.PUBLISH_TIMER_EXTENDED:
return ImsQmiIF.CONFIG_ITEM_PUBLISH_TIMER_EXTENDED;
case ImsConfig.ConfigConstants.CAPABILITIES_CACHE_EXPIRATION:
return ImsQmiIF.CONFIG_ITEM_CAPABILITIES_CACHE_EXPIRATION;
case ImsConfig.ConfigConstants.AVAILABILITY_CACHE_EXPIRATION:
return ImsQmiIF.CONFIG_ITEM_AVAILABILITY_CACHE_EXPIRATION;
case ImsConfig.ConfigConstants.CAPABILITIES_POLL_INTERVAL:
return ImsQmiIF.CONFIG_ITEM_CAPABILITIES_POLL_INTERVAL;
case ImsConfig.ConfigConstants.SOURCE_THROTTLE_PUBLISH:
return ImsQmiIF.CONFIG_ITEM_SOURCE_THROTTLE_PUBLISH;
case ImsConfig.ConfigConstants.MAX_NUMENTRIES_IN_RCL:
return ImsQmiIF.CONFIG_ITEM_MAX_NUM_ENTRIES_IN_RCL;
case ImsConfig.ConfigConstants.CAPAB_POLL_LIST_SUB_EXP:
return ImsQmiIF.CONFIG_ITEM_CAPAB_POLL_LIST_SUB_EXP;
case ImsConfig.ConfigConstants.GZIP_FLAG:
return ImsQmiIF.CONFIG_ITEM_GZIP_FLAG;
case ImsConfig.ConfigConstants.EAB_SETTING_ENABLED:
return ImsQmiIF.CONFIG_ITEM_EAB_SETTING_ENABLED;
case ImsConfig.ConfigConstants.VOICE_OVER_WIFI_ROAMING:
return ImsQmiIF.CONFIG_ITEM_VOICE_OVER_WIFI_ROAMING;
case ImsConfig.ConfigConstants.VOICE_OVER_WIFI_MODE:
return ImsQmiIF.CONFIG_ITEM_VOICE_OVER_WIFI_MODE;
case ImsConfig.ConfigConstants.LBO_PCSCF_ADDRESS:
return ImsQmiIF.CONFIG_ITEM_LBO_PCSCF_ADDRESS;
case ImsConfig.ConfigConstants.MOBILE_DATA_ENABLED:
return ImsQmiIF.CONFIG_ITEM_MOBILE_DATA_ENABLED;
case ImsConfig.ConfigConstants.VOLTE_USER_OPT_IN_STATUS:
return ImsQmiIF.CONFIG_ITEM_VOLTE_USER_OPT_IN_STATUS;
case ImsConfig.ConfigConstants.KEEP_ALIVE_ENABLED:
return ImsQmiIF.CONFIG_ITEM_KEEP_ALIVE_ENABLED;
case ImsConfig.ConfigConstants.REGISTRATION_RETRY_BASE_TIME_SEC:
return ImsQmiIF.CONFIG_ITEM_REGISTRATION_RETRY_BASE_TIME_SEC;
case ImsConfig.ConfigConstants.REGISTRATION_RETRY_MAX_TIME_SEC:
return ImsQmiIF.CONFIG_ITEM_REGISTRATION_RETRY_MAX_TIME_SEC;
case ImsConfig.ConfigConstants.SPEECH_START_PORT:
return ImsQmiIF.CONFIG_ITEM_SPEECH_START_PORT;
case ImsConfig.ConfigConstants.SPEECH_END_PORT:
return ImsQmiIF.CONFIG_ITEM_SPEECH_END_PORT;
case ImsConfig.ConfigConstants.SIP_INVITE_REQ_RETX_INTERVAL_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_INVITE_REQ_RETX_INTERVAL_MSEC;
case ImsConfig.ConfigConstants.SIP_INVITE_RSP_WAIT_TIME_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_INVITE_RSP_WAIT_TIME_MSEC;
case ImsConfig.ConfigConstants.SIP_INVITE_RSP_RETX_WAIT_TIME_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_INVITE_RSP_RETX_WAIT_TIME_MSEC;
case ImsConfig.ConfigConstants.SIP_NON_INVITE_REQ_RETX_INTERVAL_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_NON_INVITE_REQ_RETX_INTERVAL_MSEC;
case ImsConfig.ConfigConstants.SIP_NON_INVITE_TXN_TIMEOUT_TIMER_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_NON_INVITE_TXN_TIMEOUT_TIMER_MSEC;
case ImsConfig.ConfigConstants.SIP_INVITE_RSP_RETX_INTERVAL_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_INVITE_RSP_RETX_INTERVAL_MSEC;
case ImsConfig.ConfigConstants.SIP_ACK_RECEIPT_WAIT_TIME_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_ACK_RECEIPT_WAIT_TIME_MSEC;
case ImsConfig.ConfigConstants.SIP_ACK_RETX_WAIT_TIME_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_ACK_RETX_WAIT_TIME_MSEC;
case ImsConfig.ConfigConstants.SIP_NON_INVITE_REQ_RETX_WAIT_TIME_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_NON_INVITE_REQ_RETX_WAIT_TIME_MSEC;
case ImsConfig.ConfigConstants.SIP_NON_INVITE_RSP_RETX_WAIT_TIME_MSEC:
return ImsQmiIF.CONFIG_ITEM_SIP_NON_INVITE_RSP_RETX_WAIT_TIME_MSEC;
case ImsConfig.ConfigConstants.AMR_WB_OCTET_ALIGNED_PT:
return ImsQmiIF.CONFIG_ITEM_AMR_WB_OCTET_ALIGNED_PT;
case ImsConfig.ConfigConstants.AMR_WB_BANDWIDTH_EFFICIENT_PT:
return ImsQmiIF.CONFIG_ITEM_AMR_WB_BANDWIDTH_EFFICIENT_PT;
case ImsConfig.ConfigConstants.AMR_OCTET_ALIGNED_PT:
return ImsQmiIF.CONFIG_ITEM_AMR_OCTET_ALIGNED_PT;
case ImsConfig.ConfigConstants.AMR_BANDWIDTH_EFFICIENT_PT:
return ImsQmiIF.CONFIG_ITEM_AMR_BANDWIDTH_EFFICIENT_PT;
case ImsConfig.ConfigConstants.DTMF_WB_PT:
return ImsQmiIF.CONFIG_ITEM_DTMF_WB_PT;
case ImsConfig.ConfigConstants.DTMF_NB_PT:
return ImsQmiIF.CONFIG_ITEM_DTMF_NB_PT;
case ImsConfig.ConfigConstants.AMR_DEFAULT_MODE:
return ImsQmiIF.CONFIG_ITEM_AMR_DEFAULT_MODE;
case ImsConfig.ConfigConstants.SMS_PSI:
return ImsQmiIF.CONFIG_ITEM_SMS_PSI;
case ImsConfig.ConfigConstants.VIDEO_QUALITY:
return ImsQmiIF.CONFIG_ITEM_VIDEO_QUALITY;
case TH_LTE1:
return ImsQmiIF.CONFIG_ITEM_THRESHOLD_LTE1;
case TH_LTE2:
return ImsQmiIF.CONFIG_ITEM_THRESHOLD_LTE2;
case TH_LTE3:
return ImsQmiIF.CONFIG_ITEM_THRESHOLD_LTE3;
case TH_1x:
return ImsQmiIF.CONFIG_ITEM_THRESHOLD_1x;
case VOWT_A:
return ImsQmiIF.CONFIG_ITEM_THRESHOLD_WIFI_A;
case VOWT_B:
return ImsQmiIF.CONFIG_ITEM_THRESHOLD_WIFI_B;
case T_EPDG_LTE:
return ImsQmiIF.CONFIG_ITEM_T_EPDG_LTE;
case T_EPDG_WIFI:
return ImsQmiIF.CONFIG_ITEM_T_EPDG_WIFI;
case T_EPDG_1X:
return ImsQmiIF.CONFIG_ITEM_T_EPDG_1x;
case VICE_SETTING_ENABLED:
return ImsQmiIF.CONFIG_ITEM_VCE_SETTING_ENABLED;
default:
throw new IllegalArgumentException();
}
}
public static boolean isActive(DriverCallIms dc) {
return (dc != null && dc.state == DriverCallIms.State.ACTIVE);
}
/**
* Maps the proto exception error codes passed from lower layers (RIL) to internal error codes.
*/
public static int toUiErrorCode(ImsRilException ex) {
switch (ex.getErrorCode()) {
case ImsQmiIF.E_HOLD_RESUME_FAILED:
return QtiCallConstants.ERROR_CALL_SUPP_SVC_FAILED;
case ImsQmiIF.E_HOLD_RESUME_CANCELED:
return QtiCallConstants.ERROR_CALL_SUPP_SVC_CANCELLED;
case ImsQmiIF.E_REINVITE_COLLISION:
return QtiCallConstants.ERROR_CALL_SUPP_SVC_REINVITE_COLLISION;
default:
return QtiCallConstants.ERROR_CALL_CODE_UNSPECIFIED;
}
}
/**
* Maps the proto exception error codes passed from lower layers (RIL) to Ims error codes.
*/
public static int toImsErrorCode(ImsRilException ex) {
switch (ex.getErrorCode()) {
case ImsQmiIF.E_HOLD_RESUME_FAILED:
return ImsReasonInfo.CODE_SUPP_SVC_FAILED;
case ImsQmiIF.E_HOLD_RESUME_CANCELED:
return ImsReasonInfo.CODE_SUPP_SVC_CANCELLED;
case ImsQmiIF.E_REINVITE_COLLISION:
return ImsReasonInfo.CODE_SUPP_SVC_REINVITE_COLLISION;
default:
return ImsReasonInfo.CODE_UNSPECIFIED;
}
}
/**
* Check is carrier one supported or not
*/
public static boolean isCarrierOneSupported() {
String property = SystemProperties.get("persist.radio.atel.carrier");
return "405854".equals(property);
}
/**
* Checks if the vidoCall number is valid,ignore the special characters and invalid length
*
* @param number the number to call.
* @return true if the number is valid
*
* @hide
*/
public static boolean isVideoCallNumValid(String number) {
if (number == null || number.isEmpty()
|| number.length() < MIN_VIDEO_CALL_PHONE_NUMBER_LENGTH) {
Log.w(TAG, "Phone number invalid!");
return false;
}
/*if the first char is "+",then remove it,
* this for support international call
*/
if(number.startsWith("+")) {
number = number.substring(1, number.length());
}
//Check non-digit characters '#', '+', ',', and ';'
if (number.contains("#") || number.contains("+") ||
number.contains(",") || number.contains(";") ||
number.contains("*")) {
return false;
}
return true;
}
/**
* Creates ImsReasonInfo object from proto structure.
*/
public static ImsReasonInfo getImsReasonInfo(ImsQmiIF.SipErrorInfo error,
int errorCode) {
if (error == null) {
return new ImsReasonInfo(errorCode, 0);
} else {
Log.d(TAG, "Sip error code:" + error.getSipErrorCode() +
" error string :" + error.getSipErrorString());
return new ImsReasonInfo(errorCode, error.getSipErrorCode(),
error.getSipErrorString());
}
}
/**
* Creates ImsReasonInfo object from async result.
*/
public static ImsReasonInfo getImsReasonInfo(AsyncResult ar)
{
ImsQmiIF.SipErrorInfo sipErrorInfo = null;
int code = ImsReasonInfo.CODE_UNSPECIFIED;
if(ar != null) {
sipErrorInfo = (ImsQmiIF.SipErrorInfo) ar.result;
if(ar.exception != null) {
code = ImsCallUtils.toImsErrorCode((ImsRilException)ar.exception);
}
}
return getImsReasonInfo(sipErrorInfo, code);
}
}
| 45.882353 | 118 | 0.667761 |
136b6e04ca99087b94e9f8d35e7e0993b98e743e | 1,281 | import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class RandomizedQueueTest {
@Test
public void isEmpty() {
RandomizedQueue<Integer> queue = new RandomizedQueue<>();
assertEquals(0, queue.size());
assertTrue(queue.isEmpty());
}
@Test
public void enqueue() {
RandomizedQueue<Integer> queue = new RandomizedQueue<>();
queue.enqueue(5);
assertEquals(1, queue.size());
assertFalse(queue.isEmpty());
assertEquals(5, queue.sample().intValue());
assertFalse(queue.isEmpty());
assertEquals(1, queue.size());
}
@Test
public void dequeue() {
RandomizedQueue<Integer> queue = new RandomizedQueue<>();
queue.enqueue(4);
assertEquals(4, queue.dequeue().intValue());
assertTrue(queue.isEmpty());
assertEquals(0, queue.size());
}
@Test
public void test() {
RandomizedQueue<Integer> queue = new RandomizedQueue<>();
queue.enqueue(297);
queue.enqueue(421);
queue.enqueue(22);
System.out.println(queue.dequeue());
queue.enqueue(118);
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
}
}
| 24.169811 | 65 | 0.601874 |
953050fe4fa0ea114a7ebea09ea858a6701deaa5 | 1,210 | package com.oven.demo.core.base.service;
import com.oven.demo.common.util.CommonUtils;
import com.oven.demo.core.log.service.LogService;
import com.oven.demo.core.user.vo.User;
import com.oven.demo.framework.cache.CacheService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* 基类服务
*
* @author Oven
*/
@Service
public class BaseService {
@Resource
private LogService logService;
@Resource
private CacheService cacheService;
/**
* 添加日志
*/
public void addLog(String title, String content) {
User user = CommonUtils.getCurrentUser();
if (user != null) {
logService.addLog(title, content, user.getId(), user.getNickName(), CommonUtils.getCurrentUserIp());
} else {
logService.addLog(title, content, -1, "系统", "127.0.0.1");
}
}
/**
* 读缓存
*/
public <T> T get(String key) {
return cacheService.get(key);
}
/**
* 写缓存
*/
public <T> void set(String key, T obj) {
cacheService.set(key, obj);
}
/**
* 批量移除缓存
*/
public void batchRemove(String... key) {
cacheService.batchRemove(key);
}
}
| 20.862069 | 112 | 0.61157 |
ec3d741e84f05e9b5b098db562c2570df65ab5ed | 2,189 |
package com.cjhxfund.autocode.wesklake.model.xsd.common.dict;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.cjhxfund.autocode.wesklake.model.xsd.common.dict package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _ArrayOfDict_QNAME = new QName("", "ArrayOfDict");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.cjhxfund.autocode.wesklake.model.xsd.common.dict
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link ArrayOfDictType }
*
*/
public ArrayOfDictType createArrayOfDictType() {
return new ArrayOfDictType();
}
/**
* Create an instance of {@link DictItemType }
*
*/
public DictItemType createDictItemType() {
return new DictItemType();
}
/**
* Create an instance of {@link ItemsType }
*
*/
public ItemsType createItemsType() {
return new ItemsType();
}
/**
* Create an instance of {@link DictType }
*
*/
public DictType createDictType() {
return new DictType();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ArrayOfDictType }{@code >}}
*
*/
@XmlElementDecl(namespace = "", name = "ArrayOfDict")
public JAXBElement<ArrayOfDictType> createArrayOfDict(ArrayOfDictType value) {
return new JAXBElement<ArrayOfDictType>(_ArrayOfDict_QNAME, ArrayOfDictType.class, null, value);
}
}
| 28.064103 | 166 | 0.679306 |
da1c1e6e4c57608622444db455f5d64877a40363 | 124,364 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|wsdlto
operator|.
name|jaxws
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|File
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|FileInputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|Method
import|;
end_import
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|Modifier
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|charset
operator|.
name|StandardCharsets
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|file
operator|.
name|FileSystems
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|file
operator|.
name|Files
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|file
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Arrays
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jws
operator|.
name|WebParam
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jws
operator|.
name|WebResult
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|jws
operator|.
name|WebService
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|namespace
operator|.
name|QName
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|ws
operator|.
name|Action
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|ws
operator|.
name|WebFault
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|ws
operator|.
name|WebServiceClient
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|common
operator|.
name|i18n
operator|.
name|Message
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|helpers
operator|.
name|FileUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|helpers
operator|.
name|IOUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|common
operator|.
name|CommandInterfaceUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|common
operator|.
name|TestFileUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|common
operator|.
name|ToolConstants
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|common
operator|.
name|ToolContext
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|common
operator|.
name|ToolException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|util
operator|.
name|AnnotationUtil
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|wsdlto
operator|.
name|AbstractCodeGenTest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|wsdlto
operator|.
name|WSDLToJava
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|tools
operator|.
name|wsdlto
operator|.
name|frontend
operator|.
name|jaxws
operator|.
name|validator
operator|.
name|UniqueBodyValidator
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|wsdl11
operator|.
name|WSDLRuntimeException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|eclipse
operator|.
name|jetty
operator|.
name|server
operator|.
name|NetworkConnector
import|;
end_import
begin_import
import|import
name|org
operator|.
name|eclipse
operator|.
name|jetty
operator|.
name|server
operator|.
name|Server
import|;
end_import
begin_import
import|import
name|org
operator|.
name|eclipse
operator|.
name|jetty
operator|.
name|server
operator|.
name|handler
operator|.
name|ResourceHandler
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertFalse
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertNotNull
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertNull
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertTrue
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|fail
import|;
end_import
begin_class
specifier|public
class|class
name|CodeGenBugTest
extends|extends
name|AbstractCodeGenTest
block|{
annotation|@
name|Test
specifier|public
name|void
name|testCXF2944
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf2944/cxf2944.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALLOW_ELEMENT_REFS
argument_list|,
literal|"true"
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.tools.fortest.cxf2944.WebResultService"
argument_list|)
decl_stmt|;
name|WebResult
name|webResult
init|=
name|AnnotationUtil
operator|.
name|getWebResult
argument_list|(
name|clz
operator|.
name|getMethods
argument_list|()
index|[
literal|0
index|]
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"hello/name"
argument_list|,
name|webResult
operator|.
name|targetNamespace
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|"name"
argument_list|,
name|webResult
operator|.
name|name
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF2935
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf2935/webservice.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALLOW_ELEMENT_REFS
argument_list|,
literal|"true"
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.WebParamWebService"
argument_list|)
decl_stmt|;
name|WebParam
name|webParam
init|=
name|AnnotationUtil
operator|.
name|getWebParam
argument_list|(
name|clz
operator|.
name|getMethods
argument_list|()
index|[
literal|0
index|]
argument_list|,
literal|"Name"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"helloString/Name"
argument_list|,
name|webParam
operator|.
name|targetNamespace
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF1969
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1969/report_incident.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
comment|//wsdl is invalid, but want to test some of the parsing of the invalid parts
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_VALIDATE_WSDL
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
try|try
block|{
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|WSDLRuntimeException
name|wrex
parameter_list|)
block|{
name|assertTrue
argument_list|(
name|wrex
operator|.
name|getMessage
argument_list|()
operator|.
name|contains
argument_list|(
literal|"Could not find portType for binding"
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
comment|// Test for CXF-1678
specifier|public
name|void
name|testLogicalOnlyWSDL
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf-1678/hello_world_logical_only.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_VALIDATE_WSDL
argument_list|)
expr_stmt|;
comment|//no binding/service
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|assertNotNull
argument_list|(
literal|"Trouble processing logical only wsdl"
argument_list|,
name|output
argument_list|)
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.cxf1678.hello_world_soap_http.GreeterImpl"
argument_list|)
decl_stmt|;
name|WebService
name|webServiceAnn
init|=
name|AnnotationUtil
operator|.
name|getPrivClassAnnotation
argument_list|(
name|clz
argument_list|,
name|WebService
operator|.
name|class
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"org.apache.cxf.cxf1678.hello_world_soap_http.Greeter"
argument_list|,
name|webServiceAnn
operator|.
name|endpointInterface
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testBug305729
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug305729/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|assertNotNull
argument_list|(
literal|"Process message with no part wsdl error"
argument_list|,
name|output
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testBug305773
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_IMPL
argument_list|,
name|ToolConstants
operator|.
name|CFG_IMPL
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug305773/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.SoapPortImpl"
argument_list|)
decl_stmt|;
name|WebService
name|webServiceAnn
init|=
name|AnnotationUtil
operator|.
name|getPrivClassAnnotation
argument_list|(
name|clz
argument_list|,
name|WebService
operator|.
name|class
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"Impl class should note generate name property value in webService annotation"
argument_list|,
name|webServiceAnn
operator|.
name|name
argument_list|()
operator|.
name|isEmpty
argument_list|()
argument_list|)
expr_stmt|;
name|assertFalse
argument_list|(
literal|"Impl class should generate portName property value in webService annotation"
argument_list|,
name|webServiceAnn
operator|.
name|portName
argument_list|()
operator|.
name|isEmpty
argument_list|()
argument_list|)
expr_stmt|;
name|assertFalse
argument_list|(
literal|"Impl class should generate serviceName property value in webService annotation"
argument_list|,
name|webServiceAnn
operator|.
name|serviceName
argument_list|()
operator|.
name|isEmpty
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testBug305700
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|,
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug305700/addNumbers.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testNamespacePackageMapping1
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|addNamespacePackageMap
argument_list|(
literal|"http://cxf.apache.org/w2j/hello_world_soap_http/types"
argument_list|,
literal|"org.apache.types"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|org
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|apache
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"apache"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|apache
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|types
init|=
operator|new
name|File
argument_list|(
name|apache
argument_list|,
literal|"types"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|types
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
index|[]
name|files
init|=
name|apache
operator|.
name|listFiles
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
literal|2
argument_list|,
name|files
operator|.
name|length
argument_list|)
expr_stmt|;
name|files
operator|=
name|types
operator|.
name|listFiles
argument_list|()
expr_stmt|;
name|assertEquals
argument_list|(
literal|17
argument_list|,
name|files
operator|.
name|length
argument_list|)
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.types.GreetMe"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
name|clz
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testNamespacePackageMapping2
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|addNamespacePackageMap
argument_list|(
literal|"http://cxf.apache.org/w2j/hello_world_soap_http"
argument_list|,
literal|"org.apache"
argument_list|)
expr_stmt|;
name|env
operator|.
name|addNamespacePackageMap
argument_list|(
literal|"http://cxf.apache.org/w2j/hello_world_soap_http/types"
argument_list|,
literal|"org.apache.types"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"org directory is not found"
argument_list|,
name|org
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|apache
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"apache"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"apache directory is not found"
argument_list|,
name|apache
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|types
init|=
operator|new
name|File
argument_list|(
name|apache
argument_list|,
literal|"types"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"types directory is not found"
argument_list|,
name|types
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.types.GreetMe"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"Generate "
operator|+
name|clz
operator|.
name|getName
argument_list|()
operator|+
literal|"error"
argument_list|,
name|Modifier
operator|.
name|isPublic
argument_list|(
name|clz
operator|.
name|getModifiers
argument_list|()
argument_list|)
argument_list|)
expr_stmt|;
name|clz
operator|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.Greeter"
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testNamespacePackageMapping3
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_PACKAGENAME
argument_list|,
literal|"org.cxf"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|org
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|cxf
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"cxf"
argument_list|)
decl_stmt|;
name|File
index|[]
name|files
init|=
name|cxf
operator|.
name|listFiles
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
literal|25
argument_list|,
name|files
operator|.
name|length
argument_list|)
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.cxf.Greeter"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"Generate "
operator|+
name|clz
operator|.
name|getName
argument_list|()
operator|+
literal|"error"
argument_list|,
name|clz
operator|.
name|isInterface
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testBug305772
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ANT
argument_list|,
name|ToolConstants
operator|.
name|CFG_ANT
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|,
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug305772/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Path
name|path
init|=
name|FileSystems
operator|.
name|getDefault
argument_list|()
operator|.
name|getPath
argument_list|(
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|,
literal|"build.xml"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|Files
operator|.
name|isReadable
argument_list|(
name|path
argument_list|)
argument_list|)
expr_stmt|;
name|String
name|content
init|=
operator|new
name|String
argument_list|(
name|Files
operator|.
name|readAllBytes
argument_list|(
name|path
argument_list|)
argument_list|,
name|StandardCharsets
operator|.
name|UTF_8
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"wsdl location should be url style in build.xml"
argument_list|,
name|content
operator|.
name|indexOf
argument_list|(
literal|"param1=\"file:"
argument_list|)
operator|>
operator|-
literal|1
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testExcludeNSWithPackageName
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-nexclude"
block|,
literal|"http://apache.org/test/types=com.iona"
block|,
literal|"-nexclude"
block|,
literal|"http://apache.org/Invoice"
block|,
literal|"-compile"
block|,
literal|"-classdir"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world_exclude.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|com
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"com"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
literal|"Generated file has been excluded"
argument_list|,
name|com
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|iona
init|=
operator|new
name|File
argument_list|(
name|com
argument_list|,
literal|"iona"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
literal|"Generated file has been excluded"
argument_list|,
name|iona
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|implFile
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/Greeter.java"
argument_list|)
decl_stmt|;
name|String
name|str
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
name|implFile
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"com.iona.BareDocumentResponse"
argument_list|)
argument_list|)
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|File
name|apache
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"apache"
argument_list|)
decl_stmt|;
name|File
name|invoice
init|=
operator|new
name|File
argument_list|(
name|apache
argument_list|,
literal|"Invoice"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
literal|"Generated file has been excluded"
argument_list|,
name|invoice
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testExcludeNSWithPackageNameViaMain
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-nexclude"
block|,
literal|"http://apache.org/test/types=com.iona"
block|,
literal|"-nexclude"
block|,
literal|"http://apache.org/Invoice"
block|,
literal|"-compile"
block|,
literal|"-classdir"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world_exclude.wsdl"
argument_list|)
block|}
decl_stmt|;
name|WSDLToJava
operator|.
name|main
argument_list|(
name|args
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|com
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"com"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
literal|"Generated file has been excluded"
argument_list|,
name|com
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|iona
init|=
operator|new
name|File
argument_list|(
name|com
argument_list|,
literal|"iona"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
literal|"Generated file has been excluded"
argument_list|,
name|iona
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|implFile
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/Greeter.java"
argument_list|)
decl_stmt|;
name|String
name|str
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
name|implFile
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"com.iona.BareDocumentResponse"
argument_list|)
argument_list|)
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|File
name|apache
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"apache"
argument_list|)
decl_stmt|;
name|File
name|invoice
init|=
operator|new
name|File
argument_list|(
name|apache
argument_list|,
literal|"Invoice"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
literal|"Generated file has been excluded"
argument_list|,
name|invoice
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testExcludeNSWithoutPackageName
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-nexclude"
block|,
literal|"http://apache.org/test/types"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world_exclude.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|com
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"test"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
literal|"Generated file has been excluded"
argument_list|,
name|com
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCommandLine
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-compile"
block|,
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-classdir"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
block|,
literal|"-p"
block|,
literal|"org.cxf"
block|,
literal|"-p"
block|,
literal|"http://apache.org/hello_world_soap_http/types=org.apache.types"
block|,
literal|"-server"
block|,
literal|"-impl"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.cxf.Greeter"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"Generate "
operator|+
name|clz
operator|.
name|getName
argument_list|()
operator|+
literal|"error"
argument_list|,
name|clz
operator|.
name|isInterface
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testDefaultLoadNSMappingOFF
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-dns"
block|,
literal|"false"
block|,
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-noAddressBinding"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/basic_callback.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|org
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|w3
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"w3"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|w3
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|p2005
init|=
operator|new
name|File
argument_list|(
name|w3
argument_list|,
literal|"_2005"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|p2005
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|p08
init|=
operator|new
name|File
argument_list|(
name|p2005
argument_list|,
literal|"_08"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|p08
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|address
init|=
operator|new
name|File
argument_list|(
name|p08
argument_list|,
literal|"addressing"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|address
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
index|[]
name|files
init|=
name|address
operator|.
name|listFiles
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
literal|11
argument_list|,
name|files
operator|.
name|length
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testDefaultLoadNSMappingON
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-noAddressBinding"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/basic_callback.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|org
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|apache
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"apache"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|apache
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|cxf
init|=
operator|new
name|File
argument_list|(
name|apache
argument_list|,
literal|"cxf"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|cxf
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|ws
init|=
operator|new
name|File
argument_list|(
name|cxf
argument_list|,
literal|"ws"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|ws
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|address
init|=
operator|new
name|File
argument_list|(
name|ws
argument_list|,
literal|"addressing"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|address
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
index|[]
name|files
init|=
name|address
operator|.
name|listFiles
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
literal|11
argument_list|,
name|files
operator|.
name|length
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testBug305924ForNestedBinding
parameter_list|()
block|{
try|try
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-all"
block|,
literal|"-compile"
block|,
literal|"-classdir"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
block|,
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-b"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug305924/binding2.xml"
argument_list|)
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug305924/hello_world.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{ }
try|try
block|{
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.types.CreateProcess$MyProcess"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Customization binding code should be generated"
argument_list|,
name|clz
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|ClassNotFoundException
name|e
parameter_list|)
block|{
name|fail
argument_list|(
literal|"Can not load the inner class MyProcess, the customization failed: \n"
operator|+
name|e
operator|.
name|getMessage
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testBug305924ForExternalBinding
parameter_list|()
block|{
try|try
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-all"
block|,
literal|"-compile"
block|,
literal|"-classdir"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
block|,
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-b"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug305924/binding1.xml"
argument_list|)
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug305924/hello_world.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|e
operator|.
name|printStackTrace
argument_list|(
name|System
operator|.
name|err
argument_list|)
expr_stmt|;
block|}
try|try
block|{
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.types.CreateProcess$MyProcess"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Customization binding code should be generated"
argument_list|,
name|clz
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|ClassNotFoundException
name|e
parameter_list|)
block|{
name|e
operator|.
name|printStackTrace
argument_list|()
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testLocatorWithJaxbBinding
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/locator_with_jaxbbinding.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testWsdlNoService
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/helloworld_withnoservice.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_VALIDATE_WSDL
argument_list|)
expr_stmt|;
comment|//no binding/service
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testNoServiceImport
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/helloworld_noservice_import.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|cls
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world1.Greeter"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
name|cls
argument_list|)
expr_stmt|;
name|cls
operator|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world2.Greeter2"
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testServiceNS
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|,
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug321/hello_world_different_ns_service.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.service.SOAPServiceTest1"
argument_list|)
decl_stmt|;
name|WebServiceClient
name|webServiceClient
init|=
name|AnnotationUtil
operator|.
name|getPrivClassAnnotation
argument_list|(
name|clz
argument_list|,
name|WebServiceClient
operator|.
name|class
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"http://cxf.apache.org/w2j/hello_world_soap_http/service"
argument_list|,
name|webServiceClient
operator|.
name|targetNamespace
argument_list|()
argument_list|)
expr_stmt|;
name|String
name|file
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/Greeter_SoapPortTest1_Client.java"
argument_list|)
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"Service QName in client is not correct"
argument_list|,
name|file
operator|.
name|contains
argument_list|(
literal|"new QName(\"http://cxf.apache.org/w2j/hello_world_soap_http/service\", \"SOAPService_Test1\")"
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testNoServiceNOPortType
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|,
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/no_port_or_service.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.no_port_or_service.types.TheComplexType"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
name|clz
argument_list|)
expr_stmt|;
block|}
comment|// CXF-492
annotation|@
name|Test
specifier|public
name|void
name|testDefaultNsMap
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|,
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_NO_ADDRESS_BINDING
argument_list|,
name|ToolConstants
operator|.
name|CFG_NO_ADDRESS_BINDING
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf492/locator.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"org directory is not exist"
argument_list|,
name|org
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|apache
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"apache"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|apache
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|cxf
init|=
operator|new
name|File
argument_list|(
name|apache
argument_list|,
literal|"cxf"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|cxf
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|ws
init|=
operator|new
name|File
argument_list|(
name|cxf
argument_list|,
literal|"ws"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|ws
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|address
init|=
operator|new
name|File
argument_list|(
name|ws
argument_list|,
literal|"addressing"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|address
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testDefaultNsMapExclude
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|,
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_NEXCLUDE
argument_list|,
literal|"http://www.w3.org/2005/08/addressing=org.apache.cxf.ws.addressing"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf492/locator.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"org directory is not exist"
argument_list|,
name|org
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|apache
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"apache"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|apache
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|ws
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/ws/addressing"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
name|ws
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|orginal
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org.w3._2005._08.addressing"
argument_list|)
decl_stmt|;
name|assertFalse
argument_list|(
name|orginal
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testHelloWorldExternalBindingFile
parameter_list|()
throws|throws
name|Exception
block|{
name|Server
name|server
init|=
operator|new
name|Server
argument_list|(
literal|0
argument_list|)
decl_stmt|;
try|try
block|{
name|ResourceHandler
name|reshandler
init|=
operator|new
name|ResourceHandler
argument_list|()
decl_stmt|;
name|reshandler
operator|.
name|setResourceBase
argument_list|(
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/"
argument_list|)
argument_list|)
expr_stmt|;
comment|// this is the only handler we're supposed to need, so we don't need to
comment|// 'add' it.
name|server
operator|.
name|setHandler
argument_list|(
name|reshandler
argument_list|)
expr_stmt|;
name|server
operator|.
name|start
argument_list|()
expr_stmt|;
name|Thread
operator|.
name|sleep
argument_list|(
literal|250
argument_list|)
expr_stmt|;
comment|//give network connector a little time to spin up
name|int
name|port
init|=
operator|(
operator|(
name|NetworkConnector
operator|)
name|server
operator|.
name|getConnectors
argument_list|()
index|[
literal|0
index|]
operator|)
operator|.
name|getLocalPort
argument_list|()
decl_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
literal|"http://localhost:"
operator|+
name|port
operator|+
literal|"/hello_world.wsdl"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
literal|"http://localhost:"
operator|+
name|port
operator|+
literal|"/remote-hello_world_binding.xsd"
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|reshandler
operator|.
name|stop
argument_list|()
expr_stmt|;
block|}
finally|finally
block|{
name|server
operator|.
name|stop
argument_list|()
expr_stmt|;
name|server
operator|.
name|destroy
argument_list|()
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testDefaultNSWithPkg
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-p"
block|,
literal|"org.cxf"
block|,
literal|"-noAddressBinding"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/basic_callback.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|org
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|org
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|apache
init|=
operator|new
name|File
argument_list|(
name|org
argument_list|,
literal|"apache"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|apache
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|cxf
init|=
operator|new
name|File
argument_list|(
name|apache
argument_list|,
literal|"cxf"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|cxf
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|ws
init|=
operator|new
name|File
argument_list|(
name|cxf
argument_list|,
literal|"ws"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|ws
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|address
init|=
operator|new
name|File
argument_list|(
name|ws
argument_list|,
literal|"addressing"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|address
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|File
index|[]
name|files
init|=
name|address
operator|.
name|listFiles
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
literal|11
argument_list|,
name|files
operator|.
name|length
argument_list|)
expr_stmt|;
name|cxf
operator|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/cxf"
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|cxf
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|files
operator|=
name|cxf
operator|.
name|listFiles
argument_list|()
expr_stmt|;
name|assertEquals
argument_list|(
literal|5
argument_list|,
name|files
operator|.
name|length
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF677
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-b"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello-mime-binding.xml"
argument_list|)
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello-mime.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|String
name|str1
init|=
literal|"SOAPBinding.ParameterStyle.BARE"
decl_stmt|;
name|String
name|str2
init|=
literal|"javax.xml.ws.Holder"
decl_stmt|;
name|String
name|str3
init|=
literal|"org.apache.cxf.mime.Address"
decl_stmt|;
name|String
name|str4
init|=
literal|"http://cxf.apache.org/w2j/hello_world_mime/types"
decl_stmt|;
name|String
name|file
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
operator|new
name|File
argument_list|(
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/org/apache/cxf/w2j/hello_world_mime/Hello.java"
argument_list|)
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|file
operator|.
name|contains
argument_list|(
name|str1
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|file
operator|.
name|contains
argument_list|(
name|str2
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|file
operator|.
name|contains
argument_list|(
name|str3
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|file
operator|.
name|contains
argument_list|(
name|str4
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testWebResult
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/sayHi.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|String
name|results
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
operator|new
name|File
argument_list|(
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|,
literal|"org/apache/sayhi/SayHi.java"
argument_list|)
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|results
operator|.
name|contains
argument_list|(
literal|"@WebResult(name = \"return\", "
operator|+
literal|"targetNamespace = \"http://apache.org/sayHi\")"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|results
operator|.
name|contains
argument_list|(
literal|"@WebResult(name = \"return\", targetNamespace = \"\")"
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF627
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug627/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug627/async_binding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
try|try
block|{
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|ex
parameter_list|)
block|{
comment|// ignore
block|}
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.Greeter"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|3
argument_list|,
name|clz
operator|.
name|getDeclaredMethods
argument_list|()
operator|.
name|length
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
comment|// Test for CXF-765
specifier|public
name|void
name|testClientServer
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug765/hello_world_ports.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|)
expr_stmt|;
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_IMPL
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_GEN_SERVER
argument_list|,
name|ToolConstants
operator|.
name|CFG_GEN_SERVER
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_GEN_CLIENT
argument_list|,
name|ToolConstants
operator|.
name|CFG_GEN_CLIENT
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|file
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|Arrays
operator|.
name|asList
argument_list|(
name|file
operator|.
name|list
argument_list|()
argument_list|)
operator|.
name|toString
argument_list|()
argument_list|,
literal|4
argument_list|,
name|file
operator|.
name|list
argument_list|()
operator|.
name|length
argument_list|)
expr_stmt|;
name|file
operator|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/DocLitBare_DocLitBarePort_Client.java"
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
literal|"DocLitBare_DocLitBarePort_Client is not found"
argument_list|,
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|file
operator|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/DocLitBare_DocLitBarePort_Server.java"
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
literal|"DocLitBare_DocLitBarePort_Server is not found"
argument_list|,
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|file
operator|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/Greeter_GreeterPort_Client.java"
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
literal|"Greeter_GreeterPort_Client is not found"
argument_list|,
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|file
operator|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/Greeter_GreeterPort_Server.java"
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
literal|"Greeter_GreeterPort_Server is not found"
argument_list|,
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testRecursiveImport
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf778/hello_world_recursive.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_VALIDATE_WSDL
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|assertNotNull
argument_list|(
literal|"Process recursive import wsdl error "
argument_list|,
name|output
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF804
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf804/hello_world_contains_import.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
comment|// env.put(ToolConstants.CFG_SERVICENAME, "SOAPService");
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|file
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/MyService.java"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"MyService is not found"
argument_list|,
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testDefinieServiceName
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf804/hello_world_contains_import.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_SERVICENAME
argument_list|,
literal|"SOAPService"
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|file
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/SOAPService.java"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"SOAPService is not found"
argument_list|,
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|file
operator|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/MyService.java"
argument_list|)
expr_stmt|;
name|assertFalse
argument_list|(
literal|"MyService should not be generated"
argument_list|,
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF805
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf805/hello_world_with_typo.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|,
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|fail
argument_list|(
literal|"exception should be thrown"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|String
name|expectedErrorMsg
init|=
literal|"Part<in> in Message "
operator|+
literal|"<{http://cxf.apache.org/w2j/hello_world_soap_http}greetMeRequest> referenced Type "
operator|+
literal|"<{http://cxf.apache.org/w2j/hello_world_soap_http/types}greetMee> can not be "
operator|+
literal|"found in the schemas"
decl_stmt|;
name|assertTrue
argument_list|(
literal|"Fail to create java parameter exception should be thrown"
argument_list|,
name|e
operator|.
name|getMessage
argument_list|()
operator|.
name|indexOf
argument_list|(
name|expectedErrorMsg
argument_list|)
operator|>
operator|-
literal|1
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testAntFile
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ANT
argument_list|,
name|ToolConstants
operator|.
name|CFG_ANT
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_SERVICENAME
argument_list|,
literal|"SOAPService_Test1"
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|file
init|=
operator|new
name|File
argument_list|(
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/build.xml"
argument_list|)
decl_stmt|;
name|String
name|str
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
name|file
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.Greeter_SoapPortTest1_Client"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.Greeter_SoapPortTest2_Client"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.Greeter_SoapPortTest1_Server"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.Greeter_SoapPortTest2_Server"
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testNonUniqueBody
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf939/bug.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_VALIDATE_WSDL
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|String
name|ns
init|=
literal|"http://bugs.cxf/services/bug1"
decl_stmt|;
name|QName
name|bug1
init|=
operator|new
name|QName
argument_list|(
name|ns
argument_list|,
literal|"myBug1"
argument_list|)
decl_stmt|;
name|QName
name|bug2
init|=
operator|new
name|QName
argument_list|(
name|ns
argument_list|,
literal|"myBug2"
argument_list|)
decl_stmt|;
name|Message
name|msg1
init|=
operator|new
name|Message
argument_list|(
literal|"NON_UNIQUE_BODY"
argument_list|,
name|UniqueBodyValidator
operator|.
name|LOG
argument_list|,
name|bug1
argument_list|,
name|bug1
argument_list|,
name|bug2
argument_list|,
name|bug1
argument_list|)
decl_stmt|;
name|Message
name|msg2
init|=
operator|new
name|Message
argument_list|(
literal|"NON_UNIQUE_BODY"
argument_list|,
name|UniqueBodyValidator
operator|.
name|LOG
argument_list|,
name|bug1
argument_list|,
name|bug2
argument_list|,
name|bug1
argument_list|,
name|bug1
argument_list|)
decl_stmt|;
name|boolean
name|boolA
init|=
name|msg1
operator|.
name|toString
argument_list|()
operator|.
name|trim
argument_list|()
operator|.
name|equals
argument_list|(
name|e
operator|.
name|getMessage
argument_list|()
operator|.
name|trim
argument_list|()
argument_list|)
decl_stmt|;
name|boolean
name|boolB
init|=
name|msg2
operator|.
name|toString
argument_list|()
operator|.
name|trim
argument_list|()
operator|.
name|equals
argument_list|(
name|e
operator|.
name|getMessage
argument_list|()
operator|.
name|trim
argument_list|()
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|boolA
operator|||
name|boolB
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testWrapperStyleNameCollision
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf918/bug.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|String
name|ns1
init|=
literal|"http://bugs.cxf/services/bug1"
decl_stmt|;
name|String
name|ns2
init|=
literal|"http://www.w3.org/2001/XMLSchema"
decl_stmt|;
name|QName
name|elementName
init|=
operator|new
name|QName
argument_list|(
name|ns1
argument_list|,
literal|"theSameNameFieldDifferentDataType"
argument_list|)
decl_stmt|;
name|QName
name|stringName
init|=
operator|new
name|QName
argument_list|(
name|ns2
argument_list|,
literal|"string"
argument_list|)
decl_stmt|;
name|QName
name|intName
init|=
operator|new
name|QName
argument_list|(
name|ns2
argument_list|,
literal|"int"
argument_list|)
decl_stmt|;
name|Message
name|msg
init|=
operator|new
name|Message
argument_list|(
literal|"WRAPPER_STYLE_NAME_COLLISION"
argument_list|,
name|UniqueBodyValidator
operator|.
name|LOG
argument_list|,
name|elementName
argument_list|,
name|stringName
argument_list|,
name|intName
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|msg
operator|.
name|toString
argument_list|()
operator|.
name|trim
argument_list|()
argument_list|,
name|e
operator|.
name|getMessage
argument_list|()
operator|.
name|trim
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testNonWrapperStyleNameCollision
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf918/bug2.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|fail
argument_list|(
literal|"The cxf918/bug2.wsdl should not have generated code"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|assertTrue
argument_list|(
name|e
operator|.
name|getMessage
argument_list|()
argument_list|,
name|e
operator|.
name|getMessage
argument_list|()
operator|.
name|contains
argument_list|(
literal|"theSameNameFieldDifferentDataType"
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testParameterOrderNoOutputMessage
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug967.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|fail
argument_list|(
literal|"The cxf967.wsdl is a valid wsdl, should pass the test, caused by: "
operator|+
name|e
operator|.
name|getMessage
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testParameterOrderDifferentNS
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/bug978/bug.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|String
name|results
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/tempuri/GreeterRPCLit.java"
argument_list|)
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|results
operator|.
name|contains
argument_list|(
literal|"@WebParam(partName = \"inInt\", name = \"inInt\")"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|results
operator|.
name|contains
argument_list|(
literal|"Style.RPC"
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testAsyncImplAndClient
parameter_list|()
throws|throws
name|Exception
block|{
comment|// CXF994
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|,
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf994/hello_world_async.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf994/async.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testZeroInputOutOfBandHeader
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1001.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_EXTRA_SOAPHEADER
argument_list|,
literal|"TRUE"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|,
name|ToolConstants
operator|.
name|CFG_CLIENT
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|String
name|results
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
operator|new
name|File
argument_list|(
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|,
literal|"soapinterface/ems/esendex/com/AccountServiceSoap.java"
argument_list|)
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|results
operator|.
name|contains
argument_list|(
literal|"public int getMessageLimit"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|results
operator|.
name|contains
argument_list|(
literal|"name = \"MessengerHeader"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|results
operator|.
name|contains
argument_list|(
literal|"header = true"
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testBindingForImportWSDL
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1095/hello_world_services.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
operator|new
name|String
index|[]
block|{
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1095/binding.xml"
argument_list|)
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1095/binding1.xml"
argument_list|)
block|}
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world.messages.CustomizedFault"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Customization Fault Class is not generated"
argument_list|,
name|clz
argument_list|)
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|serviceClz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world.services.CustomizedService"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Customization Fault Class is not generated"
argument_list|,
name|serviceClz
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testReuseJaxwsBindingFile
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1094/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1094/async_binding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.Greeter"
argument_list|)
decl_stmt|;
name|Method
name|method1
init|=
name|clz
operator|.
name|getMethod
argument_list|(
literal|"greetMeSometimeAsync"
argument_list|,
operator|new
name|Class
index|[]
block|{
name|java
operator|.
name|lang
operator|.
name|String
operator|.
name|class
block|,
name|javax
operator|.
name|xml
operator|.
name|ws
operator|.
name|AsyncHandler
operator|.
name|class
block|}
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"jaxws binding file does not take effect for hello_world.wsdl"
argument_list|,
name|method1
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1094/echo_date.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1094/async_binding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|clz
operator|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.tools.fortest.date.EchoDate"
argument_list|)
expr_stmt|;
name|Method
name|method2
init|=
name|clz
operator|.
name|getMethod
argument_list|(
literal|"echoDateAsync"
argument_list|,
operator|new
name|Class
index|[]
block|{
name|javax
operator|.
name|xml
operator|.
name|datatype
operator|.
name|XMLGregorianCalendar
operator|.
name|class
block|,
name|javax
operator|.
name|xml
operator|.
name|ws
operator|.
name|AsyncHandler
operator|.
name|class
block|}
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"jaxws binding file does not take effect for echo_date.wsdl"
argument_list|,
name|method2
argument_list|)
expr_stmt|;
block|}
comment|// See CXF-2135
annotation|@
name|Test
specifier|public
name|void
name|testReuseJaxbBindingFile1
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1094/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1094/jaxbbinding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.types.CreateProcess$MyProcess"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Failed to generate customized class for hello_world.wsdl"
argument_list|,
name|clz
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1094/hello_world_oneway.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1094/jaxbbinding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|customizedClz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.oneway.types.CreateProcess$MyProcess"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Failed to generate customized class for hello_world_oneway.wsdl"
argument_list|,
name|customizedClz
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testBindingXPath
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1106/binding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.Greeter"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Failed to generate SEI class"
argument_list|,
name|clz
argument_list|)
expr_stmt|;
name|Method
index|[]
name|methods
init|=
name|clz
operator|.
name|getMethods
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
literal|"jaxws binding file parse error, number of generated method is not expected"
argument_list|,
literal|14
argument_list|,
name|methods
operator|.
name|length
argument_list|)
expr_stmt|;
name|boolean
name|existSayHiAsyn
init|=
literal|false
decl_stmt|;
for|for
control|(
name|Method
name|m
range|:
name|methods
control|)
block|{
if|if
condition|(
literal|"sayHiAsyn"
operator|.
name|equals
argument_list|(
name|m
operator|.
name|getName
argument_list|()
argument_list|)
condition|)
block|{
name|existSayHiAsyn
operator|=
literal|true
expr_stmt|;
block|}
block|}
name|assertFalse
argument_list|(
literal|"sayHiAsyn method should not be generated"
argument_list|,
name|existSayHiAsyn
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testJaxbCatalog
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1112/myservice.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CATALOG
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1112/catalog.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1112/jaxbbinding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.mytest.ObjectFactory"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Customization types class should be generated"
argument_list|,
name|clz
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCatalog2
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
literal|"http://example.org/wsdl"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CATALOG
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1112/jax-ws-catalog.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1112/binding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_VALIDATE_WSDL
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCatalog3
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
literal|"http://example.org/wsdl"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CATALOG
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1112/jax-ws-catalog2.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1112/binding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|remove
argument_list|(
name|ToolConstants
operator|.
name|CFG_VALIDATE_WSDL
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testServer
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/InvoiceServer.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
operator|new
name|String
index|[]
block|{
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1141/jaxws.xml"
argument_list|)
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1141/jaxb.xml"
argument_list|)
block|}
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|file
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/mytest"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|13
argument_list|,
name|file
operator|.
name|list
argument_list|()
operator|.
name|length
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCxf1137
parameter_list|()
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1137/helloWorld.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|fail
argument_list|(
literal|"The wsdl is not a valid wsdl, see cxf-1137"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|assertTrue
argument_list|(
name|e
operator|.
name|getMessage
argument_list|()
operator|.
name|indexOf
argument_list|(
literal|"Summary: Failures: 5, Warnings: 0"
argument_list|)
operator|!=
operator|-
literal|1
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testTwoJaxwsBindingFile
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
operator|new
name|String
index|[]
block|{
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1152/jaxws1.xml"
argument_list|)
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1152/jaxws2.xml"
argument_list|)
block|}
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|File
name|file
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/mypkg"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|25
argument_list|,
name|file
operator|.
name|listFiles
argument_list|()
operator|.
name|length
argument_list|)
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.mypkg.MyService"
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Customized service class is not found"
argument_list|,
name|clz
argument_list|)
expr_stmt|;
name|clz
operator|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.mypkg.MyGreeter"
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
literal|"Customized SEI class is not found"
argument_list|,
name|clz
argument_list|)
expr_stmt|;
name|Method
name|customizedMethod
init|=
name|clz
operator|.
name|getMethod
argument_list|(
literal|"myGreetMe"
argument_list|,
operator|new
name|Class
index|[]
block|{
name|String
operator|.
name|class
block|}
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Customized method 'myGreetMe' in MyGreeter.class is not found"
argument_list|,
name|customizedMethod
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testJaxwsBindingJavaDoc
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1152/jaxws1.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|List
argument_list|<
name|String
argument_list|>
name|results1
init|=
name|FileUtils
operator|.
name|readLines
argument_list|(
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/mypkg/MyGreeter.java"
argument_list|)
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|results1
operator|.
name|contains
argument_list|(
literal|" * this is package javadoc"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|results1
operator|.
name|contains
argument_list|(
literal|" * this is class javadoc"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|results1
operator|.
name|contains
argument_list|(
literal|" * this is method javadoc"
argument_list|)
argument_list|)
expr_stmt|;
name|List
argument_list|<
name|String
argument_list|>
name|results2
init|=
name|FileUtils
operator|.
name|readLines
argument_list|(
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/mypkg/SOAPServiceTest1.java"
argument_list|)
argument_list|)
decl_stmt|;
name|boolean
name|match1
init|=
literal|false
decl_stmt|;
name|boolean
name|match2
init|=
literal|false
decl_stmt|;
for|for
control|(
name|String
name|str
range|:
name|results2
control|)
block|{
if|if
condition|(
name|str
operator|.
name|contains
argument_list|(
literal|"package javadoc"
argument_list|)
condition|)
block|{
name|match1
operator|=
literal|true
expr_stmt|;
block|}
if|if
condition|(
name|str
operator|.
name|contains
argument_list|(
literal|"service class javadoc"
argument_list|)
condition|)
block|{
name|match2
operator|=
literal|true
expr_stmt|;
block|}
block|}
name|assertTrue
argument_list|(
name|results1
operator|.
name|toString
argument_list|()
argument_list|,
name|match1
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|results2
operator|.
name|toString
argument_list|()
argument_list|,
name|match2
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testWSAActionAnno
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1209/hello_world_fault.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF964
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf964/hello_world_fault.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.intfault.BadRecordLitFault"
argument_list|)
decl_stmt|;
name|WebFault
name|webFault
init|=
name|AnnotationUtil
operator|.
name|getPrivClassAnnotation
argument_list|(
name|clz
argument_list|,
name|WebFault
operator|.
name|class
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"int"
argument_list|,
name|webFault
operator|.
name|name
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF1620
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/jaxb_custom_extensors.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/jaxb_custom_extensors.xjb"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.jaxb_custom_ext.types.Foo"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|3
argument_list|,
name|clz
operator|.
name|getDeclaredFields
argument_list|()
operator|.
name|length
argument_list|)
expr_stmt|;
name|clz
operator|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.jaxb_custom_ext.types.Foo2"
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|1
argument_list|,
name|clz
operator|.
name|getDeclaredFields
argument_list|()
operator|.
name|length
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF1048
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_IMPL
argument_list|,
name|ToolConstants
operator|.
name|CFG_IMPL
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1048/test.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|clz
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.hello_world_soap_http.PingSoapPortImpl"
argument_list|)
decl_stmt|;
name|WebService
name|webServiceAnn
init|=
name|AnnotationUtil
operator|.
name|getPrivClassAnnotation
argument_list|(
name|clz
argument_list|,
name|WebService
operator|.
name|class
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
literal|"org.apache.hello_world_soap_http.Ping"
argument_list|,
name|webServiceAnn
operator|.
name|endpointInterface
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|"GreeterSOAPService"
argument_list|,
name|webServiceAnn
operator|.
name|serviceName
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|"PingSoapPort"
argument_list|,
name|webServiceAnn
operator|.
name|portName
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF1694
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1694/test.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|ex
parameter_list|)
block|{
name|assertTrue
argument_list|(
name|ex
operator|.
name|getMessage
argument_list|()
operator|.
name|contains
argument_list|(
literal|"{http://child/}Binding is not correct"
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF1662
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-p"
block|,
literal|"org.cxf"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1662/test.wsdl"
argument_list|)
block|}
decl_stmt|;
try|try
block|{
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|ToolException
name|tex
parameter_list|)
block|{
name|assertTrue
argument_list|(
name|tex
operator|.
name|getMessage
argument_list|()
operator|.
name|contains
argument_list|(
literal|" -p option cannot be used when "
operator|+
literal|"wsdl contains mutiple schemas"
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|String
index|[]
name|args2
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-p"
block|,
literal|"org.cxf"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1662/test2.wsdl"
argument_list|)
block|}
decl_stmt|;
try|try
block|{
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args2
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|ToolException
name|tex
parameter_list|)
block|{
name|assertNull
argument_list|(
name|tex
argument_list|)
expr_stmt|;
block|}
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|file
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/cxf/package-info.java"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|String
name|str
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
name|file
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"http://child/xsd"
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testMultiXjcArgs
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-xjc-Xlocator"
block|,
literal|"-xjc-Xsync-methods"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|File
name|file
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/types/SayHi.java"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|file
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|String
name|str
init|=
name|TestFileUtils
operator|.
name|getStringFromFile
argument_list|(
name|file
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"@XmlLocation"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|str
operator|.
name|contains
argument_list|(
literal|"synchronized"
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF1939
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-impl"
block|,
literal|"-server"
block|,
literal|"-client"
block|,
literal|"-autoNameResolution"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf1939/hello_world.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/Soap_PortImpl.java"
argument_list|)
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/SoapPortImpl.java"
argument_list|)
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/TestServiceName.java"
argument_list|)
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/TestServiceName1.java"
argument_list|)
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF3105
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
literal|"-impl"
block|,
literal|"-server"
block|,
literal|"-client"
block|,
literal|"-b"
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf3105/ws-binding.xml"
argument_list|)
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf3105/cxf3105.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|f
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/testcase/cxf3105/Login.java"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|f
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
name|String
name|contents
init|=
name|IOUtils
operator|.
name|readStringFromStream
argument_list|(
operator|new
name|FileInputStream
argument_list|(
name|f
argument_list|)
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|contents
operator|.
name|contains
argument_list|(
literal|"Loginrequesttype loginRequest"
argument_list|)
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|contents
operator|.
name|contains
argument_list|(
literal|"<Loginresponsetype> loginResponse"
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testOverloadWithAction
parameter_list|()
throws|throws
name|Exception
block|{
name|String
index|[]
name|args
init|=
operator|new
name|String
index|[]
block|{
literal|"-d"
block|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
block|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world_overload.wsdl"
argument_list|)
block|}
decl_stmt|;
name|CommandInterfaceUtils
operator|.
name|commandCommonMain
argument_list|()
expr_stmt|;
name|WSDLToJava
name|w2j
init|=
operator|new
name|WSDLToJava
argument_list|(
name|args
argument_list|)
decl_stmt|;
name|w2j
operator|.
name|run
argument_list|(
operator|new
name|ToolContext
argument_list|()
argument_list|)
expr_stmt|;
name|assertNotNull
argument_list|(
name|output
argument_list|)
expr_stmt|;
name|File
name|f
init|=
operator|new
name|File
argument_list|(
name|output
argument_list|,
literal|"org/apache/cxf/w2j/hello_world_soap_http/SayHi.java"
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
name|f
operator|.
name|exists
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF3290
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf-3290/bug.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|cls
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.bugs3290.services.bug1.MyBugService"
argument_list|)
decl_stmt|;
name|Method
name|m
init|=
name|cls
operator|.
name|getMethod
argument_list|(
literal|"getMyBug1"
argument_list|)
decl_stmt|;
name|assertEquals
argument_list|(
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.bugs3290.services.bug2.MyBugService"
argument_list|)
argument_list|,
name|m
operator|.
name|getReturnType
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF3353andCXF3491
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|,
literal|"all"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf3353/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|fail
argument_list|(
literal|"shouldn't get exception"
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF4128
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|,
literal|"all"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf4128/cxf4128.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|fail
argument_list|(
literal|"shouldn't get exception"
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF4452
parameter_list|()
throws|throws
name|Exception
block|{
try|try
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_BINDING
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf4452/binding.xml"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|fail
argument_list|(
literal|"shouldn't get exception"
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testCXF5280
parameter_list|()
throws|throws
name|Exception
block|{
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_ALL
argument_list|,
literal|"all"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_COMPILE
argument_list|,
literal|"compile"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_OUTPUTDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_CLASSDIR
argument_list|,
name|output
operator|.
name|getCanonicalPath
argument_list|()
operator|+
literal|"/classes"
argument_list|)
expr_stmt|;
name|env
operator|.
name|put
argument_list|(
name|ToolConstants
operator|.
name|CFG_WSDLURL
argument_list|,
name|getLocation
argument_list|(
literal|"/wsdl2java_wsdl/cxf5280/hello_world.wsdl"
argument_list|)
argument_list|)
expr_stmt|;
name|processor
operator|.
name|setContext
argument_list|(
name|env
argument_list|)
expr_stmt|;
name|processor
operator|.
name|execute
argument_list|()
expr_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|pcls
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.Greeter"
argument_list|)
decl_stmt|;
name|Class
argument_list|<
name|?
argument_list|>
name|acls
init|=
name|classLoader
operator|.
name|loadClass
argument_list|(
literal|"org.apache.cxf.w2j.hello_world_soap_http.types.GreetMe"
argument_list|)
decl_stmt|;
name|Method
name|m
init|=
name|pcls
operator|.
name|getMethod
argument_list|(
literal|"greetMe"
argument_list|,
operator|new
name|Class
index|[]
block|{
name|acls
block|}
argument_list|)
decl_stmt|;
name|Action
name|actionAnn
init|=
name|AnnotationUtil
operator|.
name|getPrivMethodAnnotation
argument_list|(
name|m
argument_list|,
name|Action
operator|.
name|class
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
name|actionAnn
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|"http://cxf.apache.org/w2j/hello_world_soap_http/greetMe"
argument_list|,
name|actionAnn
operator|.
name|input
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
| 14.735071 | 810 | 0.804944 |
41d78ea53c53e2e3829435ad67485619279ea52a | 7,167 | package io.joyrpc.transport.channel;
/*-
* #%L
* joyrpc
* %%
* Copyright (C) 2019 joyrpc.io
* %%
* 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.
* #L%
*/
import io.joyrpc.exception.ChannelClosedException;
import io.joyrpc.transport.session.Session;
import io.joyrpc.util.SystemClock;
import io.joyrpc.util.Timer.TimeTask;
import io.joyrpc.util.Timer.Timeout;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static io.joyrpc.constants.Constants.FUTURE_TIMEOUT_PREFIX;
import static io.joyrpc.util.Timer.timer;
/**
* Future管理器,绑定到Channel上
*/
public class FutureManager<I, M> {
/**
* 通道
*/
protected Channel channel;
/**
* ID生成器
*/
protected Supplier<I> idGenerator;
/**
* 计数器
*/
protected AtomicInteger counter = new AtomicInteger();
/**
* 消费者
*/
protected Consumer<I> timeout;
/**
* Future管理,有些连接并发很少不需要初始化
*/
protected Map<I, RequestFuture<I, M>> futures = new ConcurrentHashMap<>();
/**
* 构造函数
*
* @param channel 连接通道
* @param idGenerator id生成器
*/
public FutureManager(final Channel channel, final Supplier<I> idGenerator) {
this.channel = channel;
this.idGenerator = idGenerator;
this.timeout = id -> complete(id, null, new TimeoutException("future is timeout."));
}
/**
* 创建一个future
*
* @param messageId 消息ID
* @param timeoutMillis 超时时间(毫秒)
* @param afterRun 结束后执行
* @return 完成状态
*/
public RequestFuture<I, M> create(final I messageId,
final long timeoutMillis,
final BiConsumer<M, Throwable> afterRun) {
return create(messageId, timeoutMillis, null, null, afterRun);
}
/**
* 创建一个future
*
* @param messageId 消息ID
* @param timeoutMillis 超时时间
* @param session 会话
* @param requests 正在处理的请求数
* @return 完成状态
*/
public RequestFuture<I, M> create(final I messageId,
final long timeoutMillis,
final Session session,
final AtomicInteger requests) {
return create(messageId, timeoutMillis, session, requests, null);
}
/**
* 创建一个future
*
* @param messageId 消息ID
* @param timeoutMillis 超时时间
* @param session 会话
* @param requests 正在处理的请求数
* @param afterRun 结束后执行
* @return 完成状态
*/
protected RequestFuture<I, M> create(final I messageId,
final long timeoutMillis,
final Session session,
final AtomicInteger requests,
final BiConsumer<M, Throwable> afterRun) {
return futures.computeIfAbsent(messageId, o -> {
//增加计数器
counter.incrementAndGet();
TimeTask task = new FutureTimeoutTask<>(messageId, SystemClock.now() + timeoutMillis, timeout);
Timeout timeout = timer().add(task);
return new RequestFuture<>(o, session, timeout, requests, afterRun);
});
}
/**
* 根据msgId获取future
*
* @param messageId 消息ID
* @return 增强的CompletableFuture
*/
public RequestFuture<I, M> get(final I messageId) {
return futures.get(messageId);
}
/**
* 正常结束
*
* @param messageId 消息ID
* @param message 消息
* @return 成功标识
*/
public boolean complete(final I messageId, final M message) {
return complete(messageId, message, null);
}
/**
* 异常结束
*
* @param messageId 消息ID
* @param throwable 异常
* @return 成功标识
*/
public boolean completeExceptionally(final I messageId, final Throwable throwable) {
return complete(messageId, null, throwable);
}
/**
* 结束
*
* @param messageId 消息ID
* @param message 消息
* @param throwable 异常
* @return 成功标识
*/
protected boolean complete(final I messageId, final M message, final Throwable throwable) {
RequestFuture<I, M> result = futures.remove(messageId);
if (result != null) {
//减少计数器
counter.decrementAndGet();
return throwable != null ? result.completeExceptionally(throwable) : result.complete(message);
}
return false;
}
/**
* 开启FutureManager(注册timeout事件)
*/
public void open() {
}
/**
* 清空
*/
public void close() {
Map<I, RequestFuture<I, M>> futures = this.futures;
this.futures = new ConcurrentHashMap<>();
this.counter = new AtomicInteger();
Exception exception = new ChannelClosedException("channel is inactive, address is " + channel.getRemoteAddress());
futures.forEach((id, future) -> future.completeExceptionally(exception));
futures.clear();
}
/**
* 生成消息ID
*
* @return 消息ID
*/
public I generateId() {
return idGenerator.get();
}
/**
* 待应答的请求数
*
* @return 应答的请求数
*/
public int size() {
return counter.get();
}
/**
* 请求数是否为空
*
* @return 请求数为空标识
*/
public boolean isEmpty() {
return counter.get() == 0;
}
/**
* Future超时检查任务
*
* @param <I>
*/
protected static class FutureTimeoutTask<I> implements TimeTask {
/**
* 消息ID
*/
protected I messageId;
/**
* 时间
*/
protected long time;
/**
* 执行回调的消费者
*/
protected Consumer<I> timeout;
/**
* 构造函数
*
* @param messageId 消息ID
* @param time 执行时间
* @param timeout 消费者
*/
public FutureTimeoutTask(I messageId, long time, Consumer<I> timeout) {
this.messageId = messageId;
this.time = time;
this.timeout = timeout;
}
@Override
public String getName() {
return FUTURE_TIMEOUT_PREFIX + messageId.toString();
}
@Override
public long getTime() {
return time;
}
@Override
public void run() {
timeout.accept(messageId);
}
}
}
| 25.967391 | 122 | 0.564253 |
67915de9f4748606ebb311c4e9f2568e2c6300b3 | 293 | public class Video {
public final int iD;
public final int size;
public Video (int newID, int newSize) {
iD = newID;
size = newSize;
}
public int getID() {
return iD;
}
public int getSize() {
return size;
}
}
| 16.277778 | 44 | 0.494881 |
b5eadd22fcb952395ef0e887044592917156ac99 | 8,664 | /*
* citygml4j - The Open Source Java API for CityGML
* https://github.com/citygml4j
*
* Copyright 2013-2020 Claus Nagel <[email protected]>
*
* 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.citygml4j.model.common.visitor;
import org.citygml4j.model.xal.Address;
import org.citygml4j.model.xal.AddressDetails;
import org.citygml4j.model.xal.AddressIdentifier;
import org.citygml4j.model.xal.AddressLatitude;
import org.citygml4j.model.xal.AddressLatitudeDirection;
import org.citygml4j.model.xal.AddressLine;
import org.citygml4j.model.xal.AddressLines;
import org.citygml4j.model.xal.AddressLongitude;
import org.citygml4j.model.xal.AddressLongitudeDirection;
import org.citygml4j.model.xal.AdministrativeArea;
import org.citygml4j.model.xal.AdministrativeAreaName;
import org.citygml4j.model.xal.Barcode;
import org.citygml4j.model.xal.BuildingName;
import org.citygml4j.model.xal.Country;
import org.citygml4j.model.xal.CountryName;
import org.citygml4j.model.xal.CountryNameCode;
import org.citygml4j.model.xal.Department;
import org.citygml4j.model.xal.DepartmentName;
import org.citygml4j.model.xal.DependentLocality;
import org.citygml4j.model.xal.DependentLocalityName;
import org.citygml4j.model.xal.DependentLocalityNumber;
import org.citygml4j.model.xal.DependentThoroughfare;
import org.citygml4j.model.xal.EndorsementLineCode;
import org.citygml4j.model.xal.Firm;
import org.citygml4j.model.xal.FirmName;
import org.citygml4j.model.xal.KeyLineCode;
import org.citygml4j.model.xal.LargeMailUser;
import org.citygml4j.model.xal.LargeMailUserIdentifier;
import org.citygml4j.model.xal.LargeMailUserName;
import org.citygml4j.model.xal.Locality;
import org.citygml4j.model.xal.LocalityName;
import org.citygml4j.model.xal.MailStop;
import org.citygml4j.model.xal.MailStopName;
import org.citygml4j.model.xal.MailStopNumber;
import org.citygml4j.model.xal.PostBox;
import org.citygml4j.model.xal.PostBoxNumber;
import org.citygml4j.model.xal.PostBoxNumberExtension;
import org.citygml4j.model.xal.PostBoxNumberPrefix;
import org.citygml4j.model.xal.PostBoxNumberSuffix;
import org.citygml4j.model.xal.PostOffice;
import org.citygml4j.model.xal.PostOfficeName;
import org.citygml4j.model.xal.PostOfficeNumber;
import org.citygml4j.model.xal.PostTown;
import org.citygml4j.model.xal.PostTownName;
import org.citygml4j.model.xal.PostTownSuffix;
import org.citygml4j.model.xal.PostalCode;
import org.citygml4j.model.xal.PostalCodeNumber;
import org.citygml4j.model.xal.PostalCodeNumberExtension;
import org.citygml4j.model.xal.PostalRoute;
import org.citygml4j.model.xal.PostalRouteName;
import org.citygml4j.model.xal.PostalRouteNumber;
import org.citygml4j.model.xal.PostalServiceElements;
import org.citygml4j.model.xal.Premise;
import org.citygml4j.model.xal.PremiseLocation;
import org.citygml4j.model.xal.PremiseName;
import org.citygml4j.model.xal.PremiseNumber;
import org.citygml4j.model.xal.PremiseNumberPrefix;
import org.citygml4j.model.xal.PremiseNumberRange;
import org.citygml4j.model.xal.PremiseNumberRangeFrom;
import org.citygml4j.model.xal.PremiseNumberRangeTo;
import org.citygml4j.model.xal.PremiseNumberSuffix;
import org.citygml4j.model.xal.SortingCode;
import org.citygml4j.model.xal.SubAdministrativeArea;
import org.citygml4j.model.xal.SubAdministrativeAreaName;
import org.citygml4j.model.xal.SubPremise;
import org.citygml4j.model.xal.SubPremiseLocation;
import org.citygml4j.model.xal.SubPremiseName;
import org.citygml4j.model.xal.SubPremiseNumber;
import org.citygml4j.model.xal.SubPremiseNumberPrefix;
import org.citygml4j.model.xal.SubPremiseNumberSuffix;
import org.citygml4j.model.xal.SupplementaryPostalServiceData;
import org.citygml4j.model.xal.Thoroughfare;
import org.citygml4j.model.xal.ThoroughfareLeadingType;
import org.citygml4j.model.xal.ThoroughfareName;
import org.citygml4j.model.xal.ThoroughfareNumber;
import org.citygml4j.model.xal.ThoroughfareNumberFrom;
import org.citygml4j.model.xal.ThoroughfareNumberPrefix;
import org.citygml4j.model.xal.ThoroughfareNumberRange;
import org.citygml4j.model.xal.ThoroughfareNumberSuffix;
import org.citygml4j.model.xal.ThoroughfareNumberTo;
import org.citygml4j.model.xal.ThoroughfarePostDirection;
import org.citygml4j.model.xal.ThoroughfarePreDirection;
import org.citygml4j.model.xal.ThoroughfareTrailingType;
public interface XALFunctor<T> extends Functor<T> {
T apply(Address address);
T apply(AddressDetails addressDetails);
T apply(AddressIdentifier addressIdentifier);
T apply(AddressLatitude addressLatitude);
T apply(AddressLatitudeDirection addressLatitudeDirection);
T apply(AddressLine addressLine);
T apply(AddressLines addressLines);
T apply(AddressLongitude addressLongitude);
T apply(AddressLongitudeDirection addressLongitudeDirection);
T apply(AdministrativeArea administrativeArea);
T apply(AdministrativeAreaName administrativeAreaName);
T apply(Barcode barcode);
T apply(BuildingName buildingName);
T apply(Country country);
T apply(CountryName countryName);
T apply(CountryNameCode countryNameCode);
T apply(Department department);
T apply(DepartmentName departmentName);
T apply(DependentLocality dependentLocality);
T apply(DependentLocalityName dependentLocalityName);
T apply(DependentLocalityNumber dependentLocalityNumber);
T apply(DependentThoroughfare dependentThoroughfare);
T apply(EndorsementLineCode endorsementLineCode);
T apply(Firm firm);
T apply(FirmName firmName);
T apply(KeyLineCode keyLineCode);
T apply(LargeMailUser largeMailUser);
T apply(LargeMailUserIdentifier largeMailUserIdentifier);
T apply(LargeMailUserName largeMailUserName);
T apply(Locality locality);
T apply(LocalityName localityName);
T apply(MailStop mailStop);
T apply(MailStopName mailStopName);
T apply(MailStopNumber mailStopNumber);
T apply(PostalCode postalCode);
T apply(PostalCodeNumber postalCodeNumber);
T apply(PostalCodeNumberExtension postalCodeNumberExtension);
T apply(PostalRoute postalRoute);
T apply(PostalRouteName postalRouteName);
T apply(PostalRouteNumber postalRouteNumber);
T apply(PostalServiceElements postalServiceElements);
T apply(PostBox postBox);
T apply(PostBoxNumber postBoxNumber);
T apply(PostBoxNumberExtension postBoxNumberExtension);
T apply(PostBoxNumberPrefix postBoxNumberPrefix);
T apply(PostBoxNumberSuffix postBoxNumberSuffix);
T apply(PostOffice postOffice);
T apply(PostOfficeName postOfficeName);
T apply(PostOfficeNumber postOfficeNumber);
T apply(PostTown postTown);
T apply(PostTownName postTownName);
T apply(PostTownSuffix postTownSuffix);
T apply(Premise premise);
T apply(PremiseLocation premiseLocation);
T apply(PremiseName premiseName);
T apply(PremiseNumber premiseNumber);
T apply(PremiseNumberPrefix premiseNumberPrefix);
T apply(PremiseNumberRange premiseNumberRange);
T apply(PremiseNumberRangeFrom premiseNumberRangeFrom);
T apply(PremiseNumberRangeTo premiseNumberRangeTo);
T apply(PremiseNumberSuffix premiseNumberSuffix);
T apply(SortingCode sortingCode);
T apply(SubAdministrativeArea subAdministrativeArea);
T apply(SubAdministrativeAreaName subAdministrativeAreaName);
T apply(SubPremise subPremise);
T apply(SubPremiseLocation subPremiseLocation);
T apply(SubPremiseName subPremiseName);
T apply(SubPremiseNumber subPremiseNumber);
T apply(SubPremiseNumberPrefix subPremiseNumberPrefix);
T apply(SubPremiseNumberSuffix subPremiseNumberSuffix);
T apply(SupplementaryPostalServiceData supplementaryPostalServiceData);
T apply(Thoroughfare thoroughfare);
T apply(ThoroughfareLeadingType thoroughfareLeadingType);
T apply(ThoroughfareName thoroughfareName);
T apply(ThoroughfareNumber thoroughfareNumber);
T apply(ThoroughfareNumberFrom thoroughfareNumberFrom);
T apply(ThoroughfareNumberPrefix thoroughfareNumberPrefix);
T apply(ThoroughfareNumberRange thoroughfareNumberRange);
T apply(ThoroughfareNumberSuffix thoroughfareNumberSuffix);
T apply(ThoroughfareNumberTo thoroughfareNumberTo);
T apply(ThoroughfarePostDirection thoroughfarePostDirection);
T apply(ThoroughfarePreDirection thoroughfarePreDirection);
T apply(ThoroughfareTrailingType thoroughfareTrailingType);
}
| 45.6 | 75 | 0.841644 |
27e15f6710fab70609c23161937464ad25fe6917 | 2,450 |
package com.rewayaat.core.data;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"grader", "rationale", "grading"})
public class Grading implements Serializable {
@ApiModelProperty(notes = "Grader's full name")
@JsonProperty("grader")
private String grader;
@ApiModelProperty(notes = "Rationale used for the grading")
@JsonProperty("rationale")
private String rationale;
@ApiModelProperty(notes = "The grading value(eg: hassan, dhaeef, etc..)")
@JsonProperty("grading")
private String grading;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = -4608238425517677384L;
/**
* No args constructor for use in serialization
*/
public Grading() {
}
/**
* @param grading
* @param rationale
* @param grader
*/
public Grading(String grader, String rationale, String grading) {
super();
this.grader = grader;
this.rationale = rationale;
this.grading = grading;
}
@JsonProperty("grader")
public String getGrader() {
return grader;
}
@JsonProperty("grader")
public void setGrader(String grader) {
this.grader = grader;
}
@JsonProperty("rationale")
public String getRationale() {
return rationale;
}
@JsonProperty("rationale")
public void setRationale(String rationale) {
this.rationale = rationale;
}
@JsonProperty("grading")
public String getGrading() {
return grading;
}
@JsonProperty("grading")
public void setGrading(String grading) {
this.grading = grading;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| 26.630435 | 85 | 0.689388 |
b8b9a28972e2ff117f631751a037604c7bb9655a | 460 | class Foo {
String field;
String field2;
int hash = field.<warning descr="Method invocation 'hashCode' may produce 'java.lang.NullPointerException'">hashCode</warning>();
Foo(String f2) {
field2 = f2;
}
void someMethod() {
if (<warning descr="Condition 'field == null' is always 'false'">field == null</warning>) {
System.out.println("impossible");
}
if (field2 == null) {
System.out.println("impossible");
}
}
} | 25.555556 | 131 | 0.630435 |
a7e8b9fe4d0e09e76bcb068987f1e53645c4b398 | 606 | package de.codecentric.boot.webflux;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class SimpleWebfluxController {
@GetMapping("/hello")
public Mono<String> hello() {
return Mono.just("hello world (" + randomFib() + ")");
}
private long randomFib() {
return fib(Math.round(Math.random() * 30.0));
}
private long fib(long n) {
return n == 0 ? 0 : (n == 1 ? 1 : fib(n - 1) + fib(n - 2));
}
}
| 25.25 | 68 | 0.620462 |
c79baceb8f67bbbeb7bc3a94a8cee5f059855f21 | 1,817 | package com.harambase.pioneer.controller;
import com.harambase.pioneer.common.Page;
import com.harambase.pioneer.common.ResultMap;
import com.harambase.pioneer.service.RoleService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@CrossOrigin
@Controller
@RequestMapping("/role")
public class RoleController {
private final RoleService roleService;
public RoleController(RoleService roleService) {
this.roleService = roleService;
}
@RequestMapping(method = RequestMethod.GET)
@PreAuthorize("hasAnyRole('SYSTEM','ADMIN')")
public ResponseEntity list(@RequestParam(value = "start", required = false, defaultValue = "0") Integer start,
@RequestParam(value = "length", required = false, defaultValue = "100") Integer length,
@RequestParam(value = "search", required = false, defaultValue = "") String search,
@RequestParam(value = "order", required = false, defaultValue = "desc") String order,
@RequestParam(value = "orderCol", required = false, defaultValue = "role_id") String orderCol) {
search = search.replace("'", "");
ResultMap message = roleService.list(search, order, orderCol);
message.put("recordsTotal", ((Page) message.get("page")).getTotalRows());
return new ResponseEntity<>(message, HttpStatus.OK);
}
}
| 46.589744 | 127 | 0.708861 |
8805ae4001ec2b6a3ef983d5df02f879335de7c4 | 11,168 | package ca.pfv.spmf.algorithms.classifiers.naive_bayes_text_classifier;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import ca.pfv.spmf.tools.MemoryLogger;
import ca.pfv.spmf.tools.textprocessing.PorterStemmer;
import ca.pfv.spmf.tools.textprocessing.StopWordAnalyzer;
/** * * * This is an implementation of the Naive Bayes Document Classifier algorithm.
*
* Copyright (c) 2014 Sabarish Raghu
*
* This file is part of the SPMF DATA MINING SOFTWARE * (http://www.philippe-fournier-viger.com/spmf).
*
*
* SPMF is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. *
* SPMF is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. *
*
* You should have received a copy of the GNU General Public License along with * SPMF. If not, see .
*
* @author SabarishRaghu
*/
/**
*
* Input can be of any format.
* For the training data, Please place the input files under corresponding ClassNames as FolderNames.
* Output has the following format outputfileName \t ClassName
*/
public class AlgoNaiveBayesClassifier {
private String mTestDataDirectory="";
private String mTrainingDataDirectory="";
private boolean mInMemoryFlag=false; //By Default operations are executed by File IO rather than in memory objects.
private HashMap<String,List<File>> mFileLists=new HashMap<String,List<File>>();
private ArrayList<String> mClassNames;
private StopWordAnalyzer mAnalyzer;
private PorterStemmer mStemmer;
private String mOutputDirectory="";
private ArrayList<MemoryFile> mMemFiles=new ArrayList<MemoryFile>();
long mStartTimestamp = 0; // last execution start time
long mEndTimeStamp = 0; // last execution end time
HashMap<String,Integer> classProb;
/**
*
* @param trainingDirectory
* @param testDirectory
* @param outputDirectory
* @param memoryFlag
* @throws Exception
*/
public void runAlgorithm(String trainingDirectory,String testDirectory,String outputDirectory,boolean memoryFlag) throws Exception
{
this.mTrainingDataDirectory=trainingDirectory;
this.mTestDataDirectory=testDirectory;
this.mOutputDirectory=outputDirectory;
this.mInMemoryFlag=memoryFlag;
this.runAlgorithm();
Runtime.getRuntime().freeMemory(); //Mark the objects for GC's Mark & Sweep.
}
private void runAlgorithm() throws Exception
{
this.mStartTimestamp=System.currentTimeMillis();
mAnalyzer=new StopWordAnalyzer();
mStemmer=new PorterStemmer();
classProb=new HashMap<String,Integer>();
BufferedWriter writer=new BufferedWriter(new FileWriter(new File(mOutputDirectory+"/output.tsv")));
ArrayList<OccurrenceProbabilties> op=new ArrayList<OccurrenceProbabilties>(); //A cache to hold probability for already calculated words in each class
File[] listOfTestFiles=new File(mTestDataDirectory).listFiles();
File[] listOfTrainingFiles=new File(mTrainingDataDirectory).listFiles();
mClassNames=new ArrayList<String>();
int totalTrainingFiles=0;
for(File f: listOfTrainingFiles)
{
mClassNames.add(f.getName());
OccurrenceProbabilties oc=new OccurrenceProbabilties();
oc.setClassName(f.getName());
oc.setOccuranceMap(new HashMap<String,Double>());
op.add(oc);
File classTraining[]=new File(mTrainingDataDirectory+"/"+f.getName()).listFiles();
mFileLists.put(f.getName(), (List<File>) Arrays.asList(classTraining));
classProb.put(f.getName(), classTraining.length);
totalTrainingFiles++;
}
if(mInMemoryFlag==true)
{
System.out.println("Loading Data in to memory.... May take a while depending upon the size of the data");
loadIntoMemory();
}
for(File f:listOfTestFiles)
{
TreeMap<String,BigDecimal> probabilities=new TreeMap<String,BigDecimal>();
System.out.println("---------------Computing for Test File:"+f.getName()+"-----------");
for(String currentClass:mClassNames)
{
TestRecord testRecord=readOneTestFile(f);
BigDecimal prob=new BigDecimal(""+1.0);
for(String word:testRecord.getWords())
{
double termProbInClass=0.0;
if(getFromExistingProbability(word,op,currentClass)!=0.0)
{
termProbInClass=getFromExistingProbability(word,op,currentClass);
}
else
{
if(mInMemoryFlag==true)
termProbInClass=calculateProbabilityInMemory(word,op,currentClass);
else
termProbInClass=calculateProbability(word,op,currentClass);
for(OccurrenceProbabilties oc:op)
{
if(oc.getClassName().equalsIgnoreCase(currentClass))
{
oc.getOccuranceMap().put(word, termProbInClass);
break;
}
}
}
prob=prob.multiply(new BigDecimal(""+termProbInClass));
}
//P(Class/Doc)=P(Doc/class)*P(class)
prob=prob.multiply(new BigDecimal(""+((double)classProb.get(currentClass)/(double)totalTrainingFiles)));
probabilities.put(currentClass, prob);
}
Entry<String,BigDecimal> maxEntry = null;
for(Entry<String,BigDecimal> entry : probabilities.entrySet()) {
if (maxEntry == null || entry.getValue().compareTo( maxEntry.getValue())>0) {
maxEntry = entry;
}
}
System.out.println(f.getName()+"\t"+maxEntry.getKey());
writer.write(f.getName()+"\t"+maxEntry.getKey()+"\n");
}
writer.close();
this.mEndTimeStamp=System.currentTimeMillis();
}
/**
* Load the training data in to memory
*/
private void loadIntoMemory() throws IOException
{
for(String s:mClassNames)
{
List<File> classTraining=mFileLists.get(s);
MemoryFile memfile=new MemoryFile();
ArrayList<String> words=new ArrayList<String>();
memfile.setClassname(s);
for(File f:classTraining)
{
BufferedReader reader=new BufferedReader(new FileReader(f));
String currentLine="";
while((currentLine=reader.readLine())!=null)
{
currentLine=currentLine.replaceAll("\\P{L}", " ").toLowerCase().replaceAll("\n"," ");
currentLine=currentLine.replaceAll("\\s+", " ");
currentLine=mAnalyzer.removeStopWords(currentLine);
for(String processedWord:currentLine.split("\\s+"))
{
processedWord=mStemmer.stem(processedWord);
if(processedWord.length()>1)
{
words.add(processedWord);
}
}
}
reader.close();
}
memfile.setContent(words);
mMemFiles.add(memfile);
}
}
/**
* Get the probability value of a particular word in a particular class. Calculates them from in memory stored objects
* @param word
* @param op
* @param currentClass
* @return probability value of the word in the class
*/
private double calculateProbabilityInMemory(String word,ArrayList<OccurrenceProbabilties> op, String currentClass)
{
double prob=0.0;
int count=0;
int occurances=0;
for(MemoryFile memFile:mMemFiles)
{
if(memFile.getClassname().equals(currentClass))
{
occurances+=Collections.frequency(memFile.getContent(), word)*50; //Giving more weightage to occurances rather than just incrementing by 1.
count+=memFile.getContent().size();
}
}
prob=(double)((double)occurances+50.0)/(double)((double)count+100.0); // Normalizing the value to avoid return of 0.0
return prob;
}
/**
* Get the probability value of a particular word in a particular class. Calculates them from File search.
* @param word
* @param op
* @param currentClass
* @return probability value of the word in the class
* @throws Exception
*/
private double calculateProbability(String word,
ArrayList<OccurrenceProbabilties> op, String currentClass) throws Exception {
double probability=0.0;
List<File> classTraining=mFileLists.get(currentClass);
ArrayList<String> words=new ArrayList<String>();
double count=0.0;
for(File f:classTraining)
{
BufferedReader reader=new BufferedReader(new FileReader(f));
String currentLine="";
while((currentLine=reader.readLine())!=null)
{
currentLine=currentLine.replaceAll("\\P{L}", " ").toLowerCase().replaceAll("\n"," ");
currentLine=currentLine.replaceAll("\\s+", " ");
currentLine=mAnalyzer.removeStopWords(currentLine);
for(String processedWord:currentLine.split("\\s+"))
{
processedWord=mStemmer.stem(processedWord);
if(processedWord.length()>1)
{
words.add(processedWord);
}
if(processedWord.equalsIgnoreCase(word))
{
count+=20;
}
}
}
reader.close();
}
probability=(double)((double)count+50.0)/(double)((double)words.size()+100.0);
return probability;
}
/**
* Get from cached probabilities.
* @param word
* @param probabilties
* @param className
* @return the cached probabilities
*/
public double getFromExistingProbability(String word, ArrayList<OccurrenceProbabilties>probabilties, String className)
{
double value=0.0;
for(OccurrenceProbabilties op:probabilties)
{
if(op.getClassName().equals(className))
{
Set<String> myKeys=op.getOccuranceMap().keySet();
for(String s:myKeys)
{
if(op.getOccuranceMap().get(s) != null&&s.equals(word))
{
value=op.getOccuranceMap().get(s);
}
}
}
}
return value;
}
/**
* Reads one test file and stores it in Object.
* @param f
* @return
*/
public TestRecord readOneTestFile(File f) throws Exception
{
TestRecord record=new TestRecord();
String currentLine;
ArrayList<String> words=new ArrayList<String>();
BufferedReader br=new BufferedReader(new FileReader(f));
while((currentLine=br.readLine())!=null)
{
currentLine=currentLine.toLowerCase(); //convert everyword to lower case
currentLine=currentLine.replaceAll("\\P{L}", " "); //only alphabets
currentLine=currentLine.replaceAll("\n"," ");
currentLine=currentLine.replaceAll("\\s+", " ").trim();
currentLine=mAnalyzer.removeStopWords(currentLine);
String lineWords[]=currentLine.split("\\s+");
for(String eachWord:lineWords)
{
String processedWord=mStemmer.stem(eachWord);
if(processedWord.length()>1)
{
words.add(processedWord);
}
}
}
record.setRecordId(Integer.parseInt(f.getName().replaceAll("\\D+","")));
record.setWords(words);
br.close();
return record;
}
/**
* Print statistics of the latest execution to System.out.
*/
public void printStatistics() {
System.out.println("========== Naive Bayes Classifier Stats ============");
System.out.println(" Total time ~: " + (mEndTimeStamp - mStartTimestamp)
+ " ms");
System.out.println(" Max memory:" + MemoryLogger.getInstance().getMaxMemory() + " mb ");
System.out.println("=====================================");
}
}
| 33.04142 | 242 | 0.706125 |
411fcda911cb8e72c705474902bdd5f5fb81c4a5 | 265 | package com.baoying.enginex.executor.rule.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baoying.enginex.executor.rule.model.RuleLoopGroupAction;
public interface RuleLoopGroupActionMapper extends BaseMapper<RuleLoopGroupAction> {
}
| 26.5 | 84 | 0.849057 |
4652de74ae4c3839f45af9fa917e32bf9e90391c | 4,198 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author Fede
*/
public class Clima implements Cloneable {
private int idClima;
private int idZona;
private Date fechaHora;
private String salidaDelSol;
private String puestaDelSol;
private double temperatura;
private int iconoTemperatura;
private double sensacionTermica;
private String descripcionTemperatura;
private double presion;
private double velocidadDelViento;
private String direccionDelViento;
private double humedad;
private double indiceUV;
private String faseLuna;
private int iconoLuna;
public String mostrarFecha () {
SimpleDateFormat formatFecha = new SimpleDateFormat("dd/MM/yyyy");
String cadenaFecha = formatFecha.format(fechaHora);
return cadenaFecha;
}
public String mostrarHora () {
SimpleDateFormat formatHora = new SimpleDateFormat("H:mm:ss");
String cadenaHora = formatHora.format(fechaHora);
return cadenaHora;
}
public String getPuestaDelSol() {
return puestaDelSol;
}
public String getSalidaDelSol() {
return salidaDelSol;
}
public String getDescripcionTemperatura() {
return descripcionTemperatura;
}
public String getDireccionDelViento() {
return direccionDelViento;
}
public String getFaseLuna() {
return faseLuna;
}
public Date getFechaHora() {
return fechaHora;
}
public double getHumedad() {
return humedad;
}
public int getIconoLuna() {
return iconoLuna;
}
public int getIconoTemperatura() {
return iconoTemperatura;
}
public int getIdClima() {
return idClima;
}
public int getIdZona() {
return idZona;
}
public double getIndiceUV() {
return indiceUV;
}
public double getPresion() {
return presion;
}
public double getSensacionTermica() {
return sensacionTermica;
}
public double getTemperatura() {
return temperatura;
}
public double getVelocidadDelViento() {
return velocidadDelViento;
}
public void setPuestaDelSol(String PuestaDelSol) {
this.puestaDelSol = PuestaDelSol;
}
public void setSalidaDelSol(String SalidaDelSol) {
this.salidaDelSol = SalidaDelSol;
}
public void setDescripcionTemperatura(String descripcionTemperatura) {
this.descripcionTemperatura = descripcionTemperatura;
}
public void setDireccionDelViento(String direccionDelViento) {
this.direccionDelViento = direccionDelViento;
}
public void setFaseLuna(String faseLuna) {
this.faseLuna = faseLuna;
}
public void setFechaHora(Date fechaHora) {
this.fechaHora = fechaHora;
}
public void setHumedad(double humedad) {
this.humedad = humedad;
}
public void setIconoLuna(int iconoLuna) {
this.iconoLuna = iconoLuna;
}
public void setIconoTemperatura(int iconoTemperatura) {
this.iconoTemperatura = iconoTemperatura;
}
public void setIndiceUV(double indiceUV) {
this.indiceUV = indiceUV;
}
public void setPresion(double presion) {
this.presion = presion;
}
public void setSensacionTermica(double sensacionTermica) {
this.sensacionTermica = sensacionTermica;
}
public void setTemperatura(double temperatura) {
this.temperatura = temperatura;
}
public void setVelocidadDelViento(double velocidadDelViento) {
this.velocidadDelViento = velocidadDelViento;
}
public void setIdClima(int idClima) {
this.idClima = idClima;
}
public void setIdZona(int idZona) {
this.idZona = idZona;
}
@Override
public Object clone(){
Object obj=null;
try{
obj=super.clone();
}catch(CloneNotSupportedException ex){
System.out.println(" no se puede duplicar");
}
return obj;
}
}
| 22.449198 | 74 | 0.653406 |
d1dc7f1157200306e69281b91ff1299f732fd40d | 1,456 | package com.miu30.common.ui.entity;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.annotation.Column;
import com.lidroid.xutils.db.annotation.Id;
import com.lidroid.xutils.db.annotation.Table;
import com.miu30.common.MiuBaseApp;
/**
* Created by Murphy on 2018/10/24.
*/
@Table(name = "location")
public class LatLngMsg {
public LatLngMsg() {
}
public LatLngMsg(double lat, double lng, String name) {
this.lat = lat;
this.lng = lng;
this.name = name;
}
/**
* 本地存储id
*/
@Id
private long id;
@Column(column = "lat")
private double lat;
@Column(column = "lng")
private double lng;
@Column(column = "name")
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static DbUtils.DaoConfig getDaoConfig() {
DbUtils.DaoConfig config = new DbUtils.DaoConfig(MiuBaseApp.self);
config.setDbName("Address");
config.setDbVersion(1);
return config;
}
}
| 19.157895 | 74 | 0.59272 |
92910674e97487602b4b8e750a1fd6441a839679 | 3,451 | /*
* Copyright 2019-2020 Zheng Jie
*
* 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 me.zhengjie.modules.zhengyi.driverDetails.rest;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.zhengyi.driverDetails.domain.ZyDriverDetails;
import me.zhengjie.modules.zhengyi.driverDetails.service.ZyDriverDetailsService;
import me.zhengjie.modules.zhengyi.driverDetails.service.dto.ZyDriverDetailsDto;
import me.zhengjie.modules.zhengyi.driverDetails.service.dto.ZyDriverDetailsQueryCriteria;
import me.zhengjie.modules.zhengyi.driverOrder.service.ZyDriverOrderService;
import me.zhengjie.modules.zhengyi.driverOrder.service.dto.ZyDriverOrderDto;
import me.zhengjie.modules.zhengyi.employer.service.ZyEmployerUserService;
import me.zhengjie.modules.zhengyi.employer.service.dto.ZyEmployerUserDto;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://el-admin.vip
* @author 政一
* @date 2020-07-03
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "司机订单详情")
@RequestMapping("/api/zyDriverDetails")
public class ZyDriverDetailsController {
private final ZyDriverDetailsService zyDriverDetailsService;
private final ZyDriverOrderService zyDriverOrderService;
private final ZyEmployerUserService zyEmployerUserService;
@AnonymousAccess
@PostMapping(value = "/add")
@Log("新增完结订单详情")
@ApiOperation("新增完结订单详情")
public ResponseEntity<Object> create(@Validated @RequestBody ZyDriverDetails resources){
//修改车主订单
zyDriverOrderService.updateHire(resources.getDriverOrderId(),1);
ZyDriverOrderDto orderDto = zyDriverOrderService.findById(resources.getDriverOrderId());
ZyEmployerUserDto userDto = zyEmployerUserService.findById(resources.getOwnerId());
resources.setName(orderDto.getName());
resources.setPhone(orderDto.getPhone());
resources.setType(Integer.parseInt(orderDto.getType()));
resources.setDrivingType(orderDto.getDrivingType());
resources.setContent(orderDto.getContent());
resources.setOwnerName(userDto.getName());
resources.setOwnerPhone(userDto.getPhone());
return new ResponseEntity<>(zyDriverDetailsService.create(resources),HttpStatus.CREATED);
}
@AnonymousAccess
@GetMapping(value = "/getDriverDetails")
@Log("获取完成订单详情")
@ApiOperation("获取完成订单详情")
public ZyDriverDetailsDto getDriverDetails(@RequestParam String id){
return zyDriverDetailsService.getDriverDetails(id);
}
}
| 41.578313 | 97 | 0.78499 |
ea158ba0fc520186b04b6093fa2b10118ed49194 | 4,611 | package com.chinamobile.other;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
public class MyTest {
@Test
public void testme() throws IOException {
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow((short) 2);
row.setHeightInPoints(30);
createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM);
createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);
createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);
createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);
createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);
createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);
createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("xssf-align.xlsx");
wb.write(fileOut);
fileOut.close();
}
/**
* Creates a cell and aligns it a certain way.
*
* @param wb the workbook
* @param row the row to create the cell in
* @param column the column number to create the cell in
* @param halign the horizontal alignment for the cell.
*/
private void createCell(Workbook wb, Row row, short column, short halign, short valign) {
Cell cell = row.createCell(column);
cell.setCellValue("Align It");
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(halign);
cellStyle.setVerticalAlignment(valign);
cell.setCellStyle(cellStyle);
}
@Test
public void test2() throws IOException{
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(1);
// Create a cell and put a value in it.
// Style the cell with borders all around.
CellStyle style = wb.createCellStyle();
// style.setFillBackgroundColor(IndexedColors.AUTOMATIC.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.index);
Font font = wb.createFont();
font.setFontHeightInPoints((short)24);
font.setFontName("Courier New");
font.setItalic(true);
font.setStrikeout(true);
style.setFont(font);
CellUtil.createCell(row, 1, "nihao",style);
//style.setFont(font);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
}
private Map<String, String> map=new HashMap<String, String>();
@Test
public void before(){
map.put("a", "aa");
}
@Test
public void testLong() throws EncryptedDocumentException, InvalidFormatException, IOException{
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue("This is a aoptest of merging");
sheet.addMergedRegion(new CellRangeAddress(
1, //first row (0-based)
1, //last row (0-based)
1, //first column (0-based)
2 //last column (0-based)
));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(new File("E:/aoptest/gzb.xls"));
wb.write(fileOut);
fileOut.close();
}
}
| 36.888 | 101 | 0.652353 |
df152d37f198ac567ae04ab6301b20612d524d68 | 2,386 | /*
* Copyright (c) 2010-2020. Axon Framework
*
* 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.axonframework.extensions.tracing;
import io.opentracing.Span;
import org.axonframework.common.Registration;
import org.axonframework.queryhandling.SubscriptionQueryResult;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Traceable implementation of {@link SubscriptionQueryResult}.
*
* @param <I> The type of initial result
* @param <U> The type of incremental updates
* @author Lucas Campos
* @since 4.3
*/
public class TraceableSubscriptionQueryResult<I, U> implements SubscriptionQueryResult<I, U> {
private final Mono<I> initialResult;
private final Flux<U> updates;
private final Registration registrationDelegate;
private final Span span;
/**
* Initializes a Traceable SubscriptionQueryResult which contains the original subscriptionQueryResult and the
* responsible Span.
*
* @param subscriptionQueryResult the original subscriptionQueryResult
* @param span the span wrapping the subscriptionQuery
*/
public TraceableSubscriptionQueryResult(SubscriptionQueryResult<I, U> subscriptionQueryResult, Span span) {
this.initialResult = subscriptionQueryResult.initialResult();
this.updates = subscriptionQueryResult.updates();
this.registrationDelegate = subscriptionQueryResult;
this.span = span;
}
@Override
public Mono<I> initialResult() {
span.log("initialResultReceived");
return initialResult;
}
@Override
public Flux<U> updates() {
return updates.doOnEach(ignored -> span.log("updateReceived"));
}
@Override
public boolean cancel() {
span.log("subscriptionClosed");
span.finish();
return registrationDelegate.cancel();
}
} | 33.605634 | 114 | 0.719195 |
0c5e809c1da86590f29c478cf3dfbaddae0c0187 | 1,599 | /*
* Copyright (c) 2015, Inversoft 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 org.primeframework.mvc.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Something that can get a cookie...nom nom nom...
*
* @author Daniel DeGroff
*/
public interface CookieConfig {
/**
* Add a cookie to the HTTP response
*
* @param request the HTTP request
* @param response the HTTP response
* @param value the value of the cookie
*/
void add(HttpServletRequest request, HttpServletResponse response, String value);
/**
* Delete a cookie
*
* @param request the HTTP request
* @param response the HTTP response
*/
void delete(HttpServletRequest request, HttpServletResponse response);
/**
* Get me a cookie please.
*
* @param request the HTTP servlet request
* @return the cookie value or null.
*/
String get(HttpServletRequest request);
/**
* @return the name of the cookie that this config can 'get'.
*/
String name();
}
| 28.052632 | 83 | 0.706692 |
eb346f1e3ee85084f0b28dcfe38322c8a8fe57ec | 6,749 | /*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. 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 Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) 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 RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS 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 rice.pastry.socket.nat.probe;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.mpisws.p2p.transport.multiaddress.AddressStrategy;
import org.mpisws.p2p.transport.multiaddress.MultiInetSocketAddress;
import org.mpisws.p2p.transport.networkinfo.ProbeStrategy;
import org.mpisws.p2p.transport.networkinfo.Prober;
import rice.Continuation;
import rice.environment.logging.Logger;
import rice.p2p.commonapi.Cancellable;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.MessageDeserializer;
import rice.pastry.NodeHandle;
import rice.pastry.PastryNode;
import rice.pastry.client.PastryAppl;
import rice.pastry.messaging.Message;
import rice.pastry.socket.SocketNodeHandle;
import rice.pastry.socket.nat.rendezvous.RendezvousSocketNodeHandle;
import rice.pastry.transport.PMessageNotification;
import rice.pastry.transport.PMessageReceipt;
public class ProbeApp extends PastryAppl implements ProbeStrategy {
Prober prober;
AddressStrategy addressStrategy;
public ProbeApp(PastryNode pn, Prober prober, AddressStrategy addressStrategy) {
super(pn, null, 0, null);
this.prober = prober;
this.addressStrategy = addressStrategy;
setDeserializer(new MessageDeserializer() {
public rice.p2p.commonapi.Message deserialize(InputBuffer buf, short type,
int priority, rice.p2p.commonapi.NodeHandle sender) throws IOException {
switch(type) {
case ProbeRequestMessage.TYPE:
return ProbeRequestMessage.build(buf, getAddress());
default:
throw new IllegalArgumentException("Unknown type: "+type);
}
}
});
}
@Override
public void messageForAppl(Message msg) {
ProbeRequestMessage prm = (ProbeRequestMessage)msg;
handleProbeRequestMessage(prm);
}
public void handleProbeRequestMessage(ProbeRequestMessage prm) {
if (logger.level <= Logger.FINE) logger.log("handleProbeRequestMessage("+prm+")");
prober.probe(
addressStrategy.getAddress(((SocketNodeHandle)thePastryNode.getLocalHandle()).getAddress(),
prm.getProbeRequester()),
prm.getUID(), null, null);
}
/**
* Send a ProbeRequestMessage to a node in the leafset.
*
* The node must not have the same external address as addr.
* If no such candidate can be found, use someone who does.
* If there are no candidates at all, send the message to self (or call handleProbeRequest()
*/
public Cancellable requestProbe(MultiInetSocketAddress addr, long uid, final Continuation<Boolean, Exception> deliverResultToMe) {
if (logger.level <= Logger.FINE) logger.log("requestProbe("+addr+","+uid+","+deliverResultToMe+")");
// Step 1: find valid helpers
// make a list of valid candidates
ArrayList<NodeHandle> valid = new ArrayList<NodeHandle>();
Iterator<NodeHandle> candidates = thePastryNode.getLeafSet().iterator();
while(candidates.hasNext()) {
SocketNodeHandle nh = (SocketNodeHandle)candidates.next();
// don't pick self
if (!nh.equals(thePastryNode.getLocalHandle())) {
// if nh will send to addr's outermost address
if (addressStrategy.getAddress(nh.getAddress(), addr).equals(addr.getOutermostAddress())) {
valid.add(nh);
}
}
}
// if there are no valid nodes, use the other nodes
if (valid.isEmpty()) {
deliverResultToMe.receiveResult(false);
return null;
// if (logger.level <= Logger.WARNING) logger.log("requestProbe("+addr+","+uid+") found nobody to help verify connectivity, doing it by my self");
// valid.add(thePastryNode.getLocalHandle());
}
// Step 2: choose one randomly
NodeHandle handle = valid.get(thePastryNode.getEnvironment().getRandomSource().nextInt(valid.size()));
// Step 3: send the probeRequest
ProbeRequestMessage prm = new ProbeRequestMessage(addr, uid, getAddress());
return thePastryNode.send(handle, prm, new PMessageNotification() {
public void sent(PMessageReceipt msg) {
deliverResultToMe.receiveResult(true);
}
public void sendFailed(PMessageReceipt msg, Exception reason) {
deliverResultToMe.receiveResult(false);
}
}, null);
}
public Collection<InetSocketAddress> getExternalAddresses() {
ArrayList<InetSocketAddress> ret = new ArrayList<InetSocketAddress>();
Iterator<NodeHandle> i = thePastryNode.getLeafSet().iterator();
while(i.hasNext()) {
NodeHandle nh = i.next();
RendezvousSocketNodeHandle rsnh = (RendezvousSocketNodeHandle)nh;
if (rsnh.canContactDirect()) {
ret.add(rsnh.getInetSocketAddress());
}
}
return ret;
}
}
| 41.404908 | 151 | 0.71981 |
e4c9bdf0e2b7d33fb1924654c81ee45e7afe3e5c | 13,407 | /*
* Copyright (c) 2009-2021 jMonkeyEngine
* 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 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.environment;
import com.jme3.app.Application;
import com.jme3.asset.AssetManager;
import com.jme3.environment.generation.*;
import com.jme3.environment.util.EnvMapUtils;
import com.jme3.light.LightProbe;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.texture.TextureCubeMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
/**
* This Factory allows to create LightProbes within a scene given an EnvironmentCamera.
*
* Since the process can be long, you can provide a JobProgressListener that
* will be notified of the ongoing generation process when calling the makeProbe method.
*
* The process is as follows:
* 1. Create an EnvironmentCamera
* 2. give it a position in the scene
* 3. call {@link LightProbeFactory#makeProbe(com.jme3.environment.EnvironmentCamera, com.jme3.scene.Spatial)}
* 4. add the created LightProbe to a node with the {@link Node#addLight(com.jme3.light.Light) } method.
*
* Optionally for step 3 call
* {@link #makeProbe(com.jme3.environment.EnvironmentCamera, com.jme3.scene.Spatial, com.jme3.environment.generation.JobProgressListener)}
* with a {@link JobProgressListener} to be notified of the progress of the generation process.
*
* The generation will be split in several threads for faster generation.
*
* This class is entirely thread safe and can be called from any thread.
*
* Note that in case you are using a {@link JobProgressListener} all the its
* method will be called inside and app.enqueue callable.
* This means that it's completely safe to modify the scenegraph within the
* Listener method, but also means that the event will be delayed until next update loop.
*
* @see EnvironmentCamera
* @author bouquet
*/
public class LightProbeFactory {
/**
* A private constructor to inhibit instantiation of this class.
*/
private LightProbeFactory() {
}
/**
* Creates a LightProbe with the giver EnvironmentCamera in the given scene.
*
* Note that this is an asynchronous process that will run on multiple threads.
* The process is thread safe.
* The created lightProbe will only be marked as ready when the rendering process is done.
*
* If you want to monitor the process use
* {@link #makeProbe(com.jme3.environment.EnvironmentCamera, com.jme3.scene.Spatial, com.jme3.environment.generation.JobProgressListener)}
*
*
*
* @see LightProbe
* @see EnvironmentCamera
* @param envCam the EnvironmentCamera
* @param scene the Scene
* @return the created LightProbe
*/
public static LightProbe makeProbe(final EnvironmentCamera envCam, Spatial scene) {
return makeProbe(envCam, scene, null);
}
/**
* Creates a LightProbe with the giver EnvironmentCamera in the given scene.
*
* Note that this is an asynchronous process that will run on multiple threads.
* The process is thread safe.
* The created lightProbe will only be marked as ready when the rendering process is done.
*
* The JobProgressListener will be notified of the progress of the generation.
* Note that you can also use a {@link JobProgressAdapter}.
*
* @see LightProbe
* @see EnvironmentCamera
* @see JobProgressListener
* @param envCam the EnvironmentCamera
* @param scene the Scene
* @param genType Fast or HighQuality. Fast may be ok for many types of environment, but you may need high quality when an environment map has very high lighting values.
* @param listener the listener of the generation progress.
* @return the created LightProbe
*/
public static LightProbe makeProbe(final EnvironmentCamera envCam, Spatial scene, final EnvMapUtils.GenerationType genType, final JobProgressListener<LightProbe> listener) {
final LightProbe probe = new LightProbe();
probe.setPosition(envCam.getPosition());
probe.setPrefilteredMap(EnvMapUtils.createPrefilteredEnvMap(envCam.getSize(), envCam.getImageFormat()));
envCam.snapshot(scene, new JobProgressAdapter<TextureCubeMap>() {
@Override
public void done(TextureCubeMap map) {
generatePbrMaps(map, probe, envCam.getApplication(), genType, listener);
}
});
return probe;
}
public static LightProbe makeProbe(final EnvironmentCamera envCam, Spatial scene, final JobProgressListener<LightProbe> listener) {
return makeProbe(envCam, scene, EnvMapUtils.GenerationType.Fast, listener);
}
/**
* Updates a LightProbe with the given EnvironmentCamera in the given scene.
* <p>
* Note that this is an asynchronous process that will run on multiple threads.
* The process is thread safe.
* The created lightProbe will only be marked as ready when the rendering process is done.
* <p>
* The JobProgressListener will be notified of the progress of the generation.
* Note that you can also use a {@link JobProgressAdapter}.
*
* @param probe the Light probe to update
* @param envCam the EnvironmentCamera
* @param scene the Scene
* @param genType Fast or HighQuality. Fast may be ok for many types of environment, but you may need high quality when an environment map has very high lighting values.
* @param listener the listener of the generation progress.
* @return the created LightProbe
* @see LightProbe
* @see EnvironmentCamera
* @see JobProgressListener
*/
public static LightProbe updateProbe(final LightProbe probe, final EnvironmentCamera envCam, Spatial scene, final EnvMapUtils.GenerationType genType, final JobProgressListener<LightProbe> listener) {
envCam.setPosition(probe.getPosition());
probe.setReady(false);
if (probe.getPrefilteredEnvMap() != null) {
probe.getPrefilteredEnvMap().getImage().dispose();
}
probe.setPrefilteredMap(EnvMapUtils.createPrefilteredEnvMap(envCam.getSize(), envCam.getImageFormat()));
envCam.snapshot(scene, new JobProgressAdapter<TextureCubeMap>() {
@Override
public void done(TextureCubeMap map) {
generatePbrMaps(map, probe, envCam.getApplication(), genType, listener);
}
});
return probe;
}
public static LightProbe updateProbe(final LightProbe probe, final EnvironmentCamera envCam, Spatial scene, final JobProgressListener<LightProbe> listener) {
return updateProbe(probe, envCam, scene, EnvMapUtils.GenerationType.Fast, listener);
}
/**
* Internally called to generate the maps.
* This method will spawn 7 thread (one for the Irradiance spherical harmonics generator, and one for each face of the prefiltered env map).
* Those threads will be executed in a ScheduledThreadPoolExecutor that will be shutdown when the generation is done.
*
* @param envMap the raw env map rendered by the env camera
* @param probe the LightProbe to generate maps for
* @param app the Application
* @param listener a progress listener. (can be null if no progress reporting is needed)
*/
private static void generatePbrMaps(TextureCubeMap envMap, final LightProbe probe, Application app, EnvMapUtils.GenerationType genType, final JobProgressListener<LightProbe> listener) {
IrradianceSphericalHarmonicsGenerator irrShGenerator;
PrefilteredEnvMapFaceGenerator[] pemGenerators = new PrefilteredEnvMapFaceGenerator[6];
final JobState jobState = new JobState(new ScheduledThreadPoolExecutor(7));
irrShGenerator = new IrradianceSphericalHarmonicsGenerator(app, new JobListener(listener, jobState, probe, 6));
int size = envMap.getImage().getWidth();
irrShGenerator.setGenerationParam(EnvMapUtils.duplicateCubeMap(envMap), probe);
jobState.executor.execute(irrShGenerator);
for (int i = 0; i < pemGenerators.length; i++) {
pemGenerators[i] = new PrefilteredEnvMapFaceGenerator(app, i, new JobListener(listener, jobState, probe, i));
pemGenerators[i].setGenerationParam(EnvMapUtils.duplicateCubeMap(envMap), size, EnvMapUtils.FixSeamsMethod.None, genType, probe.getPrefilteredEnvMap());
jobState.executor.execute(pemGenerators[i]);
}
}
/**
* For debugging purposes only.
* Will return a Node meant to be added to a GUI presenting the 2 cube maps in a cross pattern with all the mip maps.
*
* @param manager the asset manager
* @return a debug node
*/
public static Node getDebugGui(AssetManager manager, LightProbe probe) {
if (!probe.isReady()) {
throw new UnsupportedOperationException("This EnvProbe is not ready yet, try to test isReady()");
}
Node debugNode = new Node("debug gui probe");
Node debugPfemCm = EnvMapUtils.getCubeMapCrossDebugViewWithMipMaps(probe.getPrefilteredEnvMap(), manager);
debugNode.attachChild(debugPfemCm);
debugPfemCm.setLocalTranslation(520, 0, 0);
return debugNode;
}
/**
* An inner class to keep the state of a generation process
*/
private static class JobState {
double progress[] = new double[7];
boolean done[] = new boolean[7];
ScheduledThreadPoolExecutor executor;
boolean started = false;
public JobState(ScheduledThreadPoolExecutor executor) {
this.executor = executor;
}
boolean isDone() {
for (boolean d : done) {
if (d == false) {
return false;
}
}
return true;
}
float getProgress() {
float mean = 0;
for (double progres : progress) {
mean += progres;
}
return mean / 7f;
}
}
/**
* An inner JobProgressListener to control the generation process and properly clean up when it's done
*/
private static class JobListener extends JobProgressAdapter<Integer> {
JobProgressListener<LightProbe> globalListener;
JobState jobState;
LightProbe probe;
int index;
public JobListener(JobProgressListener<LightProbe> globalListener, JobState jobState, LightProbe probe, int index) {
this.globalListener = globalListener;
this.jobState = jobState;
this.probe = probe;
this.index = index;
}
@Override
public void start() {
if (globalListener != null && !jobState.started) {
jobState.started = true;
globalListener.start();
}
}
@Override
public void progress(double value) {
jobState.progress[index] = value;
if (globalListener != null) {
globalListener.progress(jobState.getProgress());
}
}
@Override
public void done(Integer result) {
if (globalListener != null) {
if (result < 6) {
globalListener.step("Prefiltered env map face " + result + " generated");
} else {
globalListener.step("Irradiance map generated");
}
}
jobState.done[index] = true;
if (jobState.isDone()) {
probe.setNbMipMaps(probe.getPrefilteredEnvMap().getImage().getMipMapSizes().length);
probe.setReady(true);
if (globalListener != null) {
globalListener.done(probe);
}
jobState.executor.shutdownNow();
}
}
}
}
| 41.252308 | 203 | 0.67778 |
8bb2b06d303546c85739b88503fe4e7bce472bac | 1,024 | package datadog.trace.instrumentation.spymemcached;
import datadog.trace.instrumentation.api.AgentSpan;
import java.util.concurrent.ExecutionException;
import net.spy.memcached.MemcachedConnection;
import net.spy.memcached.internal.BulkGetFuture;
public class BulkGetCompletionListener extends CompletionListener<BulkGetFuture<?>>
implements net.spy.memcached.internal.BulkGetCompletionListener {
public BulkGetCompletionListener(final MemcachedConnection connection, final String methodName) {
super(connection, methodName);
}
@Override
public void onComplete(final BulkGetFuture<?> future) {
closeAsyncSpan(future);
}
@Override
protected void processResult(final AgentSpan span, final BulkGetFuture<?> future)
throws ExecutionException, InterruptedException {
/*
Note: for now we do not have an affective way of representing results of bulk operations,
i.e. we cannot say that we got 4 hits out of 10. So we will just ignore results for now.
*/
future.get();
}
}
| 34.133333 | 99 | 0.777344 |
e2c2cddde34157c800c8ea86f05a7f950c1bf691 | 5,134 | package data.railway;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Pablo on 19/6/17.
*/
public class Resource implements Serializable {
private String baseStation;
private int baseStationIndex;
private int resourceIndex;
private int workedMinutes;
private final int workday;
private List<Step> steps;
private int nSteps;
private int nTaskCovered;
private int nTasks;
public Resource(String baseStation, int baseStationIndex, int workday, int resourceIndex, int nTasks) {
this.baseStation = baseStation;
this.baseStationIndex = baseStationIndex;
this.workday = workday;
this.resourceIndex = resourceIndex;
this.workedMinutes = 0;
this.nSteps = 0;
this.nTaskCovered = 0;
this.steps = new ArrayList<>();
this.nTasks = nTasks;
this.steps.add(new Step(0, new StartTask(baseStation, nTasks + baseStationIndex)));
}
public Step[] getSteps() {
return steps.toArray(new Step[steps.size()]);
}
public Step getLastStep() {
return this.steps.get(this.nSteps);
}
/**
* Add a new step with the task passed in the parameter
*
* @param task the Task to add to the resource
* @param taskAlreadyCovered if the task which are going to be assigned is already covered = True
* @return boolean to indicate if the step was added or not
*/
public boolean addStep(Task task, boolean taskAlreadyCovered) {
boolean success = false;
Step lastStep = this.getLastStep();
int lastStepFinalTime = lastStep.getTask().getFinalTime();
int workedTimeIncrement;
if (lastStepFinalTime < 0) {
workedTimeIncrement = task.getTaskTime();
} else workedTimeIncrement = task.getTaskTime() + (task.getInitialTime() - lastStepFinalTime);
//DEBUG
//System.out.println("lastStepFinalTime: " + lastStepFinalTime);
//System.out.println("New Task initial time: " + task.getInitialTime());
//System.out.println("New Task final time: " + task.getFinalTime());
//System.out.println("Task time: " + task.getTaskTime());
//System.out.println("Working increment: " + workedTimeIncrement);
//System.out.println("Worked minutest: " + workedMinutes);
//System.out.println("~ RESOURCE: " + this.resourceIndex
// + " PREVIOUS WORKED MINUTES: " + workedMinutes
// + "(lastStepFinalTime: " + lastStepFinalTime + ") "
// + " TASK ADDED: " + task.getTaskIndex()
// + " (New Task initial time: " + task.getInitialTime()
// + " New Task final time: " + task.getFinalTime()
// + " Task time: " + task.getTaskTime() + ") "
// + " WITH TIME INCREMENT: " + workedTimeIncrement
// + " CURRENT WORKED MINUTES " + (workedMinutes + workedTimeIncrement));
//if ((workedMinutes + workedTimeIncrement) > workday) {
////Assignation not possible
//} else {
this.steps.add(new Step(workedMinutes, task));
nSteps += 1;
workedMinutes += workedTimeIncrement;
if (!taskAlreadyCovered) {
nTaskCovered += 1;
success = true;
}
//}
return success;
}
/**
* @param task Task to check if it is going to be assigned
* @return 0 if it is not possible to add the step, or 1 if it is possible
*/
public int possibleStep(Task task) {
int result;
Step lastStep = this.getLastStep();
int lastStepFinalTime = lastStep.getTask().getFinalTime();
int workedTimeIncrement;
if (lastStepFinalTime < 0) {
workedTimeIncrement = task.getTaskTime();
} else workedTimeIncrement = task.getTaskTime() + (task.getInitialTime() - lastStepFinalTime);
//DEBUG
//System.out.println("RESOURCE WORKDAY: " + workday);
//System.out.println("WORKED MINUTES: " + workedMinutes);
//System.out.println("WORK INCREMENT: " + workedTimeIncrement);
if ((workedMinutes + workedTimeIncrement) > workday) {
//Assignation not possible
result = 0;
} else {
result = 1;
}
return result;
}
public Resource clone(){
//System.out.println("CLONING RESOURCE " + resourceIndex);
return new Resource(baseStation, baseStationIndex, workday, resourceIndex, nTasks);
}
public int getWorkedMinutes() {
return workedMinutes;
}
//public void setWorkedMinutes(int workedMinutes) {
// this.workedMinutes = workedMinutes;
//}
public int getnTaskCovered() {
return nTaskCovered;
}
//public void setnTaskCovered(int nTaskCovered) {
// this.nTaskCovered = nTaskCovered;
//}
public int getnSteps() {
return nSteps;
}
public int getWorkday() {
return this.workday;
}
public int getResourceIndex() {
return resourceIndex;
}
}
| 31.496933 | 107 | 0.608882 |
0ceaf0dcd2b39c062f4a42c26c7edc66b6b59ee7 | 1,206 | package net.sourceforge.greenvine.generator.helper;
import java.util.Random;
public class RandomHelper {
private final static Random random = new Random();
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
private static final String NUMBERS = "123456789";
public char getRandomChar() {
return getRandomChar(ALPHABET);
}
public String getRandomNumericString(int length) {
return generateString(NUMBERS, length);
}
public String getRandomAlphabetString(int length) {
return generateString(ALPHABET, length);
}
public String getRandomBooleanString() {
return Boolean.valueOf(random.nextBoolean()).toString();
}
private static String generateString(String characters, int length)
{
if (length > 10) {
length = 10;
}
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = getRandomChar(characters);
}
return new String(text);
}
private static char getRandomChar(String characters) {
return characters.charAt(random.nextInt(characters.length()));
}
}
| 26.217391 | 72 | 0.634328 |
ca5a0a58d9bde5dc1d6eca721995f4d28da9d656 | 635 | package appleoctopus.lastword.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Created by lin1000 on 2017/3/26.
*/
public class Time {
public static String getCurrentTimeUTC(){
//follow iso8601 format within entire application and formalized in utc timezone
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
return nowAsISO;
}
}
| 27.608696 | 120 | 0.691339 |
2e853b637d922a1b2e10af50f00457a84f2f8624 | 1,155 | /*
* Copyright (c) 2021 Allette Systems pty. ltd.
*/
package org.pageseeder.xlsx.util;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
public class FileUtils {
/**
* Filters directories.
*/
public static final FileFilter DIR_FILTER = new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory();
}
};
/**
* Returns the content of the source file.
*
* @param source the source
* @return the string
* @throws IOException Signals that an I/O exception has occurred.
*/
public static String read(File source) throws IOException {
return read(source, "UTF-8");
}
/**
* Returns the content of the source file.
*
* @param source the source
* @return the string
* @throws IOException Signals that an I/O exception has occurred.
*/
public static String read(File source, String charset) throws IOException {
Charset encoding = Charset.forName(charset);
byte[] encoded = Files.readAllBytes(source.toPath());
return new String(encoded, encoding);
}
}
| 23.571429 | 77 | 0.679654 |
893a580033887e35d004e40ccc750a9ab19d833d | 3,334 | package jep.model.optimizationProblem.correctiveProcedure;
import java.util.Objects;
import jep.model.optimizationProblem.FitnessComparator;
import jep.model.optimizationProblem.InitialSolutionConstructor;
import jep.model.optimizationProblem.OptimizationProblem;
/**
* This class implements the threshold accepting procedure. Which is a corrective procedure using a
* threshold - which is decreased over time- to allow the acceptance of worse iterations (within the
* threshold-radius).
*
* @param <T> specific {@link OptimizationProblem}-instance this procedure is to be used for
*/
public class ThresholdAcceptingProcedure<T extends OptimizationProblem>
extends AbstractCorrectiveProcedure<T> {
private final ThresholdSinkingFunction thresholdSinkingFunction;
/**
* Constructs a new {@link ThresholdAcceptingProcedure}-instance.
*
* @param initialSolutionCosntructor {@link InitialSolutionConstructor}-instance which is used
* to construct the initial solution
* @param fitnessComperator {@link FitnessComparator}-instance used to compare the fitness of
* two solutions to validate if a neighbor is accepted as new solution
* @param neighborFunction {@link NeighborFunction}-instance which is used to construct
* neighbors
* @param acceptanceFunction {@link AcceptanceFunction}-instance which is used to validate if a
* new neighbor is accepted
* @param breakCondition {@link BreakCondition}-instance which is used to check if the procedure
* is to be terminated
* @param thresholdSinkingFunction {@link ThresholdSinkingFunction}-instance which handles the
* threshold logic
* @param thresholdBreakCondition algorithm specific break condition which is terminate the
* procedure parallel to the "general" break condition
*/
public ThresholdAcceptingProcedure(InitialSolutionConstructor<T> initialSolutionCosntructor,
FitnessComparator<T> fitnessComperator, NeighborFunction<T> neighborFunction,
BreakCondition<T> breakCondition, ThresholdSinkingFunction thresholdSinkingFunction,
ThresholdBreakCondition thresholdBreakCondition) {
super(initialSolutionCosntructor, fitnessComperator, neighborFunction,
(currentSolution, neighbor, comperator) -> {
if (fitnessComperator.getFitnessDifference(currentSolution, neighbor)
- thresholdSinkingFunction.getThreshold() <= 0) {
return true;
} else {
thresholdSinkingFunction.notifyAboutWorseIteration();
return false;
}
}, (currentSolution, iterationCount, iterationWithAcceptanceCount) -> {
return breakCondition.isFulfilled(currentSolution, iterationCount,
iterationWithAcceptanceCount)
|| thresholdBreakCondition
.isFulfilled(thresholdSinkingFunction.getThreshold());
});
this.thresholdSinkingFunction = Objects.requireNonNull(thresholdSinkingFunction);
}
@Override
public void reset() {
thresholdSinkingFunction.reset();
}
}
| 49.761194 | 100 | 0.692561 |
Subsets and Splits