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
|
---|---|---|---|---|---|
1de370a0335cd4688b2efe3fcfe74c0a3f66af19 | 2,612 | /*****************************************************************
|
| Cryptanium Secure Key Box
|
| $Id: ImportExport.java 7790 2016-01-05 09:52:35Z kstraupe $
|
| This software is provided to you pursuant to your Software
| license agreement (SLA) with whiteCryption Corporation
| ("whiteCryption") and Intertrust Technologies Corporation
| ("Intertrust"). This software may be used only in accordance
| with the terms of this agreement.
|
| Copyright (c) 2000-2016, whiteCryption Corporation. All rights reserved.
| Copyright (c) 2004-2016, Intertrust Technologies Corporation. All rights reserved.
|
****************************************************************/
package com.zcwfeng.fastdev.secure.skb.binding;
//The engine class which instantiates the objects:
import com.cryptanium.skb.Engine;
//The SecureData class, used for key storage:
import com.cryptanium.skb.SecureData;
//Parameters, used for raw bytes SecureData generation:
import com.cryptanium.skb.parameters.RawBytesParameters;
import com.cryptanium.skb.SkbException;
/**
* This example demonstrates the use of AES algorithm for
* <ul>
* <li>Import/export</li>
* <li>Encryption/decryption</li>
* <li>Wrap/Unwrap</li>
* </ul>
*/
public class ImportExport
{
public static void run(Logger log)
{
try
{
log.logInfo("Key import/export");
/* Exporting secure data: */
// Generate 128bit AES key
SecureData generated = Engine.generateSecureData(SecureData.DataType.SKB_DATA_TYPE_BYTES, new RawBytesParameters(16));
log.logDebug("SecureData info before export:");
log.dumpSecureDataInfo(generated);
// Export secure data. Persistent is used in order to save / load data later.
// As of now, the second parameter should always be null.
byte[] exportedBytes = generated.export(SecureData.ExportTarget.SKB_EXPORT_TARGET_PERSISTENT, null);
// Now, you can save those bytes for later use.
/* Importing secure data: */
SecureData imported = Engine.createDataFromExported(exportedBytes);
log.logDebug("SecureData info after import:");
log.dumpSecureDataInfo(imported);
log.logDebug("Key import/export done");
}
catch (SkbException e)
{
log.logError(e.getMessage());
}
catch (Exception e)
{
log.logError("Internal error: " + e.getMessage());
}
}
}
| 33.487179 | 131 | 0.61026 |
29d5fe1768f1af51a9ad3ad47064762e718e33a1 | 873 | package com.yx.sys.common;
/**
* sys_content表中的content_model_type字段描述
*
* @author lilulu
* @since 2018/08/17 16:16
*/
public enum SysContentStatusEnum {
UNPUBLISH(0,"待发布"),
PUBLISH(1,"发布"),
DOWNLINE(2,"下线");
/**
* 成员变量
*/
private int status;//状态值
private String desc;//描述
public int getStatus() {
return status;
}
public String getDesc() {
return desc;
}
/**
* 构造方法
* @param status
* @param desc
*/
private SysContentStatusEnum(int status, String desc) {
this.status=status;
this.desc=desc;
}
public static String getDesc(int status) {
for(SysContentStatusEnum demo: SysContentStatusEnum.values()) {
if(demo.getStatus()==status) {
return demo.getDesc();
}
}
return null;
}
}
| 18.1875 | 71 | 0.55441 |
a086d73d8db34ce0192dd34e6a1fb231902c1a72 | 519 | package fr.rtgrenoble.velascof.simtelui.task;
import javafx.application.Platform;
import javafx.concurrent.Task;
import org.controlsfx.dialog.ExceptionDialog;
public abstract class TaskBase extends Task<Void> {
@Override
protected Void call() {
try {
call0();
} catch (Throwable t) {
t.printStackTrace();
Platform.runLater(() -> new ExceptionDialog(t).show());
}
return null;
}
protected abstract void call0() throws Throwable;
}
| 22.565217 | 67 | 0.639692 |
9fa3717bb52869003d6551f86b250b2195e6cc54 | 3,817 | package br.com.cadastrodepessoas.util;
import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.KeyListener;
import android.text.method.NumberKeyListener;
import android.util.AttributeSet;
import android.widget.EditText;
public class EditTextCep extends androidx.appcompat.widget.AppCompatEditText {
private boolean isUpdating;
/*
* Mapeia a posição do cursor do número de telefone para o número com máscara... 1234567890
* => 12345-678
*/
private int positioning[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9 };
public EditTextCep(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public EditTextCep(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public EditTextCep(Context context) {
super(context);
initialize();
}
public String getCleanText() {
String text = EditTextCep.this.getText().toString();
text.replaceAll("[^0-9]*", "");
return text;
}
private void initialize() {
final int maxNumberLength = 8;
this.setKeyListener((KeyListener) keylistenerNumber);
this.setText(" - ");
this.setSelection(1);
this.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String current = s.toString();
/*
* Definindo um sinalizador de que estamos realmente
* atualizando o texto, para não precisar atualizá-lo de novo...
*/
if (isUpdating) {
isUpdating = false;
return;
}
/* Retira qualquer dígito não numérico da String... */
String number = current.replaceAll("[^0-9]*", "");
if (number.length() > 8)
number = number.substring(0, 8);
int length = number.length();
/* Completa número para 10 caracteres... */
String paddedNumber = padNumber(number, maxNumberLength);
/* Separa o número em partes... */
String part1 = paddedNumber.substring(0, 5);
String part2 = paddedNumber.substring(5, 8);
/* Constrói a máscara... */
String cep = part1 + "-" + part2;
/*
* Desativa evento afterTextChanged através da Flag
*/
isUpdating = true;
EditTextCep.this.setText(cep);
EditTextCep.this.setSelection(positioning[length]);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
protected String padNumber(String number, int maxLength) {
String padded = new String(number);
for (int i = 0; i < maxLength - number.length(); i++)
padded += " ";
return padded;
}
private final KeylistenerNumber keylistenerNumber = new KeylistenerNumber();
private class KeylistenerNumber extends NumberKeyListener {
public int getInputType() {
return InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
}
@Override
protected char[] getAcceptedChars() {
return new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
}
}
} | 28.916667 | 95 | 0.549908 |
ba5a2ce3764d8474e6e19b1432797cba16a6a0bb | 5,422 | package com.am.server.api.bulletin.service.impl;
import com.am.server.api.bulletin.dao.rdb.BulletinDao;
import com.am.server.api.bulletin.pojo.BulletinExpiredDelayedImpl;
import com.am.server.api.bulletin.pojo.Status;
import com.am.server.api.bulletin.pojo.ao.BulletinListAo;
import com.am.server.api.bulletin.pojo.ao.SaveBulletinAo;
import com.am.server.api.bulletin.pojo.ao.UpdateBulletinAo;
import com.am.server.api.bulletin.pojo.po.BulletinDo;
import com.am.server.api.bulletin.pojo.vo.BulletinContentVo;
import com.am.server.api.bulletin.pojo.vo.BulletinListVo;
import com.am.server.api.bulletin.service.BulletinService;
import com.am.server.api.user.pojo.po.AdminUserDo;
import com.am.server.common.annotation.transaction.Commit;
import com.am.server.common.annotation.transaction.ReadOnly;
import com.am.server.common.base.pojo.vo.PageVO;
import com.am.server.common.base.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.DelayQueue;
import java.util.stream.Collectors;
/**
* @author 阮雪峰
* @date 2018/11/13 13:05
*/
@Service
public class BulletinServiceImpl implements BulletinService {
private final BulletinDao bulletinDao;
private final CommonService commonService;
private final DelayQueue<BulletinExpiredDelayedImpl> delayQueue;
private final SimpMessagingTemplate simpMessagingTemplate;
@Autowired
public BulletinServiceImpl(BulletinDao bulletinDao, CommonService commonService, DelayQueue<BulletinExpiredDelayedImpl> delayQueue, SimpMessagingTemplate simpMessagingTemplate) {
this.bulletinDao = bulletinDao;
this.commonService = commonService;
this.delayQueue = delayQueue;
this.simpMessagingTemplate = simpMessagingTemplate;
}
@ReadOnly
@Override
public PageVO<BulletinListVo> list(BulletinListAo bulletinAo) {
Page<BulletinDo> page = bulletinDao.findAll(bulletinAo);
return new PageVO<BulletinListVo>()
.setPage(bulletinAo.getPage())
.setPageSize(bulletinAo.getPageSize())
.setTotal((int) page.getTotalElements())
.setTotalPage(page.getTotalPages())
.setRows(
page.getContent()
.stream().map(bulletin ->
new BulletinListVo().setId(bulletin.getId())
.setTitle(bulletin.getTitle())
.setContent(bulletin.getContent())
.setCreatedTime(bulletin.getCreatedTime())
.setCreatorBy(Optional.ofNullable(bulletin.getCreatedBy()).map(AdminUserDo::getUsername).orElse(""))
.setDate(bulletin.getDate())
.setDays(bulletin.getDays())
.setStatus(bulletin.getStatus())
).collect(Collectors.toList())
);
}
@Commit
@Override
public void save(SaveBulletinAo saveBulletinAo) {
BulletinDo bulletinDo = new BulletinDo()
.setStatus(Status.UNPUBLISHED)
.setTitle(saveBulletinAo.getTitle())
.setContent(saveBulletinAo.getContent())
.setDays(saveBulletinAo.getDays());
bulletinDao.save(bulletinDo);
}
@Commit
@Override
public void update(UpdateBulletinAo updateBulletinAo) {
bulletinDao.findById(updateBulletinAo.getId())
.ifPresent(bulletinDo -> {
bulletinDo.setTitle(updateBulletinAo.getTitle())
.setContent(updateBulletinAo.getContent())
.setDays(updateBulletinAo.getDays());
bulletinDao.save(bulletinDo);
});
}
@Commit
@Override
public void publish(Long id) {
bulletinDao.findById(id)
.ifPresent(bulletin -> {
LocalDate nowDate = LocalDate.now();
bulletin.setStatus(Status.PUBLISHED)
.setDate(nowDate);
bulletinDao.save(bulletin);
delayQueue.put(new BulletinExpiredDelayedImpl(id, nowDate.atStartOfDay().plusDays(bulletin.getDays())));
BulletinContentVo vo = new BulletinContentVo().setTitle(bulletin.getTitle()).setContent(bulletin.getContent());
simpMessagingTemplate.convertAndSend("/topic/bulletin", vo);
});
}
@ReadOnly
@Override
public List<BulletinDo> findPublishedAndUnexpiredList() {
return bulletinDao.findByStatusOrderByIdDesc(Status.PUBLISHED);
}
@Commit
@Override
public void delete(Long id) {
bulletinDao.deleteById(id);
delayQueue.remove(new BulletinExpiredDelayedImpl(id, LocalDateTime.now()));
}
@Commit
@Override
public void expire(Long id) {
bulletinDao.findById(id).ifPresent(bulletin -> bulletinDao.save(bulletin.setStatus(Status.EXPIRED)));
}
}
| 39.576642 | 182 | 0.646625 |
dd64175b466c65f622054a5357c95b1ab9454e99 | 2,230 | package com.stx.xhb.dmgameapp.mvp.ui.main;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.widget.TextView;
import com.stx.core.base.BaseFragment;
import com.stx.core.base.BaseMvpFragment;
import com.stx.xhb.dmgameapp.R;
import com.stx.xhb.dmgameapp.mvp.ui.adapter.GameViewPagerFragmentAdapter;
import com.stx.xhb.dmgameapp.mvp.ui.game.ChinesizeFragment;
import com.stx.xhb.dmgameapp.mvp.ui.game.CategoryFragment;
import com.stx.xhb.dmgameapp.mvp.ui.game.GameRankFragment;
import com.stx.xhb.dmgameapp.mvp.ui.game.HotGameFragment;
import com.stx.xhb.dmgameapp.mvp.ui.game.SaleFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
/**
* 视频的Fragment
*/
public class GameFragment extends BaseFragment{
@Bind(R.id.title)
TextView mTitle;
@Bind(R.id.tabLayout)
TabLayout mTabLayout;
@Bind(R.id.video_viewpager)
ViewPager mVideoViewpager;
public static GameFragment newInstance() {
return new GameFragment();
}
@Override
protected int getLayoutResource() {
return R.layout.fragment_game;
}
@Override
protected void onInitView(Bundle savedInstanceState) {
initView();
}
@Override
protected void lazyLoad() {
}
//获取控件
private void initView() {
mTitle.setText("游戏");
setAdapter();
}
//设置适配器
private void setAdapter() {
List<BaseMvpFragment> fragmentList = new ArrayList<>();
fragmentList.add(HotGameFragment.newInstance());
fragmentList.add(SaleFragment.newInstance());
fragmentList.add(ChinesizeFragment.newInstance());
fragmentList.add(GameRankFragment.newInstance());
fragmentList.add(CategoryFragment.newInstance());
GameViewPagerFragmentAdapter adapter = new GameViewPagerFragmentAdapter(getChildFragmentManager(), fragmentList);
mVideoViewpager.setAdapter(adapter);
mVideoViewpager.setOffscreenPageLimit(fragmentList.size());
mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mTabLayout.setTabMode(TabLayout.MODE_FIXED);
mTabLayout.setupWithViewPager(mVideoViewpager);
}
}
| 28.589744 | 121 | 0.727354 |
a5628be52533d0ca5e2929ae06f4f5d0ea55979d | 397 | package com.adhikari.photoalbum.service;
import java.util.stream.Stream;
import org.springframework.web.multipart.MultipartFile;
import com.adhikari.photoalbum.model.ResourceEntity;
public interface ResourcesService {
public ResourceEntity uploadResource(MultipartFile multi);
public ResourceEntity downloadResource(String fileId);
public Stream<ResourceEntity> getAllResources();
}
| 22.055556 | 59 | 0.826196 |
1ec862301c154fb8e3e84f21d35eb28be79cfcfa | 886 | package org.radartools.detection;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ProbabilityTest {
@Test
void testValidProbabilities() {
try {
Probability valid = new Probability(1.0);
assertEquals(valid.getValue(),1.0);
valid = new Probability(0.0);
assertEquals(valid.getValue(),0.0);
valid = new Probability(0.5);
assertEquals(valid.getValue(),0.5);
} catch (Exception e) {
fail("Testing a valid probability caused an exception");
e.printStackTrace();
}
}
@Test
void testInvalidProbabilities() {
try {
Probability invalid = new Probability(3.0);
fail("Testing an invalid probability did not cause an exception");
} catch (Exception e) {
}
}
} | 27.6875 | 78 | 0.58465 |
086430f716f5bcb66f3586450b0ca6aac105bc89 | 765 |
package dhbw.wwi.vertsys.javaee.jtodo.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für time complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="time">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "time")
public class Time {
}
| 23.181818 | 102 | 0.65098 |
46e967ae2b70fd0dd8d48ab402648b7ac7a2c885 | 5,346 | /*
* Copyright © 2013-2019, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.business.internal.assembler;
import com.google.inject.ConfigurationException;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import javax.inject.Inject;
import org.javatuples.Tuple;
import org.seedstack.business.assembler.Assembler;
import org.seedstack.business.assembler.AssemblerRegistry;
import org.seedstack.business.domain.AggregateRoot;
import org.seedstack.business.internal.BusinessErrorCode;
import org.seedstack.business.internal.BusinessException;
import org.seedstack.business.util.Tuples;
class AssemblerRegistryImpl implements AssemblerRegistry {
private final Injector injector;
@Inject
AssemblerRegistryImpl(Injector injector) {
this.injector = injector;
}
@Override
public <A extends AggregateRoot<?>, D> Assembler<A, D> getAssembler(Class<A> aggregateRootClass,
Class<D> dtoClass) {
return findAssemblerOf(aggregateRootClass, dtoClass, null, null);
}
@Override
public <A extends AggregateRoot<?>, D> Assembler<A, D> getAssembler(Class<A> aggregateRootClass, Class<D> dtoClass,
@Nullable Annotation qualifier) {
return findAssemblerOf(aggregateRootClass, dtoClass, qualifier, null);
}
@Override
public <A extends AggregateRoot<?>, D> Assembler<A, D> getAssembler(Class<A> aggregateRootClass, Class<D> dtoClass,
@Nullable Class<? extends Annotation> qualifier) {
return findAssemblerOf(aggregateRootClass, dtoClass, null, qualifier);
}
@Override
public <T extends Tuple, D> Assembler<T, D> getTupleAssembler(
Class<? extends AggregateRoot<?>>[] aggregateRootClasses, Class<D> dtoClass) {
return findAssemblerOf(classesToTupleType(aggregateRootClasses), dtoClass, null, null);
}
@Override
public <T extends Tuple, D> Assembler<T, D> getTupleAssembler(
Class<? extends AggregateRoot<?>>[] aggregateRootClasses, Class<D> dtoClass, Annotation qualifier) {
return findAssemblerOf(classesToTupleType(aggregateRootClasses), dtoClass, qualifier, null);
}
@Override
public <T extends Tuple, D> Assembler<T, D> getTupleAssembler(
Class<? extends AggregateRoot<?>>[] aggregateRootClasses, Class<D> dtoClass,
@Nullable Class<? extends Annotation> qualifier) {
return findAssemblerOf(classesToTupleType(aggregateRootClasses), dtoClass, null, qualifier);
}
private Type classesToTupleType(Class<? extends AggregateRoot<?>>[] aggregateRootClasses) {
return Types.newParameterizedType(Tuples.classOfTuple(aggregateRootClasses.length), aggregateRootClasses);
}
@SuppressWarnings("unchecked")
private <T, D> Assembler<T, D> findAssemblerOf(Type aggregateRoot, Class<D> dto, @Nullable Annotation qualifier,
@Nullable Class<? extends Annotation> qualifierClass) {
Assembler<T, D> o;
try {
if (qualifier != null) {
o = (Assembler<T, D>) getInstance(Assembler.class, qualifier, aggregateRoot, dto);
} else if (qualifierClass != null) {
o = (Assembler<T, D>) getInstance(Assembler.class, qualifierClass, aggregateRoot, dto);
} else {
o = (Assembler<T, D>) getInstance(Assembler.class, aggregateRoot, dto);
}
} catch (ConfigurationException e) {
BusinessException seedException = BusinessException.createNew(
BusinessErrorCode.UNABLE_TO_FIND_ASSEMBLER_WITH_QUALIFIER)
.put("aggregateRoot", aggregateRoot)
.put("dto", dto);
if (qualifier != null) {
seedException.put("qualifier", qualifier);
throw seedException;
} else if (qualifierClass != null) {
seedException.put("qualifier", qualifierClass.getSimpleName());
throw seedException;
} else {
throw BusinessException.createNew(BusinessErrorCode.UNABLE_TO_FIND_ASSEMBLER)
.put("aggregateRoot", aggregateRoot)
.put("dto", dto);
}
}
return o;
}
private Object getInstance(Type rawType, Class<? extends Annotation> qualifier, Type... typeArguments) {
return injector.getInstance(
Key.get(TypeLiteral.get(Types.newParameterizedType(rawType, typeArguments)), qualifier));
}
private Object getInstance(Type rawType, Annotation qualifier, Type... typeArguments) {
return injector.getInstance(
Key.get(TypeLiteral.get(Types.newParameterizedType(rawType, typeArguments)), qualifier));
}
private Object getInstance(Type rawType, Type... typeArguments) {
return injector.getInstance(Key.get(TypeLiteral.get(Types.newParameterizedType(rawType, typeArguments))));
}
}
| 43.819672 | 119 | 0.682192 |
489153e3e5400acb5ebbf718ea9f6186bc66402f | 330 | package com.moodysalem.graphbuilder.core.inputs;
/**
* All binding interfaces that contain some information about a specific field inherit from this
* interface.
*/
interface FieldInformation {
/**
* @return the position in the GraphQL schema where the information is associated.
*/
SchemaPosition getPosition();
}
| 23.571429 | 96 | 0.748485 |
3d7a4fdf74a711826c4f800e76fa4ce0a627e6e9 | 1,378 | package euler;
public class P023NonabundantSums {
public static boolean isAbundant(int n) {
int i = 0, sum = 1;
for (i = 2; i * i < n; i++) {
if (n % i == 0)
sum += i + n / i;
}
if (i * i == n)
sum += i;
// System.out.println(n+" "+sum);
if (sum > n)
return true;
return false;
}
public static void main(String[] args) {
int i = 0, j = 0, n = 0;
final int N = 28123;
int abundant[] = new int[N];
for (i = 1; i < N; i++) {
if (isAbundant(i)) {
abundant[j++] = i;
}
}
// for (i = 0; i < j; i++) {
// System.out.println(abundant[i]+" "+i);
// }
// *******************************version1 much slower********************************
// int length = j, sum = 0;
// out: for (n = 1; n <= N; n++) {
// for (i = 0; i < length; i++) {
// for (j = i; j < length; j++) {
// if (n == abundant[i] + abundant[j]) {
// continue out;
// }
// }
// }
// sum += n;
// }
// *************************************************************************************
int length = j, sum = 0;
boolean[] number = new boolean[N];
for (i = 0; i < length; i++) {
for (j = i; j < length; j++) {
n = abundant[i] + abundant[j];
if (n < N && number[n] == false) {
number[n] = true;
}
}
}
for (i = 1; i < N; i++) {
if (number[i] == false)
sum += i;
}
System.out.println(sum);
}
}
| 20.878788 | 90 | 0.403483 |
d51119135e3453aa81e41099a98062a62009b9d9 | 1,726 | package gov.vha.isaac.ochre.api.collections;
import org.apache.mahout.math.map.OpenObjectIntHashMap;
import java.util.OptionalInt;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.ObjIntConsumer;
import org.apache.mahout.math.function.ObjectIntProcedure;
/**
* Created by kec on 12/18/14.
* @param <T> Type of object in map.
*/
public class ConcurrentObjectIntMap<T> {
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock read = rwl.readLock();
private final Lock write = rwl.writeLock();
OpenObjectIntHashMap<T> backingMap = new OpenObjectIntHashMap<>();
public void forEachPair(ObjIntConsumer<T> consumer) {
backingMap.forEachPair((T first, int second) -> {
consumer.accept(first, second);
return true;
});
}
public boolean containsKey(T key) {
try {
read.lock();
return backingMap.containsKey(key);
} finally {
if (read != null)
read.unlock();
}
}
public OptionalInt get(T key) {
try {
read.lock();
if (backingMap.containsKey(key)) {
return OptionalInt.of(backingMap.get(key));
}
return OptionalInt.empty();
} finally {
if (read != null)
read.unlock();
}
}
public boolean put(T key, int value) {
try {
write.lock();
return backingMap.put(key, value);
} finally {
if (write != null)
write.unlock();
}
}
public int size() {
return backingMap.size();
}
}
| 24.657143 | 73 | 0.5927 |
c2dac5c145e4d89964fe1f8e55c3ed142490e8d2 | 3,214 | package com.transcendensoft.hedbanz.presentation.friends.list.delegates;
/**
* Copyright 2017. Andrii Chernysh
* <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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hannesdorfmann.adapterdelegates3.AdapterDelegate;
import com.transcendensoft.hedbanz.R;
import com.transcendensoft.hedbanz.domain.entity.Friend;
import com.transcendensoft.hedbanz.presentation.friends.list.holder.AcceptedFriendViewHolder;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.subjects.PublishSubject;
/**
* This delegate is responsible for creating
* {@link com.transcendensoft.hedbanz.presentation.friends.list.holder.AcceptedFriendViewHolder}
* and binding ViewHolder widgets according to model.
* <p>
* An AdapterDelegate get added to an AdapterDelegatesManager.
* This manager is the man in the middle between RecyclerView.
* Adapter and each AdapterDelegate.
*
* @author Andrii Chernysh. E-mail: [email protected]
* Developed by <u>Transcendensoft</u>
*/
public class AcceptedFriendAdapterDelegate extends AdapterDelegate<List<Friend>> {
private PublishSubject<Friend> removeFriendSubject = PublishSubject.create();
@Inject
public AcceptedFriendAdapterDelegate() {}
@Override
protected boolean isForViewType(@NonNull List<Friend> items, int position) {
return items.get(position).isAccepted() && !items.get(position).isPending();
}
@NonNull
@Override
protected RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
Context context = parent.getContext();
View itemView = LayoutInflater.from(context)
.inflate(R.layout.item_friend_accepted, parent, false);
return new AcceptedFriendViewHolder(itemView);
}
@Override
protected void onBindViewHolder(@NonNull List<Friend> items, int position,
@NonNull RecyclerView.ViewHolder holder,
@NonNull List<Object> payloads) {
Friend friend = items.get(position);
AcceptedFriendViewHolder acceptedFriendViewHolder = (AcceptedFriendViewHolder) holder;
acceptedFriendViewHolder.bindName(friend.getLogin());
acceptedFriendViewHolder.bindIcon(friend.getIconId().getResId());
acceptedFriendViewHolder.removeFriendObservable(friend)
.subscribe(removeFriendSubject);
}
public PublishSubject<Friend> getRemoveFriendSubject() {
return removeFriendSubject;
}
}
| 37.811765 | 96 | 0.741444 |
2dfeb5dad44cde09d66ff72729f8ef94d20d6c4b | 7,946 | /*
* Copyright 2018 Otso Björklund.
* Distributed under the MIT license (see LICENSE.txt or https://opensource.org/licenses/MIT).
*/
package org.wmn4j.notation.elements;
import java.util.Objects;
/**
* The <code>Pitch</code> class represents a pitch. Pitches consist of the basic
* pitch letter <code>Pitch.Base</code>, alter number which tells by how many
* half-steps the pitch is altered, and octave number which tells the octave of
* the note. Octave number is based on
* <a href="http://en.wikipedia.org/wiki/Scientific_pitch_notation">scientific
* pitch notation</a>. This class is immutable.
*/
public final class Pitch implements Comparable<Pitch> {
/**
* The letter in a pitch name.
*/
public enum Base {
/**
* The base letter C in the pitch name.
*/
C(0),
/**
* The base letter D in the pitch name.
*/
D(2),
/**
* The base letter E in the pitch name.
*/
E(4),
/**
* The base letter F in the pitch name.
*/
F(5),
/**
* The base letter G in the pitch name.
*/
G(7),
/**
* The base letter A in the pitch name.
*/
A(9),
/**
* The base letter B in the pitch name.
*/
B(11);
private final int pitchAsInt;
Base(int pitchAsInt) {
this.pitchAsInt = pitchAsInt;
}
}
/**
* The limit for altering notes in half-steps (=3).
*/
public static final int ALTER_LIMIT = 3;
/**
* Highest allowed octave number (=10).
*/
public static final int MAX_OCTAVE = 10;
private final Base pitchBase;
private final int alter;
private final int octave;
/**
* Returns a <code>Pitch</code> object.
*
* @throws IllegalArgumentException if alter is greater than {@link #ALTER_LIMIT
* ALTER_LIMIT} of smaller than
* {@link #ALTER_LIMIT -1*ALTER_LIMIT}, or if
* octave is negative or larger than
* {@link #MAX_OCTAVE MAX_OCTAVE}.
* @param pitchName the letter on which the name of the pitch is based.
* @param alter by how many half-steps the pitch is altered up (positive
* values) or down (negative values).
* @param octave the octave of the pitch.
* @return Pitch object with the specified attributes.
*/
public static Pitch getPitch(Base pitchName, int alter, int octave) {
if (alter > ALTER_LIMIT || alter < -1 * ALTER_LIMIT) {
throw new IllegalArgumentException(
"alter was " + alter + ". alter must be between -" + ALTER_LIMIT + " and " + ALTER_LIMIT);
}
if (octave < 0 || octave > MAX_OCTAVE) {
throw new IllegalArgumentException("octave was " + octave + ". octave must be between 0 and " + MAX_OCTAVE);
}
return new Pitch(pitchName, alter, octave);
}
/**
* Private constructor. To get a <code>Pitch</code> object use the method
* {@link #getPitch(wmnlibnotation.Pitch.Base, int, int) getPitch}.
*
* @param pitchName the letter on which the name of the pitch is based.
* @param alter by how many half-steps the pitch is altered up or down.
* @param octave the octave of the pitch.
*/
private Pitch(Base pitchName, int alter, int octave) {
this.pitchBase = pitchName;
this.alter = alter;
this.octave = octave;
}
/**
* Returns the letter in the pitch name.
*
* @return the letter on which the name of the pitch is based.
*/
public Base getBase() {
return this.pitchBase;
}
/**
* Returns by how many half-steps the pitch is altered.
*
* @return by how many half-steps the pitch is altered up (positive value) or
* down (negative value).
*/
public int getAlter() {
return this.alter;
}
/**
* Returns the octave number.
*
* @return octave number of this pitch.
*/
public int getOctave() {
return this.octave;
}
/**
* Get an integer representation of this <code>Pitch</code>. This is the MIDI
* number of the pitch (middle-C, C4, being 60). A <code>Pitch</code> is
* transformed into an integer using the formula
* <code> pitchAsInteger = base + alter + (octave + 1) * 12 </code>, where base
* is defined by the letter in the pitch name: C = 0, D = 2, E = 4, F = 5, G =
* 7, A = 9, B = 11. Alter is the number of sharps, or the number of flats * -1.
* For example, <code>C#4 = 0 + 1 + 5 * 12 = 61</code> and
* <code>Db4 = 2 - 1 + 5 * 12 = 61</code>.
*
* @return this Pitch as an integer.
*/
public int toInt() {
return this.pitchBase.pitchAsInt + this.alter + (this.octave + 1) * 12;
}
/**
* Returns the PitchClass of this Pitch.
*
* @return the <a href="http://en.wikipedia.org/wiki/Pitch_class">pitch
* class</a> of this Pitch.
*/
public PitchClass getPitchClass() {
return PitchClass.fromInt(this.toInt());
}
/**
* Returns the pitch class number of this pitch.
*
* @return pitch class number of this pitch.
*/
public int getPCNumber() {
return this.toInt() % 12;
}
/**
* Test enharmonic equality. Compare this to other for
* <a href="http://en.wikipedia.org/wiki/Enharmonic">enharmonic</a> equality.
*
* @param other Pitch against which this is compared.
* @return true if this is enharmonically equal to other, otherwise false.
*/
public boolean equalsEnharmonically(Pitch other) {
return this.toInt() == other.toInt();
}
/**
* String representation of <code>Pitch</code>. <code>Pitch</code> objects are
* represented as strings of form <code>bao</code>, where <code>b</code> is the
* base letter in the pitch name, <code>a</code> is the alteration (sharps # or
* flats b), and <code>o</code> is the octave number. For example middle C-sharp
* is represented as the string <code>C#4</code>.
*
* @return the string representation of this Pitch.
*/
@Override
public String toString() {
String pitchName = this.pitchBase.toString();
if (alter >= 0) {
for (int i = 0; i < alter; ++i) {
pitchName += "#";
}
} else {
for (int i = 0; i > alter; --i) {
pitchName += "b";
}
}
return pitchName + octave;
}
/**
* Compare this <code>Pitch</code> for equality with <code>Object o</code>. Two
* objects of class <code>Pitch</code> are equal if they have the same ' base
* letter, alterations (sharps or flats), and same octave. Pitches that are
* enharmonically the same but spelt differently are not equal. For example,
* <code>C#4 != Db4</code>.
*
* @param o Object against which this is compared for equality.
* @return true if Object o is of class Pitch and has the same, pitch base,
* alterations, and octave as this.
*/
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Pitch)) {
return false;
}
final Pitch other = (Pitch) o;
if (other.pitchBase != this.pitchBase) {
return false;
}
if (other.octave != this.octave) {
return false;
}
if (other.alter != this.alter) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 89 * hash + Objects.hashCode(this.pitchBase);
hash = 89 * hash + this.alter;
hash = 89 * hash + this.octave;
return hash;
}
/**
* Compare this pitch against other for pitch height.
*
* @param other the Pitch against which this is compared.
* @return negative integer if this is lower than other, positive integer if
* this is higher than other, 0 if pitches are (enharmonically) of same
* height.
*/
@Override
public int compareTo(Pitch other) {
return this.toInt() - other.toInt();
}
/**
* @param other the Pitch against which this is compared.
* @return true if this is higher than other, false otherwise.
*/
public boolean higherThan(Pitch other) {
return this.toInt() > other.toInt();
}
/**
* @param other the Pitch against which this is compared.
* @return true if this is lower than other, false otherwise.
*/
public boolean lowerThan(Pitch other) {
return this.toInt() < other.toInt();
}
}
| 26.935593 | 111 | 0.640951 |
c23f9d69005767328175dddf88942d123aa36908 | 413 | package com.unifig.bi.analysis.service;
import com.unifig.bi.analysis.model.StSmsNavigation;
import com.baomidou.mybatisplus.service.IService;
import java.sql.Date;
import java.util.Map;
/**
* <p>
* 导航栏 服务类
* </p>
*
*
* @since 2019-03-22
*/
public interface StSmsNavigationService extends IService<StSmsNavigation> {
Map<String, Object> line(Date startDate, Date stopDate, String navigationId);
}
| 18.772727 | 81 | 0.738499 |
b6be0518619838292bbb2a65663504229dedd368 | 1,764 | package com.heyue.wms.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.heyue.common.core.annotation.Excel;
import com.heyue.common.core.web.domain.BaseEntity;
/**
* 出库单快照对象 wms_outstore_history
*
* @author wchu
* @date 2021-08-09
*/
public class WmsOutstoreHistory extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** id */
private Long id;
/** 出库单 */
@Excel(name = "出库单")
private Long outOrderId;
/** 内容 */
@Excel(name = "内容")
private String outOrderContent;
/** 状态 */
@Excel(name = "状态")
private String orderStatus;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setOutOrderId(Long outOrderId)
{
this.outOrderId = outOrderId;
}
public Long getOutOrderId()
{
return outOrderId;
}
public void setOutOrderContent(String outOrderContent)
{
this.outOrderContent = outOrderContent;
}
public String getOutOrderContent()
{
return outOrderContent;
}
public void setOrderStatus(String orderStatus)
{
this.orderStatus = orderStatus;
}
public String getOrderStatus()
{
return orderStatus;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("outOrderId", getOutOrderId())
.append("outOrderContent", getOutOrderContent())
.append("updateTime", getUpdateTime())
.append("orderStatus", getOrderStatus())
.toString();
}
}
| 21.777778 | 71 | 0.621315 |
106e7c54b847701b7ca73134116eb4959796a55b | 172 | package com.google.android.play.core.internal;
public final class ar extends RuntimeException {
public ar() {
super("Failed to bind to the service.");
}
}
| 21.5 | 48 | 0.680233 |
fcafc3d67288a38e55a6f7001aaeccdbe676569a | 5,299 | /**
* Copyright (C) 2019 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.opengamma.financial.security.bond;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import org.testng.annotations.Test;
import com.opengamma.financial.AbstractBeanTestCase;
import com.opengamma.financial.convention.daycount.DayCounts;
import com.opengamma.financial.convention.frequency.SimpleFrequency;
import com.opengamma.financial.convention.yield.SimpleYieldConvention;
import com.opengamma.financial.security.equity.EquitySecurity;
import com.opengamma.master.security.SecurityDocument;
import com.opengamma.util.money.Currency;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.time.DateUtils;
import com.opengamma.util.time.Expiry;
/**
* Tests for {@link BondSecuritySearchRequest}.
*/
@Test(groups = TestGroup.UNIT)
public class BondSecuritySearchRequestTest extends AbstractBeanTestCase {
private static final String ISSUER_NAME = "govt issuer name";
private static final String ISSUER_TYPE = "govt issuer type";
private static final BondSecurity BOND = new GovernmentBondSecurity(ISSUER_NAME, ISSUER_TYPE, "US", "GOVT", Currency.USD, SimpleYieldConvention.US_STREET,
new Expiry(DateUtils.getUTCDate(2029, 12, 15)), "Fixed", 0.003, SimpleFrequency.SEMI_ANNUAL, DayCounts.ACT_360, DateUtils.getUTCDate(2019, 12, 15),
DateUtils.getUTCDate(2019, 12, 15), DateUtils.getUTCDate(2019, 3, 15), 100d, 10000d, 10d, 1000d, 100d, 100d);
/**
* Tests that a document with the wrong name will not match.
*/
public void testWrongNameNoMatch() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
final SecurityDocument doc = new SecurityDocument(BOND);
doc.getSecurity().setName("bond");
request.setName("government bond");
assertFalse(request.matches(doc));
}
/**
* Tests that a document with the wrong security type will not match.
*/
public void testWrongSecurityTypeNoMatch() {
final EquitySecurity equity = new EquitySecurity("exch", "code", "co", Currency.USD);
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
final SecurityDocument doc = new SecurityDocument(equity);
assertFalse(request.matches(doc));
}
/**
* Tests that a document with the wrong issuer name will not match.
*/
public void testWrongIssuerNameNoMatch() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
request.setIssuerName(ISSUER_TYPE);
final SecurityDocument doc = new SecurityDocument(BOND);
assertFalse(request.matches(doc));
}
/**
* Tests that a document with the wrong issuer name will not match.
*/
public void testWrongIssuerNameWildcardNoMatch() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
request.setIssuerName("*Z*");
final SecurityDocument doc = new SecurityDocument(BOND);
assertFalse(request.matches(doc));
}
/**
* Tests that a document with the wrong issuer type will not match.
*/
public void testWrongIssuerTypeNoMatch() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
request.setIssuerType(ISSUER_NAME);
final SecurityDocument doc = new SecurityDocument(BOND);
assertFalse(request.matches(doc));
}
/**
* Tests that a document with the wrong issuer type will not match.
*/
public void testWrongIssuerTypeWildcardNoMatch() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
request.setIssuerType("*Z*");
final SecurityDocument doc = new SecurityDocument(BOND);
assertFalse(request.matches(doc));
}
/**
* Tests a matching document.
*/
public void testMatchingIssuerName() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
request.setIssuerName(ISSUER_NAME);
final SecurityDocument doc = new SecurityDocument(BOND);
assertTrue(request.matches(doc));
}
/**
* Tests a matching document.
*/
public void testMatchingIssuerNameWildcard() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
request.setIssuerName("*i*");
final SecurityDocument doc = new SecurityDocument(BOND);
assertTrue(request.matches(doc));
}
/**
* Tests a matching document.
*/
public void testMatchingIssuerType() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
request.setIssuerType(ISSUER_TYPE);
final SecurityDocument doc = new SecurityDocument(BOND);
assertTrue(request.matches(doc));
}
/**
* Tests a matching document.
*/
public void testMatchingIssuerTypeWildCard() {
final BondSecuritySearchRequest request = new BondSecuritySearchRequest();
request.setIssuerName("*i*");
final SecurityDocument doc = new SecurityDocument(BOND);
assertTrue(request.matches(doc));
}
@Override
public JodaBeanProperties<BondSecuritySearchRequest> getJodaBeanProperties() {
return new JodaBeanProperties<>(BondSecuritySearchRequest.class, Arrays.asList("issuerName", "issuerType"),
Arrays.<Object> asList(ISSUER_NAME, ISSUER_TYPE), Arrays.<Object> asList(ISSUER_TYPE, ISSUER_NAME));
}
} | 37.316901 | 156 | 0.750708 |
54968432991638c88aff467b5e858e709d254ef0 | 21,073 | package me.shouheng.utils.data;
import androidx.annotation.NonNull;
import android.text.format.DateUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import me.shouheng.utils.UtilsApp;
import me.shouheng.utils.constant.TimeConstants;
/**
* @author Shouheng Wang ([email protected])
* @version 2019/5/12 16:07
*/
public final class TimeUtils {
public static final long SECOND = 1000;
public static final long MINUTE = 60 * SECOND;
public static final long HOUR = 60 * MINUTE;
public static final long DAY = 24 * HOUR;
private static final int[] ZODIAC_FLAGS = {20, 19, 21, 21, 21, 22, 23, 23, 23, 24, 23, 22};
private static final String[] ZODIAC = {
"水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座",
"狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"
};
private static final String[] CHINESE_ZODIAC =
{"猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"};
// region *----------------------------- 昨天|今天|明天 ---------------------------------*
public static long now() {
return System.currentTimeMillis();
}
public static String nowString() {
return toString(System.currentTimeMillis(), getDefaultFormat());
}
public static String nowString(@NonNull final DateFormat format) {
return toString(System.currentTimeMillis(), format);
}
public static Date nowDate() {
return new Date();
}
/** Get millisecond of beginning of today. */
public static long beginOfToday() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/** Get millisecond of beginning of this week. */
public static long beginOfWeek(boolean sundayFirst) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long millis = calendar.getTimeInMillis();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (sundayFirst) {
millis -= (dayOfWeek-1) * DAY;
} else {
millis -= (dayOfWeek == Calendar.SUNDAY ? 6 : dayOfWeek-2) * DAY;
}
return millis;
}
/** Get millisecond of beginning of this month. */
public static long beginOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/** Get millisecond of beginning of this year. */
public static long beginOfYear() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/** Get millisecond of end of today. */
public static long endOfToday() {
return beginOfToday() + DAY - 1;
}
/** Get millisecond of end of this week. */
public static long endOfWeek(boolean sundayFirst) {
return beginOfWeek(sundayFirst) + 7*DAY - 1;
}
/** Get millisecond of end of this month. */
public static long endOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)+1);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis()-1;
}
/** Get millisecond of end of this year. */
public static long endOfYear() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR)+1);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis()-1;
}
// endregion
// region *---------------------------------- 转换 --------------------------------------*
public static String toString(final long millis) {
return toString(millis, getDefaultFormat());
}
public static String toString(final long millis, @NonNull final DateFormat format) {
return format.format(new Date(millis));
}
/**
* Time format output by system flags. See sample app for details.
*
* @param millis millis of time
* @param flags flags
* @return date string output
*/
public static String toString(long millis, int flags) {
return DateUtils.formatDateTime(UtilsApp.getApp(), millis, flags);
}
public static long toMillis(final String time) {
return toMillis(time, getDefaultFormat());
}
public static long toMillis(final String time, @NonNull final DateFormat format) {
try {
return format.parse(time).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return -1;
}
public static Date toDate(final String time) {
return toDate(time, getDefaultFormat());
}
public static Date toDate(final String time, @NonNull final DateFormat format) {
try {
return format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String toString(final Date date) {
return toString(date, getDefaultFormat());
}
public static String toString(final Date date, @NonNull final DateFormat format) {
return format.format(date);
}
public static String toString(final Date date, int flags) {
return toString(date.getTime(), flags);
}
public static long toMillis(final Date date) {
return date.getTime();
}
public static Date toDate(final long millis) {
return new Date(millis);
}
// endregion
// region *---------------------------------- 跨度 --------------------------------------*
public static long span(final String time1,
final String time2,
@TimeConstants.Unit final int unit) {
return span(time1, time2, getDefaultFormat(), unit);
}
public static long span(final String time1,
final String time2,
@NonNull final DateFormat format,
@TimeConstants.Unit final int unit) {
return toTimeSpan(toMillis(time1, format) - toMillis(time2, format), unit);
}
public static long span(final Date date1,
final Date date2,
@TimeConstants.Unit final int unit) {
return toTimeSpan(toMillis(date1) - toMillis(date2), unit);
}
public static long span(final long millis1,
final long millis2,
@TimeConstants.Unit final int unit) {
return toTimeSpan(millis1 - millis2, unit);
}
// endregion
// region *---------------------------------- 判断 --------------------------------------*
/**
* Return whether it is today.
* <p>The pattern is {@code yyyy-MM-dd HH:mm:ss}.</p>
*
* @param time The formatted time string.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isToday(final String time) {
return isToday(toMillis(time, getDefaultFormat()));
}
/**
* Return whether it is today.
*
* @param time The formatted time string.
* @param format The format.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isToday(final String time, @NonNull final DateFormat format) {
return isToday(toMillis(time, format));
}
/**
* Return whether it is today.
*
* @param date The date.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isToday(final Date date) {
return isToday(date.getTime());
}
/**
* Return whether it is today.
*
* @param millis The milliseconds.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isToday(final long millis) {
long wee = getWeeOfToday();
return millis >= wee && millis < wee + TimeConstants.DAY;
}
public static boolean isLeapYear(final String time) {
return isLeapYear(toDate(time, getDefaultFormat()));
}
public static boolean isLeapYear(final String time, @NonNull final DateFormat format) {
return isLeapYear(toDate(time, format));
}
public static boolean isLeapYear(final Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
return isLeapYear(year);
}
public static boolean isLeapYear(final long millis) {
return isLeapYear(toDate(millis));
}
public static boolean isLeapYear(final int year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
/**
* Return whether it is am.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAm() {
Calendar cal = Calendar.getInstance();
return cal.get(GregorianCalendar.AM_PM) == 0;
}
/**
* Return whether it is am.
* <p>The pattern is {@code yyyy-MM-dd HH:mm:ss}.</p>
*
* @param time The formatted time string.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAm(final String time) {
return getValueByCalendarField(time, getDefaultFormat(), GregorianCalendar.AM_PM) == 0;
}
/**
* Return whether it is am.
*
* @param time The formatted time string.
* @param format The format.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAm(final String time,
@NonNull final DateFormat format) {
return getValueByCalendarField(time, format, GregorianCalendar.AM_PM) == 0;
}
/**
* Return whether it is am.
*
* @param date The date.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAm(final Date date) {
return getValueByCalendarField(date, GregorianCalendar.AM_PM) == 0;
}
/**
* Return whether it is am.
*
* @param millis The milliseconds.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAm(final long millis) {
return getValueByCalendarField(millis, GregorianCalendar.AM_PM) == 0;
}
/**
* Return whether it is am.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isPm() {
return !isAm();
}
/**
* Return whether it is am.
* <p>The pattern is {@code yyyy-MM-dd HH:mm:ss}.</p>
*
* @param time The formatted time string.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isPm(final String time) {
return !isAm(time);
}
/**
* Return whether it is am.
*
* @param time The formatted time string.
* @param format The format.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isPm(final String time,
@NonNull final DateFormat format) {
return !isAm(time, format);
}
/**
* Return whether it is am.
*
* @param date The date.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isPm(final Date date) {
return !isAm(date);
}
/**
* Return whether it is am.
*
* @param millis The milliseconds.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isPm(final long millis) {
return !isAm(millis);
}
// endregion
// region *------------------------------- 属相|星座 ------------------------------------*
/**
* Return the Chinese zodiac.
* <p>The pattern is {@code yyyy-MM-dd HH:mm:ss}.</p>
*
* @param time The formatted time string.
* @return the Chinese zodiac
*/
public static String getChineseZodiac(final String time) {
return getChineseZodiac(toDate(time, getDefaultFormat()));
}
/**
* Return the Chinese zodiac.
*
* @param time The formatted time string.
* @param format The format.
* @return the Chinese zodiac
*/
public static String getChineseZodiac(final String time, @NonNull final DateFormat format) {
return getChineseZodiac(toDate(time, format));
}
/**
* Return the Chinese zodiac.
*
* @param date The date.
* @return the Chinese zodiac
*/
public static String getChineseZodiac(final Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return CHINESE_ZODIAC[cal.get(Calendar.YEAR) % 12];
}
/**
* Return the Chinese zodiac.
*
* @param millis The milliseconds.
* @return the Chinese zodiac
*/
public static String getChineseZodiac(final long millis) {
return getChineseZodiac(toDate(millis));
}
/**
* Return the Chinese zodiac.
*
* @param year The year.
* @return the Chinese zodiac
*/
public static String getChineseZodiac(final int year) {
return CHINESE_ZODIAC[year % 12];
}
/**
* Return the zodiac.
* <p>The pattern is {@code yyyy-MM-dd HH:mm:ss}.</p>
*
* @param time The formatted time string.
* @return the zodiac
*/
public static String getZodiac(final String time) {
return getZodiac(toDate(time, getDefaultFormat()));
}
/**
* Return the zodiac.
*
* @param time The formatted time string.
* @param format The format.
* @return the zodiac
*/
public static String getZodiac(final String time, @NonNull final DateFormat format) {
return getZodiac(toDate(time, format));
}
/**
* Return the zodiac.
*
* @param date The date.
* @return the zodiac
*/
public static String getZodiac(final Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
return getZodiac(month, day);
}
/**
* Return the zodiac.
*
* @param millis The milliseconds.
* @return the zodiac
*/
public static String getZodiac(final long millis) {
return getZodiac(toDate(millis));
}
/**
* Return the zodiac.
*
* @param month The month.
* @param day The day.
* @return the zodiac
*/
public static String getZodiac(final int month, final int day) {
return ZODIAC[day >= ZODIAC_FLAGS[month - 1]
? month - 1
: (month + 10) % 12];
}
// endregion
// region *------------------------------- Calendar ------------------------------------*
/**
* Returns the value of the given calendar field.
*
* @param field The given calendar field.
* <ul>
* <li>{@link Calendar#ERA}</li>
* <li>{@link Calendar#YEAR}</li>
* <li>{@link Calendar#MONTH}</li>
* <li>...</li>
* <li>{@link Calendar#DST_OFFSET}</li>
* </ul>
* @return the value of the given calendar field
*/
public static int getValueByCalendarField(final int field) {
Calendar cal = Calendar.getInstance();
return cal.get(field);
}
/**
* Returns the value of the given calendar field.
* <p>The pattern is {@code yyyy-MM-dd HH:mm:ss}.</p>
*
* @param time The formatted time string.
* @param field The given calendar field.
* <ul>
* <li>{@link Calendar#ERA}</li>
* <li>{@link Calendar#YEAR}</li>
* <li>{@link Calendar#MONTH}</li>
* <li>...</li>
* <li>{@link Calendar#DST_OFFSET}</li>
* </ul>
* @return the value of the given calendar field
*/
public static int getValueByCalendarField(final String time, final int field) {
return getValueByCalendarField(toDate(time, getDefaultFormat()), field);
}
/**
* Returns the value of the given calendar field.
*
* @param time The formatted time string.
* @param format The format.
* @param field The given calendar field.
* <ul>
* <li>{@link Calendar#ERA}</li>
* <li>{@link Calendar#YEAR}</li>
* <li>{@link Calendar#MONTH}</li>
* <li>...</li>
* <li>{@link Calendar#DST_OFFSET}</li>
* </ul>
* @return the value of the given calendar field
*/
public static int getValueByCalendarField(final String time,
@NonNull final DateFormat format,
final int field) {
return getValueByCalendarField(toDate(time, format), field);
}
/**
* Returns the value of the given calendar field.
*
* @param date The date.
* @param field The given calendar field.
* <ul>
* <li>{@link Calendar#ERA}</li>
* <li>{@link Calendar#YEAR}</li>
* <li>{@link Calendar#MONTH}</li>
* <li>...</li>
* <li>{@link Calendar#DST_OFFSET}</li>
* </ul>
* @return the value of the given calendar field
*/
public static int getValueByCalendarField(final Date date, final int field) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(field);
}
/**
* Returns the value of the given calendar field.
*
* @param millis The milliseconds.
* @param field The given calendar field.
* <ul>
* <li>{@link Calendar#ERA}</li>
* <li>{@link Calendar#YEAR}</li>
* <li>{@link Calendar#MONTH}</li>
* <li>...</li>
* <li>{@link Calendar#DST_OFFSET}</li>
* </ul>
* @return the value of the given calendar field
*/
public static int getValueByCalendarField(final long millis, final int field) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
return cal.get(field);
}
// endregion
// region *---------------------------------- 内部 --------------------------------------*
private static final ThreadLocal<SimpleDateFormat> SDF_THREAD_LOCAL = new ThreadLocal<>();
private static SimpleDateFormat getDefaultFormat() {
SimpleDateFormat simpleDateFormat = SDF_THREAD_LOCAL.get();
if (simpleDateFormat == null) {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
SDF_THREAD_LOCAL.set(simpleDateFormat);
}
return simpleDateFormat;
}
private static long getWeeOfToday() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
/**
* TODO 下面只能算是一种计算方式,即指定时间跨度中天的个数,但是:
* 1. 不到一天怎么算?
* 2. 起止日期怎么算?
*/
private static long toTimeSpan(final long millis, @TimeConstants.Unit final int unit) {
return millis / unit;
}
private TimeUtils() {
throw new UnsupportedOperationException("u can't initialize me!");
}
// endregion
}
| 31.546407 | 98 | 0.560528 |
613e8204cbe100d50dc44c1c3d92b6e7507e3908 | 3,332 | /*
* Copyright 2016-2018 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onehippo.cms7.channelmanager.channeleditor;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.wicket.Application;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.hippoecm.frontend.CmsHeaderItem;
import org.hippoecm.frontend.extjs.ExtUtilsHeaderItem;
import org.hippoecm.frontend.extjs.ExtWidgetRegistryHeaderItem;
import org.wicketstuff.js.ext.util.ExtResourcesHeaderItem;
public class ChannelEditorApiHeaderItem extends HeaderItem {
// All individual javascript files used in the template composer API. The array order determines the include order,
// which matters. All files listed below should also be present in the aggregation section in frontend-api/pom.xml.
private static final String[] FILES = {
"IFrameWindow.js",
"ComponentPropertiesEditor.js",
"PlainComponentPropertiesEditor.js",
"ComponentVariantAdder.js",
"PlainComponentVariantAdder.js"
};
private static final JavaScriptResourceReference[] RESOURCES;
private static final JavaScriptResourceReference CONCATENATED_RESOURCES =
new JavaScriptResourceReference(ChannelEditorApiHeaderItem.class, "channel-editor-api-bundle.js");
static {
RESOURCES = new JavaScriptResourceReference[FILES.length];
for (int i = 0; i < FILES.length; i++) {
RESOURCES[i] = new JavaScriptResourceReference(ChannelEditorApiHeaderItem.class, FILES[i]);
}
}
private static final ChannelEditorApiHeaderItem INSTANCE = new ChannelEditorApiHeaderItem();
public static ChannelEditorApiHeaderItem get() {
return INSTANCE;
}
private ChannelEditorApiHeaderItem() {}
@Override
public List<HeaderItem> getDependencies() {
return Arrays.asList(ExtResourcesHeaderItem.get(), CmsHeaderItem.get(), ExtWidgetRegistryHeaderItem.get(), ExtUtilsHeaderItem.get());
}
@Override
public Iterable<?> getRenderTokens() {
return Collections.singletonList("channel-editor-api-header-item");
}
@Override
public void render(final Response response) {
if (Application.get().getDebugSettings().isAjaxDebugModeEnabled()) {
for (JavaScriptResourceReference resourceReference : RESOURCES) {
JavaScriptHeaderItem.forReference(resourceReference).render(response);
}
} else {
JavaScriptHeaderItem.forReference(CONCATENATED_RESOURCES).render(response);
}
}
}
| 39.2 | 141 | 0.733794 |
90458f27c15c51e385a48bffbfa4df5613c6a2d1 | 684 | package me.ialistannen.navigator.util;
import me.ialistannen.navigator.Navigator;
import org.bukkit.ChatColor;
/**
* A small utility class
*/
public class Util {
/**
* @param key The key to translate
* @param formattingObjects The formattingObjects
*
* @return The translated String
*/
public static String tr(String key, Object... formattingObjects) {
return Navigator.getInstance().getLanguage().tr(key, formattingObjects);
}
/**
* Colors the string
*
* @param string The string to color
*
* @return The colored String
*/
public static String color(String string) {
return ChatColor.translateAlternateColorCodes('&', string);
}
}
| 21.375 | 74 | 0.69883 |
17a1a551ce830d8b9a3ffe7b587e06a6b924f61c | 422 | package com.sterilecode.mitosis.view;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class ViewManagerTest {
@Test
public void loadAndGetView() throws Exception {
ViewManager vm = ViewManager.getInstance();
vm.initialize();
assertNotNull(vm.getView("sample"));
}
@Test
public void getInstance() throws Exception {
assertNotNull(ViewManager.getInstance());
}
} | 20.095238 | 49 | 0.729858 |
d374723912dc812f3d2e71f67087033851a7f839 | 13,477 | package learning.topology;
import peersim.core.CommonState;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
/**
* @author sshpark
* @date 17/2/2020
*/
public class TopoUtil {
/**
* Returns the adjacency matrix of the network,
* If value is Integer.MAX_VALUE, then there is no edge between two nodes
* else it represents the delay between two nodes.
*
* Notice that the index of node starts with 0.
*
* @return Adjacency matrix
*/
public static int[][] getGraph(int n, String filePath) {
int[][] graph = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
graph[i][j] = i == j ? 0 : Integer.MAX_VALUE;
try {
FileReader fr = new FileReader(filePath);
BufferedReader bf = new BufferedReader(fr);
String str;
while ((str = bf.readLine()) != null) {
String[] temp = str.split(" ");
int from = Integer.parseInt(temp[0])-1;
int to = Integer.parseInt(temp[1])-1;
graph[from][to] = Integer.parseInt(temp[2]);
graph[to][from] = Integer.parseInt(temp[2]);
}
bf.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
return graph;
}
/**
* Returns the minimum delay from start(node index) to end(node index),
* if minDelay = Integet.MAX_VALUE, it means that message can not from start to end.
*
* Implemented by Dijkstra with heap
*
* @param graph
* @param start message from
* @return the minimum delay
*/
private static int[] getSingelNodeMinDelay(int[][] graph, int start) {
class Edge implements Comparable<Edge>{
int to , cost;
Edge(int to_,int cost_){
to = to_;
cost = cost_;
}
@Override
public int compareTo(Edge o) {
return this.cost - o.cost;
}
}
int n = graph.length;
boolean[] vis = new boolean[n];
int[] dis = new int[n];
// init dis
for (int i = 0; i < n; i++) dis[i] = Integer.MAX_VALUE;
Queue<Edge> que = new PriorityQueue<>();
que.add(new Edge(start, 0));
dis[start] = 0;
while (!que.isEmpty()) {
Edge top = que.poll();
int u = top.to;
if (dis[u] < top.cost) continue;
if (vis[u]) continue;
vis[u] = true;
for (int to = 0; to < n; to++) {
if (u != to && graph[u][to] != Integer.MAX_VALUE) {
int delay = graph[u][to];
if (!vis[to] && dis[to] > dis[u] + delay) {
dis[to] = dis[u]+delay;
que.add(new Edge(to, dis[to]));
}
}
}
}
return dis;
}
/**
* Returns the shortest path from node to node.
* @param graph
* @return
*/
public static int[][] generateMinDelayMatrix(int[][] graph) {
int[][] minDelayMatrix = new int[graph.length][graph.length];
for (int i = 0; i < graph.length; i++)
for (int j = 0; j < graph.length; j++)
minDelayMatrix[i][j] = i == j ? 1 : Integer.MAX_VALUE;
for (int nodeIndex = 0; nodeIndex < graph.length; nodeIndex++) {
int[] singleNodeDelayArray = getSingelNodeMinDelay(graph, nodeIndex);
for (int i = 0; i < graph.length; i++) {
minDelayMatrix[nodeIndex][i] = singleNodeDelayArray[i];
}
}
return minDelayMatrix;
}
/**
*
* @param graph
* @param nodeIdList
* @param aggregationRatio percentage of the model to begin aggregating
* @return
*/
public static int findParameterServerId(int[][] graph, ArrayList<Integer> nodeIdList, double aggregationRatio) {
int[][] minDelayMatrix = generateMinDelayMatrix(graph);
ArrayList<Integer> theDelaysAtAggregationRatio = new ArrayList<>();
int k = (int)Math.round(nodeIdList.size() * (1 - aggregationRatio)) + 1;
for (int i = 0; i < nodeIdList.size(); i++) {
PriorityQueue<Integer> largeK = new PriorityQueue<>(k + 1);
for (int j = 0; j < nodeIdList.size(); j++) {
if (i == j) {
continue;
}
largeK.add(minDelayMatrix[nodeIdList.get(i)][nodeIdList.get(j)]);
if (largeK.size() > k) {
largeK.poll();
}
}
theDelaysAtAggregationRatio.add(largeK.poll());
}
// System.out.println(theDelaysAtAggregationRatio);
int selectedNodeId = nodeIdList.get(0);
int minDelay = theDelaysAtAggregationRatio.get(0);
for (int nodeIndex = 1; nodeIndex < theDelaysAtAggregationRatio.size(); nodeIndex++) {
if (theDelaysAtAggregationRatio.get(nodeIndex) < minDelay) {
minDelay = theDelaysAtAggregationRatio.get(nodeIndex);
selectedNodeId = nodeIdList.get(nodeIndex);
}
}
return selectedNodeId;
}
public static ArrayList<ArrayList<Integer>>
getGraphPartitionResult(int[][] graph, ArrayList<Integer> nodeIdList, int k) {
int[][] minDelayMatrix = generateMinDelayMatrix(graph);
ArrayList<ArrayList<Integer>> clusterList = new ArrayList<>(3);
for (int i = 0; i < k; i++) {
ArrayList<Integer> cluster = new ArrayList<>(nodeIdList.size());
clusterList.add(cluster);
}
int[] clusterCenterNodeId = new int[k];
HashSet<Integer> hashSet = new HashSet<>();
int[] finalClusterCenterId = new int[k];
for (int i = 0; i < k; i++) {
int randomNodeIndex = CommonState.r.nextInt(nodeIdList.size());
while (hashSet.contains(randomNodeIndex)) {
randomNodeIndex = CommonState.r.nextInt(nodeIdList.size());
}
hashSet.add(randomNodeIndex);
clusterCenterNodeId[i] = nodeIdList.get(randomNodeIndex);
}
boolean terminateFlag = false;
while (!terminateFlag) {
terminateFlag = true;
for (int i = 0; i < k; i++) {
clusterList.get(i).clear();
}
for (int i = 0; i < nodeIdList.size(); i++) {
int nearestClusterCenter = 0;
int minDelay = minDelayMatrix[nodeIdList.get(i)][clusterCenterNodeId[0]];
for (int j = 1; j < k; j++) {
if (minDelayMatrix[nodeIdList.get(i)][clusterCenterNodeId[j]] < minDelay) {
nearestClusterCenter = j;
minDelay = minDelayMatrix[nodeIdList.get(i)][clusterCenterNodeId[j]];
}
}
clusterList.get(nearestClusterCenter).add(nodeIdList.get(i));
}
for (int i = 0; i < k; i++) {
int minTotalDelay = Integer.MAX_VALUE;
int newCenterNodeId = clusterCenterNodeId[i];
for (int j = 0; j < clusterList.get(i).size(); j++) {
int totalDelay = 0;
for (Integer nodeId : clusterList.get(i)) {
if (nodeId.equals(clusterList.get(i).get(j))) {
continue;
}
totalDelay += minDelayMatrix[nodeId][clusterList.get(i).get(j)];
}
if (totalDelay < minTotalDelay) {
minTotalDelay = totalDelay;
newCenterNodeId = clusterList.get(i).get(j);
}
}
if (newCenterNodeId != clusterCenterNodeId[i]) {
terminateFlag = false;
clusterCenterNodeId[i] = newCenterNodeId;
}
finalClusterCenterId = clusterCenterNodeId;
}
}
for (int i = 0; i < finalClusterCenterId.length; i++) {
// System.out.println(finalClusterCenterId[i]);
clusterList.get(i).add(finalClusterCenterId[i]);
// System.out.println(finalClusterList.get(i));
}
return clusterList;
}
public static ArrayList<ArrayList<Integer>> getGraphPartitionResult(int[][] graph, ArrayList<Integer> nodeIdList, double aggregationRatio, int k) {
int minClusterDelay = Integer.MAX_VALUE;
int tmpMinClusterDelay = Integer.MAX_VALUE;
int[][] minDelayMatrix = generateMinDelayMatrix(graph);
ArrayList<ArrayList<Integer>> finalClusterList = new ArrayList<>();
int[] finalClusterCenterId = new int[k];
for (int it = 0; it < 10000; it++) {
ArrayList<ArrayList<Integer>> clusterList = new ArrayList<>(k);
for (int i = 0; i < k; i++) {
ArrayList<Integer> cluster = new ArrayList<>(nodeIdList.size());
clusterList.add(cluster);
}
int[] clusterCenterNodeId = new int[k];
HashSet<Integer> hashSet = new HashSet<>();
for (int i = 0; i < k; i++) {
int randomNodeIndex = CommonState.r.nextInt(nodeIdList.size());
while (hashSet.contains(randomNodeIndex)) {
randomNodeIndex = CommonState.r.nextInt(nodeIdList.size());
}
hashSet.add(randomNodeIndex);
clusterCenterNodeId[i] = nodeIdList.get(randomNodeIndex);
}
boolean terminateFlag = false;
while (!terminateFlag) {
terminateFlag = true;
for (int i = 0; i < k; i++) {
clusterList.get(i).clear();
}
for (int i = 0; i < nodeIdList.size(); i++) {
int nearestClusterCenter = 0;
int minDelay = minDelayMatrix[nodeIdList.get(i)][clusterCenterNodeId[0]];
for (int j = 1; j < k; j++) {
if (minDelayMatrix[nodeIdList.get(i)][clusterCenterNodeId[j]] < minDelay) {
nearestClusterCenter = j;
minDelay = minDelayMatrix[nodeIdList.get(i)][clusterCenterNodeId[j]];
}
}
clusterList.get(nearestClusterCenter).add(nodeIdList.get(i));
}
int maxClusterDelay = 0;
for (int i = 0; i < k; i++) {
int minTotalDelay = Integer.MAX_VALUE;
int newCenterNodeId = clusterCenterNodeId[i];
int maxDelay = 0;
int n = (int) (Math.round(nodeIdList.size() * (1 - aggregationRatio)) + 1);
PriorityQueue<Integer> largeK = new PriorityQueue<>(n + 1);
for (int j = 0; j < clusterList.get(i).size(); j++) {
int totalDelay = 0;
for (Integer nodeId : clusterList.get(i)) {
if (nodeId == clusterList.get(i).get(j)) {
continue;
}
totalDelay += minDelayMatrix[nodeId][clusterList.get(i).get(j)];
if (minDelayMatrix[nodeId][clusterList.get(i).get(j)] > maxDelay) {
maxDelay = minDelayMatrix[nodeId][clusterList.get(i).get(j)];
}
largeK.add(minDelayMatrix[nodeId][clusterList.get(i).get(j)]);
if (largeK.size() > n) {
largeK.poll();
}
}
if (totalDelay < minTotalDelay) {
minTotalDelay = totalDelay;
newCenterNodeId = clusterList.get(i).get(j);
}
}
if (newCenterNodeId != clusterCenterNodeId[i]) {
terminateFlag = false;
clusterCenterNodeId[i] = newCenterNodeId;
}
Object tmp = largeK.poll();
int tmpMaxDelay = 0;
if (tmp != null) {
tmpMaxDelay = (Integer) tmp;
}
if (tmpMaxDelay > maxClusterDelay) {
maxClusterDelay = tmpMaxDelay;
}
}
// System.out.println(maxClusterDelay);
tmpMinClusterDelay = maxClusterDelay;
}
if (tmpMinClusterDelay < minClusterDelay) {
minClusterDelay = tmpMinClusterDelay;
// System.out.println(minClusterDelay);
finalClusterList = clusterList;
finalClusterCenterId = clusterCenterNodeId;
}
}
for (int i = 0; i < finalClusterCenterId.length; i++) {
// System.out.println(finalClusterCenterId[i]);
finalClusterList.get(i).add(finalClusterCenterId[i]);
// System.out.println(finalClusterList.get(i));
}
return finalClusterList;
}
}
| 40.963526 | 151 | 0.499814 |
27e5ef9bb61259000ce71e0e135a92c9e0dad9cf | 3,761 | package ca.on.oicr.gsi.shesmu.redict;
import ca.on.oicr.gsi.shesmu.plugin.Definer;
import ca.on.oicr.gsi.shesmu.plugin.Definer.RefillDefiner;
import ca.on.oicr.gsi.shesmu.plugin.Definer.RefillInfo;
import ca.on.oicr.gsi.shesmu.plugin.json.JsonPluginFile;
import ca.on.oicr.gsi.shesmu.plugin.refill.CustomRefillerParameter;
import ca.on.oicr.gsi.shesmu.plugin.refill.Refiller;
import ca.on.oicr.gsi.shesmu.plugin.types.Imyhat;
import ca.on.oicr.gsi.status.SectionRenderer;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RefillableDictionary extends JsonPluginFile<Configuration> {
public static final class DictionaryRefiller<I> extends Refiller<I> {
private final AtomicReference<Map<Object, Object>> dictionary;
private Function<I, Object> key;
private Function<I, Object> value;
public DictionaryRefiller(AtomicReference<Map<Object, Object>> dictionary) {
super();
this.dictionary = dictionary;
}
@Override
public void consume(Stream<I> items) {
dictionary.set(items.collect(Collectors.toMap(key, value, (a, b) -> a)));
}
}
private static final ObjectMapper MAPPER = new ObjectMapper();
private final Definer<RefillableDictionary> definer;
public RefillableDictionary(
Definer<RefillableDictionary> definer, Path fileName, String instanceName) {
super(fileName, instanceName, MAPPER, Configuration.class);
this.definer = definer;
}
@Override
public void configuration(SectionRenderer renderer) {
// Do nothing
}
@Override
protected Optional<Integer> update(Configuration configuration) {
if (configuration.getKey().isBad() || configuration.getValue().isBad()) {
return Optional.empty();
}
final var dictionary = new AtomicReference<>(Map.of());
definer.defineConstantBySupplier(
"get",
"Dictionary of values collected from refiller.",
Imyhat.dictionary(configuration.getKey(), configuration.getValue()),
dictionary::get);
definer.defineRefiller(
"put",
"A way to fill the dictionary available as a constant of the same name",
new RefillDefiner() {
@Override
public <I> RefillInfo<I, DictionaryRefiller<I>> info(Class<I> rowType) {
return new RefillInfo<>() {
@Override
public DictionaryRefiller<I> create() {
return new DictionaryRefiller<>(dictionary);
}
@Override
public Stream<CustomRefillerParameter<DictionaryRefiller<I>, I>> parameters() {
return Stream.of(
new CustomRefillerParameter<>("key", configuration.getKey()) {
@Override
public void store(
DictionaryRefiller<I> refiller, Function<I, Object> function) {
refiller.key = function;
}
},
new CustomRefillerParameter<>("value", configuration.getValue()) {
@Override
public void store(
DictionaryRefiller<I> refiller, Function<I, Object> function) {
refiller.value = function;
}
});
}
@Override
public Class<? extends Refiller> type() {
return DictionaryRefiller.class;
}
};
}
});
return Optional.empty();
}
}
| 35.481132 | 93 | 0.632013 |
6b4988f15bedf69aac065e6d11961c91b4de9d81 | 338 | package org.basex.query.util.pkg;
import org.basex.util.list.*;
/**
* Jar descriptor.
*
* @author BaseX Team 2005-15, BSD License
* @author Rositsa Shadura
*/
final class JarDesc {
/** List of jar files. */
final TokenList jars = new TokenList();
/** List of public classes. */
final TokenList classes = new TokenList();
}
| 19.882353 | 44 | 0.668639 |
fe02690e06858d28515544fdacd656cc14a54414 | 977 | package com.swengsol;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
String title = "Hello World - Tomcat Developer's Guide";
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor = \"white\">");
out.println("<h1>Hello World from the Developer's Guide!</h1>");
out.println("</body>");
out.println("</html>");
}
}
| 39.08 | 79 | 0.683726 |
ebed6a498351e5d30aa3feb9c088d60886789e93 | 7,123 | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine.management.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.gemstone.gemfire.management.internal.FederationComponent;
import com.gemstone.gemfire.management.internal.beans.stats.LongStatsDeltaAggregator;
import com.gemstone.gemfire.management.internal.beans.stats.StatsAggregator;
/**
*
* Aggregator to aggregate Statement stats from different members. Aggregation
* Strategy: a) All Counter will be aggregated to show point in time delta
* value.( across members) b) All GaugeCounter will be aggregated to show
* absolute value across members
*
* @author rishim
*
*/
public class AggregateStatementMBeanBridge {
private static final String QN_NUM_TIMES_COMPILED = "QNNumTimesCompiled";
private static final String QN_NUM_EXECUTIONS = "QNNumExecutions";
private static final String QN_NUM_EXECUTION_IN_PROGRESS = "QNNumExecutionsInProgress";
private static final String QN_NUM_TIMES_GLOBAL_INDEX_LOOKUP = "QNNumTimesGlobalIndexLookup";
private static final String QN_NUM_ROWS_MODIFIED = "QNNumRowsModified";
private static final String QN_PARSE_TIME = "QNParseTime";
private static final String QN_BIND_TIME = "QNBindTime";
private static final String QN_OPTIMIZE_TIME = "QNOptimizeTime";
private static final String QN_ROUTING_INFO_TIME = "QNRoutingInfoTime";
private static final String QN_GENERATE_TIME = "QNGenerateTime";
private static final String QN_TOTAL_COMPILATION_TIME = "QNTotalCompilationTime";
private static final String QN_EXECUTE_TIME = "QNExecuteTime";
private static final String QN_PROJECTION_TIME = "QNProjectionTime";
private static final String QN_TOTAL_EXECUTION_TIME = "QNTotalExecutionTime";
private static final String QN_ROWS_MODIFICATION_TIME = "QNRowsModificationTime";
private static final String QN_NUM_ROWS_SEEN = "QNNumRowsSeen";
private static final String QN_MSG_SEND_TIME = "QNMsgSendTime";
private static final String QN_MSG_SER_TIME = "QNMsgSerTime";
private static final String QN_RESP_DESER_TIME = "QNRespDeSerTime";
private AggregateStatementClusterStatsMonitor monitor;
private LongStatsDeltaAggregator deltas;
public AggregateStatementMBeanBridge() {
this.monitor = new AggregateStatementClusterStatsMonitor();
List<String> keysList = new ArrayList<String>();
keysList.add(QN_NUM_TIMES_COMPILED);
keysList.add(QN_NUM_EXECUTIONS);
keysList.add(QN_NUM_EXECUTION_IN_PROGRESS);
keysList.add(QN_NUM_TIMES_GLOBAL_INDEX_LOOKUP);
keysList.add(QN_NUM_ROWS_MODIFIED);
keysList.add(QN_PARSE_TIME);
keysList.add(QN_BIND_TIME);
keysList.add(QN_OPTIMIZE_TIME);
keysList.add(QN_ROUTING_INFO_TIME);
keysList.add(QN_GENERATE_TIME);
keysList.add(QN_TOTAL_COMPILATION_TIME);
keysList.add(QN_EXECUTE_TIME);
keysList.add(QN_PROJECTION_TIME);
keysList.add(QN_TOTAL_EXECUTION_TIME);
keysList.add(QN_ROWS_MODIFICATION_TIME);
keysList.add(QN_NUM_ROWS_SEEN);
keysList.add(QN_MSG_SEND_TIME);
keysList.add(QN_MSG_SER_TIME);
deltas = new LongStatsDeltaAggregator(keysList);
}
private volatile int memberCount = 0;
public int getMemberCount(){
return memberCount;
}
public void aggregate(String member, FederationComponent newState, FederationComponent oldState) {
if (newState != null && oldState == null) {
// Proxy Addition , increase member count
++memberCount;
}
if (newState == null && oldState != null) {
// Proxy Removal , decrease member count
--memberCount;
}
monitor.aggregate(newState, oldState);
deltas.aggregate(newState, oldState);
insertIntoTable(member, newState, oldState);
}
private void insertIntoTable(String member, FederationComponent newState, FederationComponent oldState) {
return ; //TODO to insert int a GEMFIREXD table
}
public long getBindTime() {
return deltas.getDelta(QN_BIND_TIME);
}
public long getExecutionTime() {
return deltas.getDelta(QN_EXECUTE_TIME);
}
public long getGenerateTime() {
return deltas.getDelta(QN_GENERATE_TIME);
}
public long getNumExecution() {
return deltas.getDelta(QN_NUM_EXECUTIONS);
}
public long getNumExecutionsInProgress() {
return monitor.getNumExecutionsInProgresss();
}
public long getNumRowsModified() {
return deltas.getDelta(QN_NUM_ROWS_MODIFIED);
}
public long getNumTimesCompiled() {
return deltas.getDelta(QN_NUM_TIMES_COMPILED);
}
public long getNumTimesGlobalIndexLookup() {
return deltas.getDelta(QN_NUM_TIMES_GLOBAL_INDEX_LOOKUP);
}
public long getOptimizeTime() {
return deltas.getDelta(QN_OPTIMIZE_TIME);
}
public long getParseTime() {
return deltas.getDelta(QN_PARSE_TIME);
}
public long getProjectionTime() {
return deltas.getDelta(QN_PROJECTION_TIME);
}
public long getQNMsgSendTime() {
return deltas.getDelta(QN_MSG_SEND_TIME);
}
public long getQNMsgSerTime() {
return deltas.getDelta(QN_MSG_SER_TIME);
}
public long getQNNumRowsSeen() {
return deltas.getDelta(QN_NUM_ROWS_SEEN);
}
public long getRoutingInfoTime() {
return deltas.getDelta(QN_ROUTING_INFO_TIME);
}
public long getRowsModificationTime() {
return deltas.getDelta(QN_ROWS_MODIFICATION_TIME);
}
public long getTotalCompilationTime() {
return deltas.getDelta(QN_TOTAL_COMPILATION_TIME);
}
public long getTotalExecutionTime() {
return deltas.getDelta(QN_TOTAL_EXECUTION_TIME);
}
public long getQNRespDeSerTime() {
return deltas.getDelta(QN_RESP_DESER_TIME);
}
public AggregateStatementClusterStatsMonitor getMonitor() {
return monitor;
}
class AggregateStatementClusterStatsMonitor {
private StatsAggregator aggregator;
private Map<String, Class<?>> typeMap;
public void aggregate(FederationComponent newState, FederationComponent oldState) {
aggregator.aggregate(newState, oldState);
}
public AggregateStatementClusterStatsMonitor() {
this.typeMap = new HashMap<String, Class<?>>();
intTypeMap();
this.aggregator = new StatsAggregator(typeMap);
}
private void intTypeMap() {
typeMap.put(QN_NUM_EXECUTION_IN_PROGRESS, Long.TYPE);
}
public long getNumExecutionsInProgresss() {
return aggregator.getIntValue(QN_NUM_EXECUTION_IN_PROGRESS);
}
}
}
| 28.838057 | 107 | 0.754036 |
39ab72b7e21e15533dc605f23056db826f9e15c1 | 1,373 | /* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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 ghidra.app.util.bin;
import java.io.IOException;
/**
* An interface for a generic random-access byte provider, plus mutation methods.
*/
public interface MutableByteProvider extends ByteProvider {
/**
* Writes a byte at the specified index.
* @param index the index to write the byte
* @param value the value to write at the specified index
* @throws IOException if an I/O error occurs
*/
public void writeByte(long index, byte value) throws IOException;
/**
* Writes a byte array at the specified index.
* @param index the index to write the byte array
* @param values the values to write at the specified index
* @throws IOException if an I/O error occurs
*/
public void writeBytes(long index, byte[] values) throws IOException;
}
| 33.487805 | 81 | 0.72906 |
40e16d339420cae776785ffd2aa1a412d959d02e | 4,849 | package haxby.db.radar;
import haxby.image.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
public class RBorder {
RImage line;
boolean paintTitle = true;
Font titleFont, font;
int titleH, titleWidth, titleY;
int anotH, anotY, anotW;
String title, yTitle;
Insets insets;
static double[] dAnot = {2, 2.5, 2};
static AffineTransform rotate90 = new AffineTransform(0, -1, 1, 0, 0, 0);
public RBorder(RImage line) {
this.line = line;
font = new Font("SansSerif", Font.PLAIN, 10);
titleFont = new Font("SansSerif", Font.PLAIN, 12);
title = line.getCruiseID() +", Line "+ line.getID() +", Shot#";
yTitle = "2-way time, microsec";
setTitleSize();
setAnotSize();
}
public Insets getBorderInsets(Component c) {
return new Insets(titleH + anotH, anotW, 0, 0);
}
public Insets getBorderInsets(Component c, Insets insets) {
if(insets == null)return getBorderInsets(c);
insets.left = anotW;
insets.top = titleH + anotH;
insets.right = 0;
insets.bottom = 0;
return insets;
}
public boolean isBorderOpaque() { return true; }
public void paintBorder(Component c, Graphics g,
int x, int y, int w, int h) {
if( c != line ) return;
boolean flip = line.isFlip();
Graphics2D g2 = (Graphics2D)g;
AffineTransform at = g2.getTransform();
g.setColor(line.isRevVid() ? Color.black : Color.white);
g.fillRect(x,y,w,h);
g.setColor(line.isRevVid() ? Color.white : Color.black);
if(paintTitle) {
g.setFont(titleFont);
g.drawString(title, x + (w - titleWidth)/2, y+titleY);
}
FontMetrics fm = line.getFontMetrics(font);
x += anotW;
w -= anotW;
y += titleH+anotH;
h -= titleH+anotH;
g.translate(x, y);
g.drawRect(-1,-1,w+2,h+2);
g.drawRect(-1,-1,w+2,h+2);
double zoom = line.getZoomX();
double cdp1 = flip ? line.cdpInterval[1] : line.cdpInterval[0];
double cdp2 = flip ? line.cdpInterval[0] : line.cdpInterval[1];
double cdpScale = (cdp2 - cdp1) / (zoom*line.width);
double cdpMin;
double cdpMax;
if( flip ) {
cdpMax = cdp1 + (x-anotW)*cdpScale;
cdpMin = cdpMax + w*cdpScale ;
} else {
cdpMin = cdp1 + (x-anotW)*cdpScale;
cdpMax = cdpMin + w*cdpScale ;
}
int k = 0;
double cdpInt = 1;
int a1 = (int)Math.ceil(cdpMin/cdpInt);
int a2 = (int)Math.floor(cdpMax/cdpInt);
int wMax = 2*fm.stringWidth(Integer.toString(a2));
while( wMax*(a2-a1+1) > w ) {
cdpInt *= dAnot[k];
k = (k+1)%3;
a1 = (int)Math.ceil(cdpMin/cdpInt);
a2 = (int)Math.floor(cdpMax/cdpInt);
}
a1 = (int)Math.ceil(cdpMin/cdpInt);
a2 = (int)Math.floor(cdpMax/cdpInt);
int da = (int)Math.rint(cdpInt);
int ax, aw;
String anot;
g.setFont(font);
for( k=a1 ; k<=a2 ; k++ ) {
if(flip) {
ax = (int)Math.rint( (cdpInt*(double)k - cdpMax)/cdpScale );
} else {
ax = (int)Math.rint( (cdpInt*(double)k - cdpMin)/cdpScale );
}
g.fillRect(ax-1, -5, 2, 5);
anot = Integer.toString((int)(k*cdpInt));
aw = fm.stringWidth(anot);
g.drawString(anot, ax-aw/2, -6);
}
g.translate(0, h);
g2.transform(rotate90);
g.setFont(titleFont);
g.drawString(yTitle, (h-fm.stringWidth(yTitle))/2, -anotH);
g.setFont(font);
zoom = line.getZoomY();
double t1 = line.tRange[0]/10;
double t2 = line.tRange[1]/10;
double tScale = (t2 - t1) / (zoom*line.height);
double tMin = t1 + (y-titleH-anotH)*tScale;
double tMax = tMin + h*tScale ;
k = 0;
double tInt = 1;
a1 = (int)Math.ceil(tMin/tInt);
a2 = (int)Math.floor(tMax/tInt);
wMax = 2*fm.stringWidth(Integer.toString(a2));
while( wMax*(a2-a1+1) > h ) {
tInt *= dAnot[k];
k = (k+1)%3;
a1 = (int)Math.ceil(tMin/tInt);
a2 = (int)Math.floor(tMax/tInt);
}
a1 = (int)Math.ceil(tMin/tInt);
a2 = (int)Math.floor(tMax/tInt);
da = (int)Math.rint(tInt);
for( k=a1 ; k<=a2 ; k++ ) {
ax = h-(int)Math.rint( (tInt*(double)k - tMin)/tScale );
g.fillRect(ax-1, -5, 2, 5);
da = (int)(k*tInt);
anot = Integer.toString(da/100);
int tmp = da%100;
if( tmp != 0 ) {
if( tmp < 10 ) {
anot += ".0"+tmp;
} else if( tmp%10 == 0) {
anot += "."+(tmp/10);
} else {
anot += "."+tmp;
}
}
aw = fm.stringWidth(anot);
g.drawString(anot, ax-aw/2, -6);
}
g2.setTransform(at);
}
public void setPaintTitle(boolean tf) {
paintTitle = tf;
}
public void setTitle() {
title = line.getCruiseID() +" Line "+ line.getID() +", Shot#";
setTitleSize();
}
void setTitleSize() {
if( !paintTitle ) {
titleH = 0;
return;
}
FontMetrics fm = line.getFontMetrics(titleFont);
titleWidth = fm.stringWidth(title);
titleY = fm.getLeading() + fm.getHeight();
titleH = titleY + fm.getDescent();
}
void setAnotSize() {
FontMetrics fm = line.getFontMetrics(font);
anotH = fm.getLeading() + fm.getHeight() + 5;
anotY = fm.getLeading() + fm.getHeight();
anotW = fm.getLeading() + fm.getHeight() + anotH;
}
}
| 28.523529 | 74 | 0.61889 |
f20362f2ac0347ea7e0e321f1403aa8533956a1d | 1,175 | package com.stupidtree.hita.views;
import android.content.Context;
import android.content.Intent;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.preference.Preference;
import static com.stupidtree.hita.activities.ActivityTimeTable.TIMETABLE_REFRESH;
public class TimeTablePreferenceChangeListener implements Preference.OnPreferenceChangeListener{
Context context;
ChangeAction change;
public TimeTablePreferenceChangeListener(Context context, ChangeAction change) {
this.context = context;
this.change = change;
}
public TimeTablePreferenceChangeListener(Context context) {
this.context = context;
}
public interface ChangeAction{
boolean OnChanged(Preference preference,Object newValue);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
callTimeTableToRefresh();
if(change!=null) return change.OnChanged(preference,newValue);
return true;
}
private void callTimeTableToRefresh(){
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(TIMETABLE_REFRESH));
}
}
| 30.921053 | 96 | 0.760851 |
c3d176ea5ec007cc51210a99af1df41131243bb7 | 7,976 |
/*
* The MIT License
*
* 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.
*/
/**
* @author Felix Bärring <[email protected]>
*/
package view;
import java.awt.Graphics2D;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.awt.image.BufferedImage;
import controller.SoundController;
/**
* @author Felix Bärring <[email protected]>
*
*/
public class TextArea extends RelativeLocation{
protected final int WIDTH;
protected final int HEIGHT;
protected final int FONT_SIZE = 20;
protected final int MAX_CHARS;
protected final int MAX_ROWS;
protected boolean needScroll;
List<char[]> lines;
BufferedImage image;
ArrowButton up;
ArrowButton down;
protected int topLine = 0;
public TextArea(List<String> l, int x, int y, int offX, int offY, int w, int h){
this.xLocation = x;
this.yLocation = y;
this.lines = new LinkedList<>();
xOffSet = offX;
yOffSet = offY;
WIDTH = w;
HEIGHT = h;
MAX_CHARS = (int)((WIDTH-20)/FONT_SIZE*1.7 - 1);
MAX_ROWS = (int)((HEIGHT-20)/25);
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
for(String s : l){
addString(s);
}
up = new ArrowButton(WIDTH-17, 7, 6, 5, 2, 0);
down = new ArrowButton(WIDTH-17, HEIGHT-15, 6, 5, 2, 1);
}
protected void addString(String s){
char[] chars = s.toCharArray();
while(chars.length > MAX_CHARS){
int cut = MAX_CHARS;
while(chars[cut] != ' ' ){
cut--;
if(cut < 0) {
lines.add((Arrays.copyOfRange(chars, 0, MAX_CHARS-1)));
if(needScroll){
topLine++;
}
addString(new String(Arrays.copyOfRange(chars, MAX_CHARS, chars.length-1)));
return;
}
}
cut++;
lines.add(fillCutsWithNull(cut, chars));
chars = Arrays.copyOfRange(chars, cut, chars.length);
}
lines.add(fillCutsWithNull(chars.length, chars));
needScroll = lines.size() > MAX_ROWS;
if(needScroll){
topLine = lines.size() - MAX_ROWS;
}
}
private char[] fillCutsWithNull(int cut, char[] chars){
char[] line = new char[MAX_CHARS];
for(int i = 0; i < MAX_CHARS; i++){
if(i < cut){
line[i] = chars[i];
} else {
line[i] = '\0';
}
}
return line;
}
public void clear(){
lines = new LinkedList<char[]>();
topLine = 0;
}
protected String lineToString(int i){
StringBuilder sb = new StringBuilder();
for(char c : lines.get(i)){
if( c == '\0') break;
sb.append(c);
}
return sb.toString();
}
@Override
public void draw(Graphics2D g) {
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setFont(PublicConstants.regularFont20);
g2.setColor(PublicConstants.BGColor);
g2.fillRect(0, 0, WIDTH, HEIGHT);
g2.setColor(PublicConstants.normalColor);
g2.fillRect(5, 5, WIDTH-10, HEIGHT-10);
g2.setColor(PublicConstants.textColor);
for(int i = topLine; i < lines.size() && i < MAX_ROWS+topLine; i++){
// Need to be optimized
g2.drawString(lineToString(i), 10, 25*(i+1-topLine)+5);
}
if(needScroll){
up.drawArrow(g2);
down.drawArrow(g2);
}
g.drawImage(image, (int)xLocation, (int)yLocation, WIDTH, HEIGHT, null);
g2.dispose();
}
@Override
public void tick() {}
@Override
public void mouseClicked(int button, int x, int y) {
if(needScroll){
up.mouseClicked(button, (int)(x-xLocation), (int)(y-yLocation));
down.mouseClicked(button, (int)(x-xLocation), (int)(y-yLocation));
}
}
@Override
public void mouseMoved(int x, int y) {
if(needScroll){
up.mouseMoved((int)(x-xLocation), (int)(y-yLocation));
down.mouseMoved((int)(x-xLocation), (int)(y-yLocation));
}
}
@Override
public void keyPressed(int key) {}
class ArrowButton{
int xLocation;
int yLocation;
int width;
int height;
int scale;
BufferedImage img;
BufferedImage hover;
boolean beingHovered = false;
int upOrDown;
ArrowButton(int x, int y, int w, int h, int s, int uod){
xLocation = x;
yLocation = y;
width = w;
height = h;
scale = s;
upOrDown = uod;
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) img.getGraphics();
g2.setColor(PublicConstants.normalColor);
g2.fillRect(0, 0, width, height);
int b = PublicConstants.textColor.getRGB();
if(upOrDown == 0){
img.setRGB(2, 0, b); img.setRGB(3, 0, b);
img.setRGB(1, 1, b); img.setRGB(2, 1, b); img.setRGB(3, 1, b); img.setRGB(4, 1, b);
img.setRGB(0, 2, b); img.setRGB(1, 2, b); img.setRGB(2, 2, b); img.setRGB(3, 2, b); img.setRGB(4, 2, b); img.setRGB(5, 2, b);
img.setRGB(2, 3, b); img.setRGB(3, 3, b);
img.setRGB(2, 4, b); img.setRGB(3, 4, b);
} else {
img.setRGB(2, 4, b); img.setRGB(3, 4, b);
img.setRGB(1, 3, b); img.setRGB(2, 3, b); img.setRGB(3, 3, b); img.setRGB(4, 3, b);
img.setRGB(0, 2, b); img.setRGB(1, 2, b); img.setRGB(2, 2, b); img.setRGB(3, 2, b); img.setRGB(4, 2, b); img.setRGB(5, 2, b);
img.setRGB(2, 1, b); img.setRGB(3, 1, b);
img.setRGB(2, 0, b); img.setRGB(3, 0, b);
}
hover = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g3 = (Graphics2D) hover.getGraphics();
g3.setColor(PublicConstants.normalColor);
g3.fillRect(0, 0, width, height);
b = PublicConstants.highlightColor.getRGB();
if(upOrDown == 0){
hover.setRGB(2, 0, b); hover.setRGB(3, 0, b);
hover.setRGB(1, 1, b); hover.setRGB(2, 1, b); hover.setRGB(3, 1, b); hover.setRGB(4, 1, b);
hover.setRGB(0, 2, b); hover.setRGB(1, 2, b); hover.setRGB(2, 2, b); hover.setRGB(3, 2, b); hover.setRGB(4, 2, b); hover.setRGB(5, 2, b);
hover.setRGB(2, 3, b); hover.setRGB(3, 3, b);
hover.setRGB(2, 4, b); hover.setRGB(3, 4, b);
} else {
hover.setRGB(2, 4, b); hover.setRGB(3, 4, b);
hover.setRGB(1, 3, b); hover.setRGB(2, 3, b); hover.setRGB(3, 3, b); hover.setRGB(4, 3, b);
hover.setRGB(0, 2, b); hover.setRGB(1, 2, b); hover.setRGB(2, 2, b); hover.setRGB(3, 2, b); hover.setRGB(4, 2, b); hover.setRGB(5, 2, b);
hover.setRGB(2, 1, b); hover.setRGB(3, 1, b);
hover.setRGB(2, 0, b); hover.setRGB(3, 0, b);
}
}
public void drawArrow(Graphics2D g){
if(beingHovered){
g.drawImage(hover, xLocation, yLocation, width*scale, height*scale, null);
}else{
g.drawImage(img, xLocation, yLocation, width*scale, height*scale, null);
}
}
public void mouseMoved(int x, int y){
if( x > xLocation && x < xLocation+(width*scale) &&
y > yLocation && y < yLocation+(height*scale)){
beingHovered = true;
} else {
beingHovered = false;
}
}
public void mouseClicked(int button, int x, int y){
if( x > xLocation && x < xLocation+(width*scale) &&
y > yLocation && y < yLocation+(height*scale)){
if(upOrDown == 0 && topLine > 0){
topLine--;
SoundController.getInstance().playButtonSound();
} else if(upOrDown == 1 && topLine < lines.size()-MAX_ROWS){
topLine++;
SoundController.getInstance().playButtonSound();
}
}
}
}
}
| 28.485714 | 141 | 0.648947 |
37882ceb70e1b28c4495975ce03ce01f4ed6cb2e | 688 | package ru.mydesignstudio.database.metadata.extractor.output.service.impl.operations.update.request;
import lombok.Builder;
import lombok.Data;
import ru.mydesignstudio.database.metadata.extractor.output.service.impl.model.ConfluenceBody;
import ru.mydesignstudio.database.metadata.extractor.output.service.impl.model.ConfluenceMetadata;
import ru.mydesignstudio.database.metadata.extractor.output.service.impl.model.ConfluenceVersion;
@Data
@Builder
public class UpdatePageRequest {
private String id;
private String title;
private String type;
private String status;
private ConfluenceVersion version;
private ConfluenceBody body;
private ConfluenceMetadata metadata;
}
| 34.4 | 100 | 0.837209 |
f5ab75bf537be1bd2ab82af5162503f0462bdd13 | 1,069 | package rfx.core.stream.kafka;
import rfx.core.model.CallbackResult;
import rfx.core.stream.emitters.DataEmitter;
import rfx.core.stream.message.KafkaDataPayload;
public class KafkaDataEmitter extends DataEmitter {
public KafkaDataEmitter() {
super();
}
private KafkaDataSeeder kafkaDataSeeder;
public KafkaDataEmitter(KafkaDataSeeder kafkaDataSeeder) {
super();
this.kafkaDataSeeder = kafkaDataSeeder;
}
public KafkaDataSeeder myKafkaDataSeeder() {
return kafkaDataSeeder;
}
public KafkaDataEmitter setKafkaDataSeeder(KafkaDataSeeder kafkaDataSeeder) {
this.kafkaDataSeeder = kafkaDataSeeder;
return this;
}
@Override
public synchronized CallbackResult<String> call() {
KafkaDataPayload dataPayload = this.myKafkaDataSeeder().buildQuery().seedData();
//topology.counter(getMetricKey()).addAndGet(dataPayload.size());//TODO
return new KafkaCallbackResult(dataPayload);
}
@Override
public String getMetricKey() {
return "emitter#"+this.myKafkaDataSeeder().getTopic()+"#"+this.myKafkaDataSeeder().getPartition();
}
}
| 25.452381 | 100 | 0.77362 |
f5072dae3dcda138232e46107c077af9d4c37a9b | 1,298 | /*
* Copyright 2010 Fae Hutter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package net.sparktank.glyph.workbench;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
/**
* An action bar advisor is responsible for creating, adding, and disposing of
* the actions added to a workbench window. Each window will be populated with
* new actions.
*/
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
// Actions - important to allocate these only in makeActions, and then use
// them in the fill methods. This ensures that the actions aren't recreated
// when fillActionBars is called with FILL_PROXY.
public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}
}
| 34.157895 | 78 | 0.766564 |
44a957d9397e31c193b0b11201ba14f3c37818e6 | 1,069 | package duckutil.sign;
import duckutil.Config;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import net.minidev.json.JSONObject;
public class Render
{
public static int render(Config config, String node, JSONObject view)
throws Exception
{
String host = config.require("host");
String key = config.require("key");
String url = String.format("http://%s/key/%s/nodes/%s/renders", host, key, node);
System.err.println(url);
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("Content-Type", "application/json");
JSONObject doc = new JSONObject();
OutputStream wr = connection.getOutputStream ();
wr.write(view.toJSONString().getBytes());
wr.flush();
wr.close();
int code = connection.getResponseCode();
return code;
}
}
| 23.755556 | 85 | 0.702526 |
3031272c81ba435027dcd562d1564d95dab864fe | 11,669 | package net.mavroprovato.springcms.command;
import net.mavroprovato.springcms.entity.Category;
import net.mavroprovato.springcms.entity.ContentStatus;
import net.mavroprovato.springcms.entity.Post;
import net.mavroprovato.springcms.entity.Tag;
import net.mavroprovato.springcms.entity.User;
import net.mavroprovato.springcms.repository.CategoryRepository;
import net.mavroprovato.springcms.repository.PostRepository;
import net.mavroprovato.springcms.repository.TagRepository;
import net.mavroprovato.springcms.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.context.annotation.ComponentScan;
import java.time.Instant;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* A command line command that generates test posts.
*/
@ComponentScan("net.mavroprovato.springcms")
public class GeneratePostsCommand implements ApplicationRunner {
/** Logger for the class */
private static Logger logger = LoggerFactory.getLogger(GeneratePostsCommand.class);
/** The default number of content items to generate */
private static final int DEFAULT_COUNT = 100;
/** The default minimum publication date for the content items */
private static final OffsetDateTime DEFAULT_START_DATE = OffsetDateTime.now().minus(1, ChronoUnit.YEARS);
/** The default maximum publication date for the content items */
private static final OffsetDateTime DEFAULT_END_DATE = OffsetDateTime.now();
/** The default number of tags to apply to a content item */
private static final int DEFAULT_TAG_COUNT = 2;
/** The default number of categories to apply to a content item */
private static final int DEFAULT_CATEGORY_COUNT = 2;
/** The post repository */
private final PostRepository postRepository;
/** The tag repository */
private final TagRepository tagRepository;
/** The category repository */
private final CategoryRepository categoryRepository;
/** The user repository */
private final UserRepository userRepository;
/**
* Value class to hold the options passed through the command line arguments
*/
private static final class Options {
int count = DEFAULT_COUNT;
OffsetDateTime startDate = DEFAULT_START_DATE;
OffsetDateTime endDate = DEFAULT_END_DATE;
int tagCount = DEFAULT_TAG_COUNT;
int categoryCount = DEFAULT_CATEGORY_COUNT;
}
/**
* Create the generate content command.
*
* @param postRepository The post repository.
* @param tagRepository The tag repository.
* @param categoryRepository The category repository.
*/
@Autowired
public GeneratePostsCommand(PostRepository postRepository, TagRepository tagRepository,
CategoryRepository categoryRepository, UserRepository userRepository) {
this.postRepository = postRepository;
this.tagRepository = tagRepository;
this.categoryRepository = categoryRepository;
this.userRepository = userRepository;
}
/**
* {@inheritDoc}
*/
@Override
public void run(ApplicationArguments args) {
// Parse the command line options
Options options = parseArguments(args);
if (options == null) {
// An error occurred during parsing
return;
}
// Generate the content items
logger.info("Generating {} content items between {} and {}.", options.count, options.startDate,
options.endDate);
for (int i = 0; i < options.count; i++) {
Post post = new Post();
post.setTitle("Test Title");
post.setContent("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation " +
"ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit " +
"in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat " +
"cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
post.setStatus(ContentStatus.PUBLISHED);
post.setPublishedAt(randomDateTime(options.startDate, options.endDate));
for (Tag tag: getRandomTags(options.tagCount)) {
post.getTags().add(tag);
}
for (Category category: getRandomCategories(options.categoryCount)) {
post.getCategories().add(category);
}
post.setAuthor(getRandomAuthor());
// Save the post
postRepository.save(post);
// Set the slug
post.setSlug("test-title-" + post.getId());
postRepository.save(post);
}
logger.info("Content items generated.");
}
/**
* Parse the command line arguments.
*
* @param args The command line arguments.
* @return The parsed command line arguments as options, or null if a parsing error has occurred.
*/
private Options parseArguments(ApplicationArguments args) {
Options options = new Options();
// Parse the count argument.
if (args.containsOption("count")) {
try {
options.count = Integer.parseInt(args.getOptionValues("count").get(0));
} catch (NumberFormatException e) {
logger.error("Cannot parse the count argument ({}) as an integer.",
args.getOptionValues("count").get(0));
return null;
}
if (options.count <= 0) {
logger.error("Count must be a positive integer.");
return null;
}
}
// Parse the start date argument
if (args.containsOption("start-date")) {
try {
String startDateString = args.getOptionValues("start-date").get(0);
options.startDate = LocalDate.parse(
startDateString, DateTimeFormatter.ISO_DATE).atStartOfDay().atOffset(ZoneOffset.UTC);
} catch (DateTimeParseException e) {
logger.error("Start date ({}) cannot be parsed.", args.getOptionValues("start-date").get(0));
return null;
}
}
// Parse the end date argument
if (args.containsOption("end-date")) {
try {
String endDateString = args.getOptionValues("end-date").get(0);
options.endDate = LocalDate.parse(
endDateString, DateTimeFormatter.ISO_DATE).atStartOfDay().atOffset(ZoneOffset.UTC);
} catch (DateTimeParseException e) {
logger.error("End date ({}) cannot be parsed.", args.getOptionValues("end-date").get(0));
return null;
}
}
// Check if start date is before end date
if (!options.startDate.isBefore(options.endDate)) {
logger.error("Start date must be before end date.");
return null;
}
// Parse the tag count argument.
if (args.containsOption("tag-count")) {
try {
options.tagCount = Integer.parseInt(args.getOptionValues("tag-count").get(0));
} catch (NumberFormatException e) {
logger.error("Cannot parse the tag count argument ({}) as an integer.",
args.getOptionValues("tag-count").get(0));
return null;
}
if (options.tagCount <= 0) {
logger.error("Tag count must be a positive integer.");
return null;
}
}
// Parse the category count argument.
if (args.containsOption("category-count")) {
try {
options.categoryCount = Integer.parseInt(args.getOptionValues("category-count").get(0));
} catch (NumberFormatException e) {
logger.error("Cannot parse the category count argument ({}) as an integer.",
args.getOptionValues("category-count").get(0));
return null;
}
if (options.categoryCount <= 0) {
logger.error("Category count must be a positive integer.");
return null;
}
}
return options;
}
/**
* Generate an iterable with random tags from the database.
*
* @param count The number of random tags to fetch.
* @return An iterable with random tags from the database.
*/
private Iterable<? extends Tag> getRandomTags(int count) {
List<Tag> allTags = tagRepository.findAll();
int postTagCount = Math.min(count, allTags.size());
List<Tag> postTags = new ArrayList<>();
for (int i = 0; i < postTagCount; i++) {
postTags.add(allTags.remove(ThreadLocalRandom.current().nextInt(allTags.size())));
}
return postTags;
}
/**
* Generate an iterable with random categories from the database.
*
* @param count The number of random categories to fetch.
* @return An iterable with random categories from the database.
*/
private Iterable<? extends Category> getRandomCategories(int count) {
List<Category> allCategories = categoryRepository.findAll();
int postCategoryCount = Math.min(count, allCategories.size());
List<Category> postCategories = new ArrayList<>();
for (int i = 0; i < postCategoryCount; i++) {
postCategories.add(allCategories.remove(ThreadLocalRandom.current().nextInt(allCategories.size())));
}
return postCategories;
}
/**
* Return a random date between two dates.
*
* @param startDate The minimum date.
* @param endDate The maximum date.
* @return The random date time.
*/
private OffsetDateTime randomDateTime(OffsetDateTime startDate, OffsetDateTime endDate) {
long min = startDate.toEpochSecond();
long max = endDate.toEpochSecond();
long random = ThreadLocalRandom.current().nextLong(min, max);
return OffsetDateTime.ofInstant(Instant.ofEpochSecond(random), ZoneId.of("UTC"));
}
/**
* Return a random author from the list of users.
*
* @return The random author.
*/
private User getRandomAuthor() {
List<User> allUsers = userRepository.findAll();
if (allUsers.isEmpty()) {
throw new IllegalStateException("No users are defined.");
}
return allUsers.get(ThreadLocalRandom.current().nextInt(allUsers.size()));
}
/**
* The entry point of the command.
*
* @param args The command line arguments.
*/
public static void main(String... args) {
SpringApplication command = new SpringApplication(GeneratePostsCommand.class);
command.setWebApplicationType(WebApplicationType.NONE);
command.run(args);
}
}
| 38.767442 | 120 | 0.637415 |
b538cf6bfa382fce05213d0cf66032fa7d5524bb | 416 | package ru.job4j.storage.store;
import ru.job4j.storage.entity.User;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class MemoryStorage implements Storage {
private List<User> users = new CopyOnWriteArrayList<>();
@Override
public void add(User user) {
users.add(user);
}
@Override
public List<User> getUsers() {
return this.users;
}
}
| 21.894737 | 60 | 0.692308 |
e8c882300849bbbfcb40751cd73a5d77636eab42 | 2,125 | //给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
//
// 例如:
//给定二叉树 [3,9,20,null,null,15,7],
//
//
// 3
// / \
// 9 20
// / \
// 15 7
//
//
// 返回锯齿形层序遍历如下:
//
//
//[
// [3],
// [20,9],
// [15,7]
//]
//
// Related Topics 栈 树 广度优先搜索
// 👍 375 👎 0
package com.tomster.leetcode.editor.cn;
import com.tomster.leetcode.entity.TreeNode;
import java.util.*;
/**
* @author: tomster
* @data: 2021-01-26 23:13:01
*/
public class BinaryTreeZigzagLevelOrderTraversal {
public static void main(String[] args) {
Solution solution = new BinaryTreeZigzagLevelOrderTraversal().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean rightWards = true;
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> levelList = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode pollNode = queue.poll();
levelList.add(pollNode.val);
if (pollNode.left != null) {
queue.add(pollNode.left);
}
if (pollNode.right != null) {
queue.add(pollNode.right);
}
}
if (!rightWards) {
Collections.reverse(levelList);
}
rightWards = !rightWards;
result.add(levelList);
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | 25 | 85 | 0.499765 |
95a977c473215f5f3c5e01e994eb6df4523bbb94 | 332 | package com.bus.sistema.app_reservacion.ModSeguridad.Services;
import java.util.List;
public interface GenericService<T extends Object> {
T save(T entity);
T update(T entity);
void delete(T entity);
void delete(int id);
void deleteInBatch(List<T> entities);
T find(int id);
List<T> findAll();
}
| 15.809524 | 62 | 0.680723 |
9d1127666d9302d3905eb9956982516982f39c29 | 3,991 | package com.eva.service.system.impl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eva.core.model.PageData;
import com.eva.core.model.PageWrap;
import com.eva.core.utils.Utils;
import com.eva.dao.system.SystemRoleMenuMapper;
import com.eva.dao.system.model.SystemRoleMenu;
import com.eva.service.system.SystemRoleMenuService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* 角色菜单关联Service实现
* @author Eva.Caesar Liu
* @date 2021/07/13 22:37
*/
@Service
public class SystemRoleMenuServiceImpl implements SystemRoleMenuService {
@Autowired
private SystemRoleMenuMapper systemRoleMenuMapper;
@Override
public Integer create(SystemRoleMenu systemRoleMenu) {
systemRoleMenuMapper.insert(systemRoleMenu);
return systemRoleMenu.getId();
}
@Override
public void deleteById(Integer id) {
SystemRoleMenu systemRoleMenu = new SystemRoleMenu();
systemRoleMenu.setId(id);
systemRoleMenu.setDeleted(Boolean.TRUE);
this.updateById(systemRoleMenu);
}
@Override
public void delete(SystemRoleMenu systemRoleMenu) {
SystemRoleMenu newRoleMenu = new SystemRoleMenu();
newRoleMenu.setDeleted(Boolean.TRUE);
UpdateWrapper<SystemRoleMenu> updateWrapper = new UpdateWrapper<>(systemRoleMenu);
systemRoleMenuMapper.update(newRoleMenu, updateWrapper);
}
@Override
@Transactional
public void deleteByIdInBatch(List<Integer> ids) {
if (CollectionUtils.isEmpty(ids)) return;
for (Integer id : ids) {
this.deleteById(id);
}
}
@Override
public void updateById(SystemRoleMenu systemRoleMenu) {
systemRoleMenuMapper.updateById(systemRoleMenu);
}
@Override
@Transactional
public void updateByIdInBatch(List<SystemRoleMenu> systemRoleMenus) {
if (CollectionUtils.isEmpty(systemRoleMenus)) return;
for (SystemRoleMenu systemRoleMenu: systemRoleMenus) {
this.updateById(systemRoleMenu);
}
}
@Override
public SystemRoleMenu findById(Integer id) {
return systemRoleMenuMapper.selectById(id);
}
@Override
public SystemRoleMenu findOne(SystemRoleMenu systemRoleMenu) {
Wrapper<SystemRoleMenu> wrapper = new QueryWrapper<>(systemRoleMenu);
return systemRoleMenuMapper.selectOne(wrapper);
}
@Override
public List<SystemRoleMenu> findList(SystemRoleMenu systemRoleMenu) {
Wrapper<SystemRoleMenu> wrapper = new QueryWrapper<>(systemRoleMenu);
return systemRoleMenuMapper.selectList(wrapper);
}
@Override
public PageData<SystemRoleMenu> findPage(PageWrap<SystemRoleMenu> pageWrap) {
IPage<SystemRoleMenu> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
QueryWrapper<SystemRoleMenu> queryWrapper = new QueryWrapper<>(Utils.MP.blankToNull(pageWrap.getModel()));
for(PageWrap.SortData sortData: pageWrap.getSorts()) {
if (sortData.getDirection().equalsIgnoreCase("DESC")) {
queryWrapper.orderByDesc(sortData.getProperty());
} else {
queryWrapper.orderByAsc(sortData.getProperty());
}
}
return PageData.from(systemRoleMenuMapper.selectPage(page, queryWrapper));
}
@Override
public long count(SystemRoleMenu systemRoleMenu) {
Wrapper<SystemRoleMenu> wrapper = new QueryWrapper<>(systemRoleMenu);
return systemRoleMenuMapper.selectCount(wrapper);
}
}
| 35.008772 | 114 | 0.72438 |
90ef920e1aa07bbcf763c5914b12df212b1f6921 | 1,677 | // Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;
import com.google.devtools.build.lib.analysis.configuredtargets.AbstractConfiguredTarget;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.InfoInterface;
import com.google.devtools.build.lib.packages.Provider;
import com.google.devtools.build.lib.skyframe.BuildConfigurationValue;
import javax.annotation.Nullable;
/** A configured target that is empty. */
public class EmptyConfiguredTarget extends AbstractConfiguredTarget {
public EmptyConfiguredTarget(Label label, BuildConfigurationValue.Key configurationKey) {
super(label, configurationKey, NestedSetBuilder.emptySet(Order.STABLE_ORDER));
}
@Nullable
@Override
protected InfoInterface rawGetSkylarkProvider(Provider.Key providerKey) {
return null;
}
@Override
protected Object rawGetSkylarkProvider(String providerKey) {
return null;
}
}
| 39 | 91 | 0.79189 |
9e7ff0b52bcbdb4fa70bbefa9d0a743f51f7c63c | 66,627 | /*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.seguridad.presentation.swing.jinternalframes;
import com.bydan.erp.cartera.presentation.swing.jinternalframes.*;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*;
import com.bydan.erp.nomina.presentation.swing.jinternalframes.*;
import com.bydan.erp.contabilidad.presentation.swing.jinternalframes.*;
import com.bydan.erp.comisiones.presentation.swing.jinternalframes.*;
import com.bydan.erp.inventario.presentation.swing.jinternalframes.*;
import com.bydan.erp.sris.presentation.swing.jinternalframes.*;
import com.bydan.erp.facturacion.presentation.swing.jinternalframes.*;
import com.bydan.erp.tesoreria.presentation.swing.jinternalframes.*;
import com.bydan.erp.puntoventa.presentation.swing.jinternalframes.*;
import com.bydan.erp.activosfijos.presentation.swing.jinternalframes.*;
import com.bydan.erp.importaciones.presentation.swing.jinternalframes.*;
import com.bydan.erp.produccion.presentation.swing.jinternalframes.*;
import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*;//;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.auxiliar.*;
import com.bydan.erp.cartera.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.nomina.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.contabilidad.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.comisiones.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.inventario.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.sris.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.facturacion.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.tesoreria.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.puntoventa.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.activosfijos.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.importaciones.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.produccion.presentation.web.jsf.sessionbean.*;
//import com.bydan.erp.seguridad.presentation.report.source.*;
import com.bydan.framework.erp.business.entity.Reporte;
import com.bydan.erp.seguridad.business.entity.Modulo;
import com.bydan.erp.seguridad.business.entity.Opcion;
import com.bydan.erp.seguridad.business.entity.Usuario;
import com.bydan.erp.seguridad.business.entity.ResumenUsuario;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg;
import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario;
import com.bydan.erp.seguridad.util.SistemaParameterReturnGeneral;
import com.bydan.erp.seguridad.business.entity.*;
import com.bydan.erp.seguridad.util.DiaConstantesFunciones;
import com.bydan.erp.seguridad.business.logic.*;
import com.bydan.framework.erp.business.entity.DatoGeneral;
import com.bydan.framework.erp.business.entity.OrderBy;
import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.framework.erp.business.logic.*;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverter;
import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate;
import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing;
import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase;
import com.bydan.framework.erp.presentation.desktop.swing.*;
import com.bydan.framework.erp.util.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.*;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.TableColumn;
import com.toedter.calendar.JDateChooser;
@SuppressWarnings("unused")
public class DiaDetalleFormJInternalFrame extends DiaBeanSwingJInternalFrameAdditional {
private static final long serialVersionUID = 1L;
public JToolBar jTtoolBarDetalleDia;
protected JMenuBar jmenuBarDetalleDia;
protected JMenu jmenuDetalleDia;
protected JMenu jmenuDetalleArchivoDia;
protected JMenu jmenuDetalleAccionesDia;
protected JMenu jmenuDetalleDatosDia;
protected JPanel jContentPane = null;
protected JPanel jContentPaneDetalleDia = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
protected GridBagLayout gridaBagLayoutDia;
protected GridBagConstraints gridBagConstraintsDia;
//protected JInternalFrameBase jInternalFrameParent; //ESTA EN BASE
//protected DiaBeanSwingJInternalFrameAdditional jInternalFrameDetalleDia;
//VENTANAS PARA ACTUALIZAR Y BUSCAR FK
public DiaSessionBean diaSessionBean;
public DiaLogic diaLogic;
public JScrollPane jScrollPanelDatosDia;
public JScrollPane jScrollPanelDatosEdicionDia;
public JScrollPane jScrollPanelDatosGeneralDia;
protected JPanel jPanelCamposDia;
protected JPanel jPanelCamposOcultosDia;
protected JPanel jPanelAccionesDia;
protected JPanel jPanelAccionesFormularioDia;
protected Integer iXPanelCamposDia=0;
protected Integer iYPanelCamposDia=0;
protected Integer iXPanelCamposOcultosDia=0;
protected Integer iYPanelCamposOcultosDia=0;
;
;
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
public JButton jButtonNuevoDia;
public JButton jButtonModificarDia;
public JButton jButtonActualizarDia;
public JButton jButtonEliminarDia;
public JButton jButtonCancelarDia;
public JButton jButtonGuardarCambiosDia;
public JButton jButtonGuardarCambiosTablaDia;
protected JButton jButtonCerrarDia;
protected JButton jButtonProcesarInformacionDia;
protected JCheckBox jCheckBoxPostAccionNuevoDia;
protected JCheckBox jCheckBoxPostAccionSinCerrarDia;
protected JCheckBox jCheckBoxPostAccionSinMensajeDia;
//TOOLBAR
protected JButton jButtonNuevoToolBarDia;
protected JButton jButtonModificarToolBarDia;
protected JButton jButtonActualizarToolBarDia;
protected JButton jButtonEliminarToolBarDia;
protected JButton jButtonCancelarToolBarDia;
protected JButton jButtonGuardarCambiosToolBarDia;
protected JButton jButtonGuardarCambiosTablaToolBarDia;
protected JButton jButtonMostrarOcultarTablaToolBarDia;
protected JButton jButtonCerrarToolBarDia;
protected JButton jButtonProcesarInformacionToolBarDia;
//TOOLBAR
//MENU
protected JMenuItem jMenuItemNuevoDia;
protected JMenuItem jMenuItemModificarDia;
protected JMenuItem jMenuItemActualizarDia;
protected JMenuItem jMenuItemEliminarDia;
protected JMenuItem jMenuItemCancelarDia;
protected JMenuItem jMenuItemGuardarCambiosDia;
protected JMenuItem jMenuItemGuardarCambiosTablaDia;
protected JMenuItem jMenuItemCerrarDia;
protected JMenuItem jMenuItemDetalleCerrarDia;
protected JMenuItem jMenuItemDetalleMostarOcultarDia;
protected JMenuItem jMenuItemProcesarInformacionDia;
protected JMenuItem jMenuItemNuevoGuardarCambiosDia;
protected JMenuItem jMenuItemMostrarOcultarDia;
//MENU
protected JLabel jLabelAccionesDia;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposRelacionesDia;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposAccionesDia;
@SuppressWarnings("rawtypes")
public JComboBox jComboBoxTiposAccionesFormularioDia;
protected Boolean conMaximoRelaciones=true;
protected Boolean conFuncionalidadRelaciones=true;
public Boolean conCargarMinimo=false;
public Boolean conMostrarAccionesCampo=false;
public Boolean permiteRecargarForm=false;//PARA NUEVO PREPARAR Y MANEJO DE EVENTOS, EVITAR QUE SE EJECUTE AL CARGAR VENTANA O LOAD
public Boolean conCargarFormDetalle=false;
public JPanel jPanelidDia;
public JLabel jLabelIdDia;
public JTextFieldMe jTextFieldidDia;
public JButton jButtonidDiaBusqueda= new JButtonMe();
public JPanel jPanelnombreDia;
public JLabel jLabelnombreDia;
public JTextField jTextFieldnombreDia;
public JButton jButtonnombreDiaBusqueda= new JButtonMe();
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
protected JTabbedPane jTabbedPaneRelacionesDia;
public static int openFrameCount = 0;
public static final int xOffset = 10, yOffset = 35;
//LOS DATOS DE NUEVO Y EDICION ACTUAL APARECEN EN OTRA VENTANA(true) O NO(false)
public static Boolean CON_DATOS_FRAME=true;
public static Boolean ISBINDING_MANUAL=true;
public static Boolean ISLOAD_FKLOTE=true;
public static Boolean ISBINDING_MANUAL_TABLA=true;
public static Boolean CON_CARGAR_MEMORIA_INICIAL=true;
//Al final no se utilizan, se inicializan desde JInternalFrameBase, desde ParametroGeneralUsuario
public static String STIPO_TAMANIO_GENERAL="NORMAL";
public static String STIPO_TAMANIO_GENERAL_TABLA="NORMAL";
public static Boolean CONTIPO_TAMANIO_MANUAL=false;
public static Boolean CON_LLAMADA_SIMPLE=true;
public static Boolean CON_LLAMADA_SIMPLE_TOTAL=true;
public static Boolean ESTA_CARGADO_PORPARTE=false;
public int iWidthScroll=0;//(screenSize.width-screenSize.width/2)+(250*0);
public int iHeightScroll=0;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
public int iWidthFormulario=450;//(screenSize.width-screenSize.width/2)+(250*0);
public int iHeightFormulario=286;//(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
public int iHeightFormularioMaximo=0;
public int iWidthFormularioMaximo=0;
public int iWidthTableDefinicion=0;
public double dStart = 0;
public double dEnd = 0;
public double dDif = 0;
public SistemaParameterReturnGeneral sistemaReturnGeneral;
public List<Opcion> opcionsRelacionadas=new ArrayList<Opcion>();
public DiaDetalleFormJInternalFrame(String sTipo) throws Exception {
super(PaginaTipo.FORMULARIO);
try {
if(sTipo.equals("MINIMO")) {
/*
this.jPanelCamposDia=new JPanel();
this.jPanelAccionesFormularioDia=new JPanel();
this.jmenuBarDetalleDia=new JMenuBar();
this.jTtoolBarDetalleDia=new JToolBar();
*/
}
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public DiaDetalleFormJInternalFrame(PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("Dia No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
Boolean cargarRelaciones=false;
this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,PaginaTipo.PRINCIPAL);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
//ES AUXILIAR PARA WINDOWS FORMS
public DiaDetalleFormJInternalFrame() throws Exception {
super(PaginaTipo.FORMULARIO);
//super("Dia No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
Boolean cargarRelaciones=false;
this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,PaginaTipo.PRINCIPAL);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public DiaDetalleFormJInternalFrame(Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("Dia No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
this.initialize(null,false,false,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public DiaDetalleFormJInternalFrame(Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("Dia No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
this.initialize(null,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,null,null,null,null,null,null,paginaTipo);
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public DiaDetalleFormJInternalFrame(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);//,jdesktopPane
this.jDesktopPane=jdesktopPane;
this.dStart=(double)System.currentTimeMillis();
//super("Dia No " + (++openFrameCount),true, /*resizable*/true, /*closable*/true, /*maximizable*/true);//iconifiable
try {
long start_time=0;
long end_time=0;
if(Constantes2.ISDEVELOPING2) {
start_time = System.currentTimeMillis();
}
this.initialize(jdesktopPane,conGuardarRelaciones,esGuardarRelacionado,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo);
if(Constantes2.ISDEVELOPING2) {
end_time = System.currentTimeMillis();
String sTipo="Clase Padre Ventana";
Funciones2.getMensajeTiempoEjecucion(start_time, end_time, sTipo,false);
}
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public JInternalFrameBase getJInternalFrameParent() {
return jInternalFrameParent;
}
public void setJInternalFrameParent(JInternalFrameBase internalFrameParent) {
jInternalFrameParent = internalFrameParent;
}
public JButton getjButtonActualizarToolBarDia() {
return this.jButtonActualizarToolBarDia;
}
public JButton getjButtonEliminarToolBarDia() {
return this.jButtonEliminarToolBarDia;
}
public JButton getjButtonCancelarToolBarDia() {
return this.jButtonCancelarToolBarDia;
}
public JButton getjButtonProcesarInformacionDia() {
return this.jButtonProcesarInformacionDia;
}
public void setjButtonProcesarInformacion(JButton jButtonProcesarInformacionDia) {
this.jButtonProcesarInformacionDia = jButtonProcesarInformacionDia;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesDia() {
return this.jComboBoxTiposAccionesDia;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposRelacionesDia(
JComboBox jComboBoxTiposRelacionesDia) {
this.jComboBoxTiposRelacionesDia = jComboBoxTiposRelacionesDia;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesDia(
JComboBox jComboBoxTiposAccionesDia) {
this.jComboBoxTiposAccionesDia = jComboBoxTiposAccionesDia;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesFormularioDia() {
return this.jComboBoxTiposAccionesFormularioDia;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesFormularioDia(
JComboBox jComboBoxTiposAccionesFormularioDia) {
this.jComboBoxTiposAccionesFormularioDia = jComboBoxTiposAccionesFormularioDia;
}
private void initialize(JDesktopPane jdesktopPane,Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
this.diaSessionBean=new DiaSessionBean();
this.diaSessionBean.setConGuardarRelaciones(conGuardarRelaciones);
this.diaSessionBean.setEsGuardarRelacionado(esGuardarRelacionado);
this.conCargarMinimo=this.diaSessionBean.getEsGuardarRelacionado();
this.conMostrarAccionesCampo=parametroGeneralUsuario.getcon_mostrar_acciones_campo_general() || opcionActual.getcon_mostrar_acciones_campo();
if(!this.conCargarMinimo) {
}
this.sTipoTamanioGeneral=FuncionesSwing.getTipoTamanioGeneral(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.sTipoTamanioGeneralTabla=FuncionesSwing.getTipoTamanioGeneralTabla(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioManual=FuncionesSwing.getConTipoTamanioManual(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
this.conTipoTamanioTodo=FuncionesSwing.getConTipoTamanioTodo(this,parametroGeneralUsuario,conGuardarRelaciones,esGuardarRelacionado);
DiaJInternalFrame.STIPO_TAMANIO_GENERAL=this.sTipoTamanioGeneral;
DiaJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA=this.sTipoTamanioGeneralTabla;
DiaJInternalFrame.CONTIPO_TAMANIO_MANUAL=this.conTipoTamanioManual;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int iWidth=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO);
int iHeight=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
//this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.opcionActual,this.usuarioActual,"Dia MANTENIMIENTO"));
if(iWidth > 650) {
iWidth=650;
}
if(iHeight > 650) {
iHeight=650;
}
this.setSize(iWidth,iHeight);
this.setFrameIcon(new ImageIcon(FuncionesSwing.getImagenBackground(Constantes2.S_ICON_IMAGE)));
this.setContentPane(this.getJContentPane(iWidth,iHeight,jdesktopPane,cargarRelaciones,usuarioActual,resumenUsuarioActual,moduloActual,opcionActual,parametroGeneralSg,parametroGeneralUsuario,paginaTipo));
if(!this.diaSessionBean.getEsGuardarRelacionado()) {
this.setResizable(true);
this.setClosable(true);
this.setMaximizable(true);
this.iconable=true;
setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
if(Constantes.CON_VARIAS_VENTANAS) {
openFrameCount++;
if(openFrameCount==Constantes.INUM_MAX_VENTANAS) {
openFrameCount=0;
}
}
}
DiaJInternalFrame.ESTA_CARGADO_PORPARTE=true;
}
public void inicializarToolBar() {
this.jTtoolBarDetalleDia= new JToolBar("MENU DATOS");
//TOOLBAR
//PRINCIPAL
this.jButtonProcesarInformacionToolBarDia=new JButtonMe();
this.jButtonModificarToolBarDia=new JButtonMe();
//PRINCIPAL
//DETALLE
this.jButtonActualizarToolBarDia=FuncionesSwing.getButtonToolBarGeneral(this.jButtonActualizarToolBarDia,this.jTtoolBarDetalleDia,
"actualizar","actualizar","Actualizar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ACTUALIZAR"),"Actualizar",false);
this.jButtonEliminarToolBarDia=FuncionesSwing.getButtonToolBarGeneral(this.jButtonEliminarToolBarDia,this.jTtoolBarDetalleDia,
"eliminar","eliminar","Eliminar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ELIMINAR"),"Eliminar",false);
this.jButtonCancelarToolBarDia=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCancelarToolBarDia,this.jTtoolBarDetalleDia,
"cancelar","cancelar","Cancelar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CANCELAR"),"Cancelar",false);
this.jButtonGuardarCambiosToolBarDia=FuncionesSwing.getButtonToolBarGeneral(this.jButtonGuardarCambiosToolBarDia,this.jTtoolBarDetalleDia,
"guardarcambios","guardarcambios","Guardar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"),"Guardar",false);
FuncionesSwing.setBoldButtonToolBar(this.jButtonActualizarToolBarDia,STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButtonToolBar(this.jButtonEliminarToolBarDia,STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButtonToolBar(this.jButtonCancelarToolBarDia,STIPO_TAMANIO_GENERAL,false,false,this);
}
public void cargarMenus() {
this.jmenuBarDetalleDia=new JMenuBarMe();
//DETALLE
this.jmenuDetalleDia=new JMenuMe("Datos Relacionados");
this.jmenuDetalleArchivoDia=new JMenuMe("Archivo");
this.jmenuDetalleAccionesDia=new JMenuMe("Acciones");
this.jmenuDetalleDatosDia=new JMenuMe("Datos");
//DETALLE_FIN
this.jMenuItemNuevoDia= new JMenuItem("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jMenuItemNuevoDia.setActionCommand("Nuevo");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoDia,"nuevo_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemModificarDia= new JMenuItem("Editar" + FuncionesSwing.getKeyMensaje("MODIFICAR"));
this.jMenuItemModificarDia.setActionCommand("Editar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemModificarDia,"modificar_button","Editar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemModificarDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemActualizarDia= new JMenuItem("Actualizar" + FuncionesSwing.getKeyMensaje("ACTUALIZAR"));
this.jMenuItemActualizarDia.setActionCommand("Actualizar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemActualizarDia,"actualizar_button","Actualizar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemActualizarDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemEliminarDia= new JMenuItem("Eliminar" + FuncionesSwing.getKeyMensaje("ELIMINAR"));
this.jMenuItemEliminarDia.setActionCommand("Eliminar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemEliminarDia,"eliminar_button","Eliminar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemEliminarDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCancelarDia= new JMenuItem("Cancelar" + FuncionesSwing.getKeyMensaje("CANCELAR"));
this.jMenuItemCancelarDia.setActionCommand("Cancelar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCancelarDia,"cancelar_button","Cancelar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCancelarDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosDia= new JMenuItem("Guardar" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosDia.setActionCommand("Guardar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosDia,"guardarcambios_button","Guardar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCerrarDia= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemCerrarDia.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCerrarDia,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCerrarDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleCerrarDia= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemDetalleCerrarDia.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleCerrarDia,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleCerrarDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemMostrarOcultarDia= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemMostrarOcultarDia.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemMostrarOcultarDia,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemMostrarOcultarDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleMostarOcultarDia= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemDetalleMostarOcultarDia.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleMostarOcultarDia,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleMostarOcultarDia, STIPO_TAMANIO_GENERAL,false,true,this);
//DETALLE
this.jmenuDetalleArchivoDia.add(this.jMenuItemDetalleCerrarDia);
this.jmenuDetalleAccionesDia.add(this.jMenuItemActualizarDia);
this.jmenuDetalleAccionesDia.add(this.jMenuItemEliminarDia);
this.jmenuDetalleAccionesDia.add(this.jMenuItemCancelarDia);
//this.jmenuDetalleDatosDia.add(this.jMenuItemDetalleAbrirOrderByDia);
this.jmenuDetalleDatosDia.add(this.jMenuItemDetalleMostarOcultarDia);
//this.jmenuDetalleAccionesDia.add(this.jMenuItemGuardarCambiosDia);
//DETALLE_FIN
//RELACIONES
//RELACIONES
//DETALLE
FuncionesSwing.setBoldMenu(this.jmenuDetalleArchivoDia, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDetalleAccionesDia, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDetalleDatosDia, STIPO_TAMANIO_GENERAL,false,true,this);
this.jmenuBarDetalleDia.add(this.jmenuDetalleArchivoDia);
this.jmenuBarDetalleDia.add(this.jmenuDetalleAccionesDia);
this.jmenuBarDetalleDia.add(this.jmenuDetalleDatosDia);
//DETALLE_FIN
//AGREGA MENU DETALLE A PANTALLA
this.setJMenuBar(this.jmenuBarDetalleDia);
}
public void inicializarElementosCamposDia() {
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
jLabelIdDia = new JLabelMe();
jLabelIdDia.setText(""+Constantes2.S_CODIGO_UNICO+"");
jLabelIdDia.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
jLabelIdDia.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
jLabelIdDia.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelIdDia,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelidDia = new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelidDia.setToolTipText(DiaConstantesFunciones.LABEL_ID);
this.gridaBagLayoutDia= new GridBagLayout();
this.jPanelidDia.setLayout(this.gridaBagLayoutDia);
jTextFieldidDia = new JTextFieldMe();
jTextFieldidDia.setText("Id");
jTextFieldidDia.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
jTextFieldidDia.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
jTextFieldidDia.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelnombreDia = new JLabelMe();
this.jLabelnombreDia.setText(""+DiaConstantesFunciones.LABEL_NOMBRE+" : *");
this.jLabelnombreDia.setToolTipText("Nombre");
this.jLabelnombreDia.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelnombreDia.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelnombreDia.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-60),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelnombreDia,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelnombreDia=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelnombreDia.setToolTipText(DiaConstantesFunciones.LABEL_NOMBRE);
this.gridaBagLayoutDia = new GridBagLayout();
this.jPanelnombreDia.setLayout(this.gridaBagLayoutDia);
jTextFieldnombreDia= new JTextFieldMe();
jTextFieldnombreDia.setEnabled(false);
jTextFieldnombreDia.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFieldnombreDia.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFieldnombreDia.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldTextField(jTextFieldnombreDia,STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonnombreDiaBusqueda= new JButtonMe();
this.jButtonnombreDiaBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonnombreDiaBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonnombreDiaBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonnombreDiaBusqueda.setText("U");
this.jButtonnombreDiaBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonnombreDiaBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonnombreDiaBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jTextFieldnombreDia.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jTextFieldnombreDia.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"nombreDiaBusqueda"));
if(this.diaSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonnombreDiaBusqueda.setVisible(false); }
}
public void inicializarElementosCamposForeigKeysDia() {
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
}
public void jButtonActionPerformedTecladoGeneral(String sTipo,ActionEvent evt) {
//System.out.println("TRANSFIERE EL MANEJO AL PADRE O FORM PRINCIPAL");
jInternalFrameParent.jButtonActionPerformedTecladoGeneral(sTipo,evt);
}
//JPanel
//@SuppressWarnings({"unchecked" })//"rawtypes"
public JScrollPane getJContentPane(int iWidth,int iHeight,JDesktopPane jDesktopPane,Boolean cargarRelaciones,Usuario usuarioActual,ResumenUsuario resumenUsuarioActual,Modulo moduloActual,Opcion opcionActual,ParametroGeneralSg parametroGeneralSg,ParametroGeneralUsuario parametroGeneralUsuario,PaginaTipo paginaTipo) throws Exception {
//PARA TABLA PARAMETROS
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
this.jContentPane = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
this.usuarioActual=usuarioActual;
this.resumenUsuarioActual=resumenUsuarioActual;
this.opcionActual=opcionActual;
this.moduloActual=moduloActual;
this.parametroGeneralSg=parametroGeneralSg;
this.parametroGeneralUsuario=parametroGeneralUsuario;
this.jDesktopPane=jDesktopPane;
this.conFuncionalidadRelaciones=parametroGeneralUsuario.getcon_guardar_relaciones();
int iGridyPrincipal=0;
this.inicializarToolBar();
//CARGAR MENUS
//this.jInternalFrameDetalleDia = new DiaBeanSwingJInternalFrameAdditional(paginaTipo);//JInternalFrameBase("Dia DATOS");
this.cargarMenus();
this.gridaBagLayoutDia= new GridBagLayout();
String sToolTipDia="";
sToolTipDia=DiaConstantesFunciones.SCLASSWEBTITULO;
if(Constantes.ISDEVELOPING) {
sToolTipDia+="(Seguridad.Dia)";
}
if(!this.diaSessionBean.getEsGuardarRelacionado()) {
sToolTipDia+="_"+this.opcionActual.getId();
}
this.jButtonNuevoDia = new JButtonMe();
this.jButtonModificarDia = new JButtonMe();
this.jButtonActualizarDia = new JButtonMe();
this.jButtonEliminarDia = new JButtonMe();
this.jButtonCancelarDia = new JButtonMe();
this.jButtonGuardarCambiosDia = new JButtonMe();
this.jButtonGuardarCambiosTablaDia = new JButtonMe();
this.jButtonCerrarDia = new JButtonMe();
this.jScrollPanelDatosDia = new JScrollPane();
this.jScrollPanelDatosEdicionDia = new JScrollPane();
this.jScrollPanelDatosGeneralDia = new JScrollPane();
this.jPanelCamposDia = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelCamposOcultosDia = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelAccionesDia = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelAccionesFormularioDia = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
//if(!this.conCargarMinimo) {
;
;
//}
this.sPath=" <---> Acceso: Dia";
if(!this.diaSessionBean.getEsGuardarRelacionado()) {
this.jScrollPanelDatosDia.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Dias" + this.sPath));
} else {
this.jScrollPanelDatosDia.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
this.jScrollPanelDatosEdicionDia.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jScrollPanelDatosGeneralDia.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jPanelCamposDia.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelCamposDia.setName("jPanelCamposDia");
this.jPanelCamposOcultosDia.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos Ocultos"));
this.jPanelCamposOcultosDia.setName("jPanelCamposOcultosDia");
this.jPanelAccionesDia.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));
this.jPanelAccionesDia.setToolTipText("Acciones");
this.jPanelAccionesDia.setName("Acciones");
this.jPanelAccionesFormularioDia.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones Extra/Post"));
this.jPanelAccionesFormularioDia.setToolTipText("Acciones");
this.jPanelAccionesFormularioDia.setName("Acciones");
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosEdicionDia, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosGeneralDia, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosDia, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelCamposDia, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelCamposOcultosDia, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelAccionesFormularioDia, STIPO_TAMANIO_GENERAL,false,false,this);
//if(!this.conCargarMinimo) {
;
;
//}
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
this.jButtonNuevoDia.setText("Nuevo");
this.jButtonModificarDia.setText("Editar");
this.jButtonActualizarDia.setText("Actualizar");
this.jButtonEliminarDia.setText("Eliminar");
this.jButtonCancelarDia.setText("Cancelar");
this.jButtonGuardarCambiosDia.setText("Guardar");
this.jButtonGuardarCambiosTablaDia.setText("Guardar");
this.jButtonCerrarDia.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoDia,"nuevo_button","Nuevo",this.diaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonModificarDia,"modificar_button","Editar",this.diaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonActualizarDia,"actualizar_button","Actualizar",this.diaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonEliminarDia,"eliminar_button","Eliminar",this.diaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCancelarDia,"cancelar_button","Cancelar",this.diaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosDia,"guardarcambios_button","Guardar",this.diaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosTablaDia,"guardarcambiostabla_button","Guardar",this.diaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarDia,"cerrar_button","Salir",this.diaSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoDia, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonModificarDia, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosDia, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosTablaDia, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCerrarDia, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonActualizarDia, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButton(this.jButtonEliminarDia, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButton(this.jButtonCancelarDia, STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonNuevoDia.setToolTipText("Nuevo"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jButtonModificarDia.setToolTipText("Editar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO+"");// + FuncionesSwing.getKeyMensaje("MODIFICAR"))
this.jButtonActualizarDia.setToolTipText("Actualizar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ACTUALIZAR"));
this.jButtonEliminarDia.setToolTipText("Eliminar)"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ELIMINAR"));
this.jButtonCancelarDia.setToolTipText("Cancelar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CANCELAR"));
this.jButtonGuardarCambiosDia.setToolTipText("Guardar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonGuardarCambiosTablaDia.setToolTipText("Guardar"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonCerrarDia.setToolTipText("Salir"+" "+DiaConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CERRAR"));
//HOT KEYS
/*
N->Nuevo
N->Alt + Nuevo Relaciones (ANTES R)
A->Actualizar
E->Eliminar
S->Cerrar
C->->Mayus + Cancelar (ANTES Q->Quit)
G->Guardar Cambios
D->Duplicar
C->Alt + Cop?ar
O->Orden
N->Nuevo Tabla
R->Recargar Informacion Inicial (ANTES I)
Alt + Pag.Down->Siguientes
Alt + Pag.Up->Anteriores
NO UTILIZADOS
M->Modificar
*/
String sMapKey = "";
InputMap inputMap =null;
//NUEVO
sMapKey = "NuevoDia";
inputMap = this.jButtonNuevoDia.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO") , FuncionesSwing.getMaskKey("NUEVO")), sMapKey);
this.jButtonNuevoDia.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"NuevoDia"));
//ACTUALIZAR
sMapKey = "ActualizarDia";
inputMap = this.jButtonActualizarDia.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ACTUALIZAR") , FuncionesSwing.getMaskKey("ACTUALIZAR")), sMapKey);
this.jButtonActualizarDia.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"ActualizarDia"));
//ELIMINAR
sMapKey = "EliminarDia";
inputMap = this.jButtonEliminarDia.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ELIMINAR") , FuncionesSwing.getMaskKey("ELIMINAR")), sMapKey);
this.jButtonEliminarDia.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"EliminarDia"));
//CANCELAR
sMapKey = "CancelarDia";
inputMap = this.jButtonCancelarDia.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CANCELAR") , FuncionesSwing.getMaskKey("CANCELAR")), sMapKey);
this.jButtonCancelarDia.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CancelarDia"));
//CERRAR
sMapKey = "CerrarDia";
inputMap = this.jButtonCerrarDia.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CERRAR") , FuncionesSwing.getMaskKey("CERRAR")), sMapKey);
this.jButtonCerrarDia.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CerrarDia"));
//GUARDAR CAMBIOS
sMapKey = "GuardarCambiosTablaDia";
inputMap = this.jButtonGuardarCambiosTablaDia.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("GUARDAR_CAMBIOS") , FuncionesSwing.getMaskKey("GUARDAR_CAMBIOS")), sMapKey);
this.jButtonGuardarCambiosTablaDia.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"GuardarCambiosTablaDia"));
//HOT KEYS
this.jCheckBoxPostAccionNuevoDia = new JCheckBoxMe();
this.jCheckBoxPostAccionNuevoDia.setText("Nuevo");
this.jCheckBoxPostAccionNuevoDia.setToolTipText("Nuevo Dia");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionNuevoDia, STIPO_TAMANIO_GENERAL,false,false,this);
this.jCheckBoxPostAccionSinCerrarDia = new JCheckBoxMe();
this.jCheckBoxPostAccionSinCerrarDia.setText("Sin Cerrar");
this.jCheckBoxPostAccionSinCerrarDia.setToolTipText("Sin Cerrar Ventana Dia");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionSinCerrarDia, STIPO_TAMANIO_GENERAL,false,false,this);
this.jCheckBoxPostAccionSinMensajeDia = new JCheckBoxMe();
this.jCheckBoxPostAccionSinMensajeDia.setText("Sin Mensaje");
this.jCheckBoxPostAccionSinMensajeDia.setToolTipText("Sin Mensaje Confirmacion");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionSinMensajeDia, STIPO_TAMANIO_GENERAL,false,false,this);
this.jComboBoxTiposAccionesDia = new JComboBoxMe();
//this.jComboBoxTiposAccionesDia.setText("Accion");
this.jComboBoxTiposAccionesDia.setToolTipText("Tipos de Acciones");
this.jComboBoxTiposAccionesFormularioDia = new JComboBoxMe();
//this.jComboBoxTiposAccionesFormularioDia.setText("Accion");
this.jComboBoxTiposAccionesFormularioDia.setToolTipText("Tipos de Acciones");
this.jLabelAccionesDia = new JLabelMe();
this.jLabelAccionesDia.setText("Acciones");
this.jLabelAccionesDia.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesDia.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesDia.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
//HOT KEYS2
/*
T->Nuevo Tabla
*/
//NUEVO GUARDAR CAMBIOS O NUEVO TABLA
//HOT KEYS2
//ELEMENTOS
this.inicializarElementosCamposDia();
//ELEMENTOS FK
this.inicializarElementosCamposForeigKeysDia();
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
//ELEMENTOS TABLAS PARAMETOS_FIN
this.jTabbedPaneRelacionesDia=new JTabbedPane();
this.jTabbedPaneRelacionesDia.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Relacionados"));
//ESTA EN BEAN
FuncionesSwing.setBoldTabbedPane(this.jTabbedPaneRelacionesDia,STIPO_TAMANIO_GENERAL,false,false,this);
int iPosXAccionPaginacion=0;
this.jComboBoxTiposAccionesDia.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesDia.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesDia.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesDia, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposAccionesFormularioDia.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesFormularioDia.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesFormularioDia.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesFormularioDia, STIPO_TAMANIO_GENERAL,false,false,this);
GridBagLayout gridaBagLayoutCamposDia = new GridBagLayout();
GridBagLayout gridaBagLayoutCamposOcultosDia = new GridBagLayout();
this.jPanelCamposDia.setLayout(gridaBagLayoutCamposDia);
this.jPanelCamposOcultosDia.setLayout(gridaBagLayoutCamposOcultosDia);
;
;
//SUBPANELES SIMPLES
//SUBPANELES POR CAMPO
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx = 0;
this.gridBagConstraintsDia.ipadx = 0;
this.gridBagConstraintsDia.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelidDia.add(jLabelIdDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx = 1;
this.gridBagConstraintsDia.ipadx = 0;
this.gridBagConstraintsDia.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelidDia.add(jTextFieldidDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx = 0;
this.gridBagConstraintsDia.ipadx = 0;
this.gridBagConstraintsDia.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelnombreDia.add(jLabelnombreDia, this.gridBagConstraintsDia);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsDia = new GridBagConstraints();
//this.gridBagConstraintsDia.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx = 2;
this.gridBagConstraintsDia.ipadx = 0;
this.gridBagConstraintsDia.insets = new Insets(0, 0, 0, 0);
this.jPanelnombreDia.add(jButtonnombreDiaBusqueda, this.gridBagConstraintsDia);
}
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx = 1;
this.gridBagConstraintsDia.ipadx = 0;
this.gridBagConstraintsDia.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelnombreDia.add(jTextFieldnombreDia, this.gridBagConstraintsDia);
//SUBPANELES SIMPLES
//SUBPANELES EN PANEL
//SUBPANELES EN PANEL CAMPOS NORMAL
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill = GridBagConstraints.NONE;
this.gridBagConstraintsDia.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsDia.gridy = iYPanelCamposDia;
this.gridBagConstraintsDia.gridx = iXPanelCamposDia++;
this.gridBagConstraintsDia.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsDia.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposDia.add(this.jPanelidDia, this.gridBagConstraintsDia);
if(iXPanelCamposDia % 1==0) {
iXPanelCamposDia=0;
iYPanelCamposDia++;
}
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill = GridBagConstraints.NONE;
this.gridBagConstraintsDia.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsDia.gridy = iYPanelCamposDia;
this.gridBagConstraintsDia.gridx = iXPanelCamposDia++;
this.gridBagConstraintsDia.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsDia.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposDia.add(this.jPanelnombreDia, this.gridBagConstraintsDia);
if(iXPanelCamposDia % 1==0) {
iXPanelCamposDia=0;
iYPanelCamposDia++;
}
//SUBPANELES EN PANEL CAMPOS OCULTOS
//SUBPANELES EN PANEL CAMPOS INICIO
//SUBPANELES EN PANEL CAMPOS FIN
//SUBPANELES EN PANEL
//ELEMENTOS TABLAS PARAMETOS
//SUBPANELES POR CAMPO
if(!this.conCargarMinimo) {
//SUBPANELES EN PANEL CAMPOS
}
//ELEMENTOS TABLAS PARAMETOS_FIN
Integer iGridXParametrosAccionesFormulario=0;
Integer iGridYParametrosAccionesFormulario=0;
GridBagLayout gridaBagLayoutAccionesDia= new GridBagLayout();
this.jPanelAccionesDia.setLayout(gridaBagLayoutAccionesDia);
GridBagLayout gridaBagLayoutAccionesFormularioDia= new GridBagLayout();
this.jPanelAccionesFormularioDia.setLayout(gridaBagLayoutAccionesFormularioDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsDia.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioDia.add(this.jComboBoxTiposAccionesFormularioDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsDia.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioDia.add(this.jCheckBoxPostAccionNuevoDia, this.gridBagConstraintsDia);
//DEBE CERRARSE Y ACTUALIZARSE TODO NUEVAMENTE, SI ES RELACIONADO PUEDE FUNCIONAR
//if(!this.diaSessionBean.getEstaModoGuardarRelaciones()) {
//SE ARRIESGA
//if(!this.conFuncionalidadRelaciones) {
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsDia.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioDia.add(this.jCheckBoxPostAccionSinCerrarDia, this.gridBagConstraintsDia);
//}
//NO TIENE MENSAJE POR DEFINICION, O ES MUY COMPLEJO LA PANTALLA PARA HACERLO MAS COMPLICADO
if(!this.diaSessionBean.getEsGuardarRelacionado()
){
//&& !this.diaSessionBean.getEstaModoGuardarRelaciones()) {
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsDia.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioDia.add(this.jCheckBoxPostAccionSinMensajeDia, this.gridBagConstraintsDia);
}
int iPosXAccion=0;
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx = iPosXAccion++;
this.jPanelAccionesDia.add(this.jButtonModificarDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx =iPosXAccion++;
this.jPanelAccionesDia.add(this.jButtonEliminarDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx = iPosXAccion++;
this.jPanelAccionesDia.add(this.jButtonActualizarDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx = iPosXAccion++;
this.jPanelAccionesDia.add(this.jButtonGuardarCambiosDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = 0;
this.gridBagConstraintsDia.gridx =iPosXAccion++;
this.jPanelAccionesDia.add(this.jButtonCancelarDia, this.gridBagConstraintsDia);
//this.setJProgressBarToJPanel();
GridBagLayout gridaBagLayoutDia = new GridBagLayout();
this.jContentPane.setLayout(gridaBagLayoutDia);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar() && !this.diaSessionBean.getEsGuardarRelacionado()) {
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyPrincipal++;
this.gridBagConstraintsDia.gridx = 0;
//this.gridBagConstraintsDia.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsDia.anchor = GridBagConstraints.CENTER;//.CENTER;NORTH
this.gridBagConstraintsDia.ipadx = 100;
}
//PROCESANDO EN OTRA PANTALLA
int iGridxBusquedasParametros=0;
//PARAMETROS TABLAS PARAMETROS
if(!this.conCargarMinimo) {
//NO BUSQUEDA
}
//PARAMETROS TABLAS PARAMETROS_FIN
//PARAMETROS REPORTES
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy =iGridyPrincipal++;
this.gridBagConstraintsDia.gridx =0;
this.gridBagConstraintsDia.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsDia.ipady =150;
this.jContentPane.add(this.jScrollPanelDatosDia, this.gridBagConstraintsDia);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
iWidthScroll=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO_RELSCROLL)+(250*0);
iHeightScroll=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO_RELSCROLL);
//if(DiaJInternalFrame.CON_DATOS_FRAME) {
//this.jInternalFrameDetalleDia = new DiaBeanSwingJInternalFrameAdditional();//JInternalFrameBase("Dia DATOS");
this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
//this.setjInternalFrameParent(this);
iHeightFormularioMaximo=(screenSize.height-screenSize.height/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ALTO);
if(iHeightFormulario>iHeightFormularioMaximo) {
iHeightFormulario=iHeightFormularioMaximo;
}
iWidthFormularioMaximo=(screenSize.width-screenSize.width/Constantes.ISWING_RESTOPARTE_DIFERENCIA_ANCHO);
if(iWidthFormulario>iWidthFormularioMaximo) {
iWidthFormulario=iWidthFormularioMaximo;
}
//this.setTitle("[FOR] - Dia DATOS");
this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.usuarioActual,"Dia Formulario",PaginaTipo.FORMULARIO,paginaTipo));
this.setSize(iWidthFormulario,iHeightFormulario);
this.setLocation(xOffset*(openFrameCount + Constantes.INUM_MAX_VENTANAS_DET_X), yOffset*(openFrameCount+Constantes.INUM_MAX_VENTANAS_DET_Y));
this.setResizable(true);
this.setClosable(true);
this.setMaximizable(true);
DiaModel diaModel=new DiaModel(this);
//SI USARA CLASE INTERNA
//DiaModel.DiaFocusTraversalPolicy diaFocusTraversalPolicy = diaModel.new DiaFocusTraversalPolicy(this);
//diaFocusTraversalPolicy.setdiaJInternalFrame(this);
this.setFocusTraversalPolicy(diaModel);
this.jContentPaneDetalleDia = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
int iGridyRelaciones=0;
GridBagLayout gridaBagLayoutDetalleDia = new GridBagLayout();
this.jContentPaneDetalleDia.setLayout(gridaBagLayoutDetalleDia);
GridBagLayout gridaBagLayoutBusquedasParametrosDia = new GridBagLayout();
if(this.parametroGeneralUsuario.getcon_botones_tool_bar()) {
//AGREGA TOOLBAR DETALLE A PANTALLA
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyRelaciones++;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPaneDetalleDia.add(jTtoolBarDetalleDia, gridBagConstraintsDia);
}
this.jScrollPanelDatosEdicionDia= new JScrollPane(jContentPaneDetalleDia,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosEdicionDia.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionDia.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionDia.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralDia= new JScrollPane(jContentPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosGeneralDia.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralDia.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralDia.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyRelaciones++;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPaneDetalleDia.add(jPanelCamposDia, gridBagConstraintsDia);
//if(!this.conCargarMinimo) {
;
//}
this.conMaximoRelaciones=false;
if(this.parametroGeneralUsuario.getcon_cargar_por_parte()) {
}
//CARGA O NO CARGA RELACIONADOS(MAESTRO DETALLE)
// ABAJO VIENE DE PARAMETRO GENERAL USUARIO
if(conMaximoRelaciones) { // && this.conFuncionalidadRelaciones) {
if(!this.conCargarMinimo) {
if(cargarRelaciones
&& diaSessionBean.getConGuardarRelaciones()
) {
if(this.diaSessionBean.getConGuardarRelaciones()) {
this.gridBagConstraintsDia= new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyRelaciones++;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPaneDetalleDia.add(this.jTabbedPaneRelacionesDia, this.gridBagConstraintsDia);
}
//RELACIONES OTROS AGRUPADOS
;
} else {
//this.jButtonNuevoRelacionesDia.setVisible(false);
}
}
}
Boolean tieneColumnasOcultas=false;
if(!Constantes.ISDEVELOPING) {
this.jPanelCamposOcultosDia.setVisible(false);
} else {
if(tieneColumnasOcultas) {
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.fill=GridBagConstraints.NONE;
this.gridBagConstraintsDia.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsDia.gridy = iGridyRelaciones++;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPaneDetalleDia.add(jPanelCamposOcultosDia, gridBagConstraintsDia);
this.jPanelCamposOcultosDia.setVisible(true);
}
}
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyRelaciones++;//1;
this.gridBagConstraintsDia.gridx = 0;
this.gridBagConstraintsDia.anchor = GridBagConstraints.CENTER;//WEST;
this.jContentPaneDetalleDia.add(this.jPanelAccionesFormularioDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyRelaciones;//1;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPaneDetalleDia.add(this.jPanelAccionesDia, this.gridBagConstraintsDia);
//this.setContentPane(jScrollPanelDatosEdicionDia);
//} else {
//DISENO_DETALLE COMENTAR Y
//DISENO_DETALLE(Solo Descomentar Seccion Inferior)
//NOTA-DISENO_DETALLE(Si cambia lo de abajo, cambiar lo comentado, Al final no es lo mismo)
/*
this.jScrollPanelDatosEdicionDia= new JScrollPane(this.jPanelCamposDia,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosEdicionDia.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionDia.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionDia.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyPrincipal++;
this.gridBagConstraintsDia.gridx = 0;
this.gridBagConstraintsDia.fill = GridBagConstraints.BOTH;
this.gridBagConstraintsDia.ipady = this.getSize().height-yOffset*3;
this.gridBagConstraintsDia.anchor = GridBagConstraints.WEST;
this.jContentPane.add(this.jScrollPanelDatosEdicionDia, this.gridBagConstraintsDia);
//ACCIONES FORMULARIO
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy =iGridyPrincipal++;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPane.add(this.jPanelAccionesFormularioDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy =iGridyPrincipal++;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPane.add(this.jPanelAccionesDia, this.gridBagConstraintsDia);
*/
//}
//DISENO_DETALLE-(Descomentar)
/*
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyPrincipal++;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPane.add(this.jPanelCamposDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy = iGridyPrincipal++;
this.gridBagConstraintsDia.gridx = 0;
this.jContentPane.add(this.jPanelCamposOcultosDia, this.gridBagConstraintsDia);
this.gridBagConstraintsDia = new GridBagConstraints();
this.gridBagConstraintsDia.gridy =iGridyPrincipal++;
this.gridBagConstraintsDia.gridx =0;
this.jContentPane.add(this.jPanelAccionesDia, this.gridBagConstraintsDia);
*/
//pack();
//return this.jScrollPanelDatosGeneralDia;//jContentPane;
return jScrollPanelDatosEdicionDia;
}
/*
case "CONTROL_BUSQUEDA":
sKeyName="F3";
case "CONTROL_BUSCAR":
sKeyName="F4";
case "CONTROL_ARBOL":
sKeyName="F5";
case "CONTROL_ACTUALIZAR":
sKeyName="F6";
sKeyName="N";
*/
}
| 40.800367 | 372 | 0.774326 |
d9d0bf5a1dc55811aa8e1c398c7cda2ba7f1889b | 613 | package com.zyqlearnboot.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
String[] beanDefinitionNames1 = run.getBeanDefinitionNames();
for (String name : beanDefinitionNames1) {
//System.out.println(name);
}
}
}
| 34.055556 | 97 | 0.737357 |
81763549249f703e76d621ea696435d774e0f6c0 | 1,430 | package edu.gdei.gdeiassistant.Pojo.Entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
@Scope("prototype")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Card implements Serializable {
//交易时间
private String tradeTime;
//商户名称
private String merchantName;
//交易名称
private String tradeName;
//交易金额
private String tradePrice;
//账户余额
private String accountBalance;
public String getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(String accountBalance) {
this.accountBalance = accountBalance;
}
public String getTradePrice() {
return tradePrice;
}
public void setTradePrice(String tradePrice) {
this.tradePrice = tradePrice;
}
public String getTradeName() {
return tradeName;
}
public void setTradeName(String tradeName) {
this.tradeName = tradeName;
}
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getTradeTime() {
return tradeTime;
}
public void setTradeTime(String tradeTime) {
this.tradeTime = tradeTime;
}
}
| 22 | 61 | 0.688811 |
4eb028c09a2944a096fbf42ce4271aae3e36d4ab | 1,823 | package PinDuoDuo;
import java.math.BigInteger;
import java.util.Scanner;
public class Duo_Duo_De_Dian_Zi_Zi_Dian {
//分治法
public static void main(String[] args){
Scanner input=new Scanner(System.in);
while(input.hasNext()){
int n=input.nextInt();
int m=input.nextInt();
long k=input.nextLong();
BigInteger[][] dp=new BigInteger[51][51];
for(int i=0;i<=n;i++){
for(int j=0;j<=m;j++){
if(i==0){
dp[i][j]=new BigInteger(Integer.toString(j));
}
else if(j==0){
dp[i][j]=new BigInteger(Integer.toString(i));
}
else{
dp[i][j]=dp[i-1][j].add(dp[i][j-1]).add(new BigInteger("2"));
}
}
}
StringBuilder sb=new StringBuilder();
while(k>0){
if(n>0&&m>0){
if(dp[n-1][m].compareTo(new BigInteger(Long.toString(k-1)))>=0){
k--;
sb.append('a');
n--;
}
else{
k-=dp[n-1][m].longValue()+2;
sb.append('b');
m--;
}
}
else if(n>0&&m==0){
n--;
k--;
sb.append('a');
}
else if(n==0&&m>0){
m--;
k--;
sb.append('b');
}
else{
k=0;
}
}
System.out.println(sb.toString());
}
}
}
| 29.403226 | 85 | 0.328031 |
ab1921214f93345b0f6adba3d3a2d9056fcc0794 | 2,684 | package com.qualcomm.ftcrobotcontroller.opmodes.phoenix;
import com.lasarobotics.library.sensor.kauailabs.navx.NavXDevice;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorController;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
/*
*
* LABEL SERVO WIRES IN A COLOR-CODED WAY
*
* */
public class Hardware {
public static final double
LEFT_SERVO_TOP = .15, LEFT_SERVO_BOTTOM = .75, LEFT_SERVO_LOWEST = 0.90,
RIGHT_SERVO_TOP = .90, RIGHT_SERVO_BOTTOM = .35, RIGHT_SERVO_LOWEST = 0.10, //might not work quite right...
CLIMBER_TOP = 0.0, CLIMBER_BOTTOM = 1.0,
STOPPER_ON = .45, STOPPER_OFF = .1,
LEFT_GRABBER_UP = .08, LEFT_GRABBER_DOWN = .9,
RIGHT_GRABBER_UP = 1, RIGHT_GRABBER_DOWN = .2;
public static boolean navxenabled = true;
private final int NAVX_DIM_I2C_PORT = 2;
private final byte NAVX_DEVICE_UPDATE_RATE_HZ = 50;
public DcMotor leftWheel, rightWheel, winch1, winch2, angler;
public Servo climberLeft, climberRight, stopper, climber, leftGrabber, rightGrabber;
public NavXDevice navx;
public Hardware(HardwareMap hardwareMap) {
this.leftWheel = hardwareMap.dcMotor.get("l");
this.leftWheel.setDirection(DcMotor.Direction.REVERSE);
this.rightWheel = hardwareMap.dcMotor.get("r");
this.winch1 = hardwareMap.dcMotor.get("w1");
this.winch1.setDirection(DcMotor.Direction.REVERSE);
this.winch2 = hardwareMap.dcMotor.get("w2");
this.angler = hardwareMap.dcMotor.get("a");
this.angler.setDirection(DcMotor.Direction.REVERSE);
this.climberLeft = hardwareMap.servo.get("6");
this.climberRight = hardwareMap.servo.get("2");
this.stopper = hardwareMap.servo.get("1");
this.climber = hardwareMap.servo.get("3");
this.leftGrabber = hardwareMap.servo.get("5");
this.rightGrabber = hardwareMap.servo.get("4");
this.winch2.setMode(DcMotorController.RunMode.RUN_USING_ENCODERS);
this.angler.setMode(DcMotorController.RunMode.RUN_USING_ENCODERS);
this.rightWheel.setMode(DcMotorController.RunMode.RUN_USING_ENCODERS);
this.climber.setPosition(CLIMBER_BOTTOM);
this.climberRight.setPosition(RIGHT_SERVO_TOP);
this.climberLeft.setPosition(LEFT_SERVO_TOP);
this.leftGrabber.setPosition(LEFT_GRABBER_UP);
this.rightGrabber.setPosition(RIGHT_GRABBER_UP);
this.stopper.setPosition(STOPPER_OFF);
if(navxenabled){
navx = new NavXDevice(hardwareMap, "dim", NAVX_DIM_I2C_PORT);
}
}
}
| 45.491525 | 119 | 0.704545 |
12d318529f934cf9bddda9a0f84e909120b5f307 | 4,646 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.rs.livepreview;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.graphics.SurfaceTexture;
import android.renderscript.Allocation;
import android.renderscript.Matrix3f;
import android.renderscript.RenderScript;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.content.res.Resources;
import android.renderscript.*;
import android.graphics.Bitmap;
public class RsYuv implements TextureView.SurfaceTextureListener
{
private int mHeight;
private int mWidth;
private RenderScript mRS;
private Allocation mAllocationOut;
private Allocation mAllocationIn;
private ScriptC_yuv mScript;
private ScriptIntrinsicYuvToRGB mYuv;
private boolean mHaveSurface;
private SurfaceTexture mSurface;
private ScriptGroup mGroup;
RsYuv(RenderScript rs) {
mRS = rs;
mScript = new ScriptC_yuv(mRS);
mYuv = ScriptIntrinsicYuvToRGB.create(rs, Element.RGBA_8888(mRS));
}
void setupSurface() {
if (mAllocationOut != null) {
mAllocationOut.setSurfaceTexture(mSurface);
}
if (mSurface != null) {
mHaveSurface = true;
} else {
mHaveSurface = false;
}
}
void reset(int width, int height) {
if (mAllocationOut != null) {
mAllocationOut.destroy();
}
android.util.Log.v("cpa", "reset " + width + ", " + height);
mHeight = height;
mWidth = width;
mScript.invoke_setSize(mWidth, mHeight);
Type.Builder tb = new Type.Builder(mRS, Element.RGBA_8888(mRS));
tb.setX(mWidth);
tb.setY(mHeight);
Type t = tb.create();
mAllocationOut = Allocation.createTyped(mRS, t, Allocation.USAGE_SCRIPT |
Allocation.USAGE_IO_OUTPUT);
tb = new Type.Builder(mRS, Element.createPixel(mRS, Element.DataType.UNSIGNED_8, Element.DataKind.PIXEL_YUV));
tb.setX(mWidth);
tb.setY(mHeight);
tb.setYuvFormat(android.graphics.ImageFormat.NV21);
mAllocationIn = Allocation.createTyped(mRS, tb.create(), Allocation.USAGE_SCRIPT);
mYuv.setInput(mAllocationIn);
setupSurface();
ScriptGroup.Builder b = new ScriptGroup.Builder(mRS);
b.addKernel(mScript.getKernelID_root());
b.addKernel(mYuv.getKernelID());
b.addConnection(t, mYuv.getKernelID(), mScript.getKernelID_root());
mGroup = b.create();
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
private long mTiming[] = new long[50];
private int mTimingSlot = 0;
void execute(byte[] yuv) {
mAllocationIn.copyFrom(yuv);
if (mHaveSurface) {
mGroup.setOutput(mScript.getKernelID_root(), mAllocationOut);
mGroup.execute();
//mYuv.forEach(mAllocationOut);
//mScript.forEach_root(mAllocationOut, mAllocationOut);
mAllocationOut.ioSendOutput();
}
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
android.util.Log.v("cpa", "onSurfaceTextureAvailable " + surface);
mSurface = surface;
setupSurface();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
android.util.Log.v("cpa", "onSurfaceTextureSizeChanged " + surface);
mSurface = surface;
setupSurface();
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
android.util.Log.v("cpa", "onSurfaceTextureDestroyed " + surface);
mSurface = surface;
setupSurface();
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
| 30.565789 | 118 | 0.662721 |
6658f7e450929488e8a8a9bd69d1b7008ab40422 | 1,415 | package com.v1as.mytavern.thing.thing.nodes;
import static java.util.Collections.singletonList;
import com.v1as.mytavern.thing.logic.GameContext;
import com.v1as.mytavern.thing.logic.NodeResults;
import com.v1as.mytavern.thing.thing.ThingCharacter;
import com.v1as.mytavern.thing.thing.ThingNode;
import com.v1as.mytavern.thing.thing.ThingNodeLink;
import com.v1as.mytavern.thing.thing.ThingState;
public class FirstNode extends ThingNode {
@Override
public NodeResults<ThingState, ThingCharacter> getRepresentation(GameContext<ThingState, ThingCharacter> ctx) {
ThingState state = ctx.getState();
NodeResults<ThingState, ThingCharacter> nodeResults = new NodeResults<>();
ThingCharacter chr = state.getCharForPlayer(ctx.getPlayer());
StringBuilder text = new StringBuilder()
.append("Приветствуем тебя игрок, сейчас ты ").append(chr.getRoleDescription())
.append(".\n Твоя цель - ");
if (chr.isThing()) {
text.append("заразить всех людей.");
} else if (chr.isInfected()) {
text.append("помочь Нечто заразить всех оставшихся людей.");
} else {
text.append("выяснить кто нечто и сжечь его огнемётом.");
}
nodeResults.setText(text.toString());
nodeResults.setLinks(singletonList(new ThingNodeLink("Поехали!", WaitNode.class)));
return nodeResults;
}
}
| 40.428571 | 115 | 0.699647 |
200ceb82d89b38fba21339d1146672daea0f1ecf | 5,826 | package uk.gov.hmcts.reform.pcqloader.postdeploy;
import com.azure.core.http.rest.PagedIterable;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.models.BlobItem;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ResourceUtils;
import uk.gov.hmcts.reform.pcqloader.PcqLoaderComponent;
import uk.gov.hmcts.reform.pcqloader.config.TestApplicationConfiguration;
import uk.gov.hmcts.reform.pcqloader.services.BlobStorageManager;
import java.io.File;
import java.io.FileNotFoundException;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplicationConfiguration.class)
@ActiveProfiles("functional")
@Slf4j
public class PcqLoaderFunctionalTest extends PcqLoaderTestBase {
private static final String CLASSPATH_BLOBTESTFILES_PATH = "classpath:BlobTestFiles/";
private static final String FUNC_TEST_PCQ_CONTAINER_NAME = "pcq-func-tests";
private static final String FUNC_TEST_PCQ_REJECTED_CONTAINER_NAME = "pcq-func-test-rejected";
private static final String BLOB_FILENAME_1 = "1579002492_31-08-2020-11-35-10.zip";
private static final String BLOB_FILENAME_2 = "1579002493_31-08-2020-11-48-42.zip";
private static final String BLOB_FILENAME_3_LARGE_FILE = "1579002494_27-03-2021-12-30-00.zip";
private static final String BLOB_FILENAME_3_INVALID_DATA = "1579002495_20-05-2021-16-40-00.zip";
private static final String BLOB_FILENAME_3_MISSING_OCR_DATA = "1579002496_01-07-2021-16-45-00.zip";
private static final String BLOB_CONTAINER_DEFAULT_DIR = "/";
private static final String BLOB_CONTAINER_PROCESSED_DIR = "processed/";
private static final int EXPECT_SUCCESSFUL_TESTS = 3;
private static final int EXPECT_REJECTED_TESTS = 2;
private static final int EXPECT_UNPROCESSED_TESTS = 0;
@Autowired
private PcqLoaderComponent pcqLoaderComponent;
@Autowired
private BlobStorageManager blobStorageManager;
@Before
public void beforeTests() throws FileNotFoundException {
log.info("Starting PcqLoaderComponent functional tests");
// Delete test containers if they already exist
if (blobStorageManager.getContainer(FUNC_TEST_PCQ_CONTAINER_NAME).exists()) {
blobStorageManager.deleteContainer(FUNC_TEST_PCQ_CONTAINER_NAME);
}
if (blobStorageManager.getContainer(FUNC_TEST_PCQ_REJECTED_CONTAINER_NAME).exists()) {
blobStorageManager.deleteContainer(FUNC_TEST_PCQ_REJECTED_CONTAINER_NAME);
}
// Create test containers
BlobContainerClient blobContainerClient = blobStorageManager.createContainer(FUNC_TEST_PCQ_CONTAINER_NAME);
blobStorageManager.createContainer(FUNC_TEST_PCQ_REJECTED_CONTAINER_NAME);
log.info("Created test container: {}", blobContainerClient.getBlobContainerUrl());
// Upload sample documents
File blobFile1 = ResourceUtils.getFile(CLASSPATH_BLOBTESTFILES_PATH + BLOB_FILENAME_1);
File blobFile2 = ResourceUtils.getFile(CLASSPATH_BLOBTESTFILES_PATH + BLOB_FILENAME_2);
File blobFile3 = ResourceUtils.getFile(CLASSPATH_BLOBTESTFILES_PATH + BLOB_FILENAME_3_LARGE_FILE);
File blobFile4 = ResourceUtils.getFile(CLASSPATH_BLOBTESTFILES_PATH + BLOB_FILENAME_3_INVALID_DATA);
File blobFile5 = ResourceUtils.getFile(CLASSPATH_BLOBTESTFILES_PATH + BLOB_FILENAME_3_MISSING_OCR_DATA);
blobStorageManager.uploadFileToBlobStorage(blobContainerClient, blobFile1.getPath());
blobStorageManager.uploadFileToBlobStorage(blobContainerClient, blobFile2.getPath());
blobStorageManager.uploadFileToBlobStorage(blobContainerClient, blobFile3.getPath());
blobStorageManager.uploadFileToBlobStorage(blobContainerClient, blobFile4.getPath());
blobStorageManager.uploadFileToBlobStorage(blobContainerClient, blobFile5.getPath());
}
@After
public void afterTests() {
log.info("Stopping PcqLoaderComponent functional tests");
blobStorageManager.deleteContainer(FUNC_TEST_PCQ_CONTAINER_NAME);
blobStorageManager.deleteContainer(FUNC_TEST_PCQ_REJECTED_CONTAINER_NAME);
}
@Test
public void testExecuteMethod() {
//Invoke the executor
pcqLoaderComponent.execute();
//Collect blobs
PagedIterable<BlobItem> totalBlobs =
blobStorageManager.getPcqContainer().listBlobs();
PagedIterable<BlobItem> unprocessedBlobs =
blobStorageManager.getPcqContainer().listBlobsByHierarchy(BLOB_CONTAINER_DEFAULT_DIR);
PagedIterable<BlobItem> processedBlobs =
blobStorageManager.getPcqContainer().listBlobsByHierarchy(BLOB_CONTAINER_PROCESSED_DIR);
PagedIterable<BlobItem> rejectedBlobs =
blobStorageManager.getRejectedPcqContainer().listBlobs();
//Check results
Assertions.assertEquals(EXPECT_SUCCESSFUL_TESTS, countBlobs(totalBlobs),
"Successful number of total blobs");
Assertions.assertEquals(EXPECT_SUCCESSFUL_TESTS, countBlobs(processedBlobs),
"Successful number of processed blobs");
Assertions.assertEquals(EXPECT_UNPROCESSED_TESTS, countBlobs(unprocessedBlobs),
"No blobs should remain");
Assertions.assertEquals(EXPECT_REJECTED_TESTS, countBlobs(rejectedBlobs),
"Number of blobs expected to be rejected");
}
}
| 50.224138 | 115 | 0.763989 |
d480a96ce440c30db4a490b0951784e6df3b622d | 966 | package com.ruoyi.system.mapper;
import java.util.List;
import com.ruoyi.system.domain.HyMeterCase;
/**
* 箱 Mapper接口
*
* @author Administrator
* @date 2021-01-12
*/
public interface HyMeterCaseMapper {
/**
* 查询箱
*
*
* @param id 箱 ID
* @return 箱
*
*/
public HyMeterCase selectHyMeterCaseById(Long id);
/**
* 查询箱 列表
*
* @param hyMeterCase 箱
*
* @return 箱 集合
*/
public List<HyMeterCase> selectHyMeterCaseList(HyMeterCase hyMeterCase);
/**
* 新增箱
*
*
* @param hyMeterCase 箱
*
* @return 结果
*/
public int insertHyMeterCase(HyMeterCase hyMeterCase);
/**
* 修改箱
*
*
* @param hyMeterCase 箱
*
* @return 结果
*/
public int updateHyMeterCase(HyMeterCase hyMeterCase);
/**
* 删除箱
*
*
* @param id 箱 ID
* @return 结果
*/
public int deleteHyMeterCaseById(Long id);
/**
* 批量删除箱
*
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteHyMeterCaseByIds(String[] ids);
}
| 13.8 | 73 | 0.612836 |
450f985d18452d6a6ab18bafd300add80fe4700d | 445 | package com.feilong.gulimall.member.dao;
import com.feilong.gulimall.member.entity.IntegrationChangeHistoryEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 积分变化历史记录
*
* @author Feilong
* @email [email protected]
* @date 2020-11-15 13:39:11
*/
@Mapper
public interface IntegrationChangeHistoryDao extends BaseMapper<IntegrationChangeHistoryEntity> {
}
| 24.722222 | 97 | 0.802247 |
90cbb8a2af4d6d8fcf4f8f0347ce6027e0248f87 | 18,608 | package architecture.community.web.spring.controller.data.secure.mgmt;
import java.io.Serializable;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.support.DatabaseMetaDataCallback;
import org.springframework.jdbc.support.MetaDataAccessException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import architecture.community.exception.NotFoundException;
import architecture.community.query.dao.CustomQueryJdbcDao;
import architecture.community.services.CommunityAdminService;
import architecture.community.services.database.schema.Column;
import architecture.community.services.database.schema.Database;
import architecture.community.services.database.schema.DatabaseFactory;
import architecture.community.services.database.schema.Table;
import architecture.community.web.model.DataSourceRequest;
import architecture.community.web.model.ItemList;
import architecture.community.web.model.Result;
import architecture.community.web.util.ServletUtils;
import architecture.ee.component.editor.DataSourceConfig;
import architecture.ee.component.editor.DataSourceConfigReader;
import architecture.ee.service.ApplicationProperties;
import architecture.ee.service.ConfigService;
import architecture.ee.service.Repository;
import architecture.ee.spring.jdbc.ExtendedJdbcUtils;
import architecture.ee.spring.jdbc.ExtendedJdbcUtils.DB;
import architecture.ee.util.ApplicationConstants;
@Controller("community-mgmt-datasource-secure-data-controller")
@RequestMapping("/data/secure/mgmt")
public class DataSourceDataController {
@Autowired( required = true)
@Qualifier("repository")
private Repository repository;
@Inject
@Qualifier("configService")
private ConfigService configService;
@Inject
@Qualifier("adminService")
private CommunityAdminService adminService;
@Inject
@Qualifier("taskExecutor")
private TaskExecutor taskExecutor;
private Logger logger = LoggerFactory.getLogger(DataSourceDataController.class);
private com.google.common.cache.LoadingCache<String, DataSourceConfig> dataSourceConfigCache = null;
private com.google.common.cache.LoadingCache<String, DatabaseInfo> databaseCache = null;
public DataSourceDataController() { }
/**
* Data Sources API (Mgmt)
******************************************/
private DataSource getDataSource(DataSourceConfig key) {
DataSource dataSource = adminService.getComponent(key.getBeanName(), DataSource.class);
return dataSource;
}
private DataSourceConfigReader getDataSourceConfigReader() {
return new DataSourceConfigReader(repository.getSetupApplicationProperties());
}
private List<DataSourceConfig> listDataSourceConfig(){
List<DataSourceConfig> list = new ArrayList<DataSourceConfig>();
ApplicationProperties config = repository.getSetupApplicationProperties();
Collection<String> names = config.getChildrenNames(ApplicationConstants.DATABASE_PROP_NAME);
DataSourceConfigReader reader = getDataSourceConfigReader();
for( String name : names ) {
try {
list.add( getDataSourceConfigFromCache( name ));
} catch (NotFoundException ignore) { }
}
return list;
}
private DataSourceConfig getDataSourceConfigFromCache(String name) throws NotFoundException {
if( dataSourceConfigCache == null) {
dataSourceConfigCache = CacheBuilder.newBuilder().maximumSize(500).expireAfterAccess(5, TimeUnit.MINUTES).build(
new CacheLoader<String, DataSourceConfig>(){
@Override
public DataSourceConfig load(String name) throws Exception {
DataSourceConfigReader reader = getDataSourceConfigReader();
DataSourceConfig dsc = reader.getDataSoruceConfig(name);
dsc.setActive(adminService.isExists(dsc.getBeanName(), DataSource.class));
return dsc;
}
}
);
}
try {
return dataSourceConfigCache.get(name);
} catch (ExecutionException e) {
throw new NotFoundException(e);
}
}
private DatabaseInfo getDatabaseInfoFromCache(DataSourceConfig key) {
if( databaseCache == null ) {
logger.debug("create cahce." );
databaseCache = CacheBuilder.newBuilder().maximumSize(500).expireAfterAccess(5, TimeUnit.MINUTES).build(
new CacheLoader<String, DatabaseInfo>(){
@Override
public DatabaseInfo load(String key) throws Exception {
logger.debug("# 1. creat new with {}", key );
DataSourceConfig cfg = getDataSourceConfigFromCache( key );
DataSource dataSource = getDataSource( cfg );
DatabaseInfo info = (DatabaseInfo) ExtendedJdbcUtils.extractDatabaseMetaData( dataSource, new DatabaseMetaDataCallback() {
public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
return new DatabaseInfo(dbmd);
}
});
return info;
}
}
);
}
logger.debug("# 0. finding database schema with {}", key.getName() );
DatabaseInfo databaseInfo = databaseCache.getIfPresent(key);
if( databaseInfo == null) {
try {
databaseInfo = databaseCache.get(key.getName());
} catch (Exception e) {
logger.error("error create cache ... {}", e );
}
}
logger.debug( "database from cache {}", databaseInfo );
if( databaseInfo.done.get() == 0)
{
try {
final DatabaseInfo toUse = databaseInfo ;
toUse.done.set(1);
logger.debug("# 2. database with {}", key.getName() );
taskExecutor.execute(new Runnable() {
public void run() {
DataSource dataSource = getDataSource( key );
logger.debug("2.0 using {}", dataSource);
try {
logger.debug("# 2.1 extract database '{}' .....", key.getName());
toUse.database = DatabaseFactory.newDatabase(dataSource.getConnection(), toUse.catalogy, toUse.schema);
toUse.done.set(2);
logger.debug("# 2.2 extract database '{}' done.", key.getName());
} catch (SQLException e) {
toUse.done.set(0);
logger.error(e.getMessage(), e);
}
}});
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
}
return databaseInfo;
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = "/datasoruce/config/names.json", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public ItemList getDataSourceNames( NativeWebRequest request){
ApplicationProperties config = repository.getSetupApplicationProperties();
Collection<String> names = config.getChildrenNames(ApplicationConstants.DATABASE_PROP_NAME);
List<String> list = new ArrayList<String>();
for( String name : names ) {
list.add(name);
}
return new ItemList(list, list.size());
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = "/datasource/config/{name}/get.json", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public DataSourceConfig getDataSourcConfig(@PathVariable String name, NativeWebRequest request){
return getDataSourceConfigReader().getDataSoruceConfig(name);
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = "/datasource/config/list.json", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public List<DataSourceConfig> getDataSourcConfig(NativeWebRequest request){
List<DataSourceConfig> list = listDataSourceConfig();
return list;
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = "/datasource/{name}/get.json", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public DatabaseInfo getDatabaseInfo(@PathVariable String name, NativeWebRequest request) throws NotFoundException{
DataSourceConfig dsc = getDataSourceConfigFromCache(name);
if( adminService.isExists(dsc.getBeanName(), DataSource.class) ) {
DatabaseInfo db = getDatabaseInfoFromCache(dsc);
return db;
}else {
throw new NotFoundException();
}
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = "/datasource/{name}/schema/table/list.json", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public ItemList getDatabaseTables(@PathVariable String name, NativeWebRequest request) throws NotFoundException{
List<TableInfo> list = new ArrayList<TableInfo>();
DataSourceConfig dsc = getDataSourceConfigFromCache(name);
if( adminService.isExists(dsc.getBeanName(), DataSource.class) ) {
DatabaseInfo db = getDatabaseInfoFromCache(dsc);
if( db != null && db.database != null)
{
for(String table : db.database.getTableNames()) {
list.add(new TableInfo( db.database.getTable(table) ) );
}
}
}else {
logger.debug("datasource {} not active yet.", name );
}
ItemList itemList = new ItemList(list, list.size());
return itemList;
}
/**
* Data Sources API (JDBC)
******************************************/
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = { "/datasources" , "/datasources/list.json"}, method = { RequestMethod.GET, RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
public List<DataSourceConfig> getJdbcDataSourcs(NativeWebRequest request){
List<DataSourceConfig> list = listDataSourceConfig();
return list;
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = { "/datasources/{name}/get.json" ,"/datasources/{name}" }, method = { RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
public DataSourceConfig getJdbcDataSource(@PathVariable String name, NativeWebRequest request){
return getDataSourceConfigReader().getDataSoruceConfig(name);
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = { "/datasources/{name}/save-or-update.json" ,"/datasources/{name}" }, method = { RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
public Result saveOrUpdateJdbcDataSource(
@PathVariable String name,
@RequestBody DataSourceConfig config,
NativeWebRequest request){
return Result.newResult();
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = { "/datasources/{name}/database/get.json" , "/datasources/{name}/database" }, method = { RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
public DatabaseInfo getJdbcDataSourceInfo(@PathVariable String name, NativeWebRequest request) throws NotFoundException{
DataSourceConfig dsc = getDataSourceConfigFromCache(name);
if( adminService.isExists(dsc.getBeanName(), DataSource.class) ) {
DatabaseInfo db = getDatabaseInfoFromCache(dsc);
return db;
}else {
throw new NotFoundException();
}
}
/**
* Data Sources API (Schema)
******************************************/
private static final int [] EXCLUDE_DATA_TYPED = { java.sql.Types.BLOB , java.sql.Types.BINARY };
private boolean isAllowed ( Column column ) {
for( int t : EXCLUDE_DATA_TYPED ) {
if( t == column.getType()) {
return false;
}
}
return true;
}
private String queryForCount( Table table ) {
StringBuilder sb = new StringBuilder("SELECT count(*) FROM ").append(table.getName()) ;
return sb.toString();
}
private String queryForSelect( Table table ) {
StringBuilder sb = new StringBuilder("SELECT ");
for( String columnName : table.getColumnNames()) {
Column column = table.getColumn(columnName);
if( isAllowed (column) ) {
sb.append(" ").append(column.getName()).append(",");
}
}
int lastIndex = sb.lastIndexOf(",");
if( lastIndex > 0 ) {
sb.replace(lastIndex , lastIndex + 1, " " );
}
sb.append(" FROM ").append( table.getName() );
return sb.toString();
}
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_SYSTEM", "ROLE_DEVELOPER"})
@RequestMapping(value = "/datasource/{dataSourceName}/schema/table/{tableName}/list.json", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public ItemList getDatabaseTables(
@PathVariable String dataSourceName,
@PathVariable String tableName,
@RequestBody DataSourceRequest dataSourceRequest,
NativeWebRequest request) throws NotFoundException{
DataSourceConfig cfg = getDataSourceConfigFromCache(dataSourceName);
DatabaseInfo db = getDatabaseInfoFromCache(cfg);
Table table = db.database.getTable(tableName);
DataSource dataSource = getDataSource( cfg );
CustomQueryJdbcDao customQueryJdbcDao = adminService.createCustomQueryJdbcDao(dataSource);
int totalCount = customQueryJdbcDao.getExtendedJdbcTemplate().queryForObject(queryForCount(table), Integer.class);
List<Map<String, Object>> list = Collections.EMPTY_LIST;
if( totalCount > 0 ) {
if( dataSourceRequest.getPageSize() > 0 ){
list = customQueryJdbcDao.getExtendedJdbcTemplate().query( queryForSelect(table), dataSourceRequest.getSkip(), dataSourceRequest.getPageSize(), new ColumnMapRowMapper() );
}else {
list = customQueryJdbcDao.getExtendedJdbcTemplate().query( queryForSelect(table), new ColumnMapRowMapper());
}
for( Map<String, Object> row : list ) {
Set<String> keys = row.keySet();
for (String k : keys) {
Object v = row.get(k);
// if( v != null )
// logger.debug( "" + v.getClass().getName() );
if ( v != null && v instanceof java.util.Date) {
row.put( k, ServletUtils.getDataAsISO8601( (java.util.Date) v));
}
}
}
}
ItemList itemList = new ItemList(list, totalCount );
return itemList;
}
public static class DatabaseInfo implements Serializable {
// 0, 1, 2
private AtomicInteger done = new AtomicInteger(0);
private DB type ;
private String databaseProductName ;
private String databaseProductVersion ;
private String driverName ;
private String driverVersion ;
private String schema;
private String catalogy;
private Database database;
public DatabaseInfo(DatabaseMetaData dbmd) {
this.type = DB.UNKNOWN;
this.database = null;
init( dbmd );
}
private void init (DatabaseMetaData dbmd) {
this.schema = null;
this.catalogy = null;
this.type = ExtendedJdbcUtils.extractDB(dbmd);
try {
this.databaseProductName = dbmd.getDatabaseProductName();
this.databaseProductVersion = dbmd.getDatabaseProductVersion();
this.driverName = dbmd.getDriverName();
this.driverVersion = dbmd.getDriverVersion();
if( this.type == DB.ORACLE || this.type == DB.MYSQL ) {
String username = dbmd.getUserName();
if( StringUtils.isNotBlank(username)) {
int endIndex = username.indexOf('@');
if( endIndex > 0 ) {
username = username.substring(0, endIndex);
}
}
this.schema = username;
}
} catch (SQLException ignore) {
ignore.printStackTrace();
}
}
public String getDatabaseProductName() {
return databaseProductName;
}
public String getDatabaseProductVersion() {
return databaseProductVersion;
}
public String getDriverName() {
return driverName;
}
public String getDriverVersion() {
return driverVersion;
}
public String getSchema() {
return schema;
}
public String getCatalogy() {
return catalogy;
}
public boolean isScrollResultsSupported() {
return this.type.isScrollResultsSupported();
}
public boolean isFetchSizeSupported() {
return type.isFetchSizeSupported();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DatabaseInfo [");
if (done != null)
builder.append("done=").append(done).append(", ");
if (type != null)
builder.append("type=").append(type).append(", ");
if (databaseProductName != null)
builder.append("databaseProductName=").append(databaseProductName).append(", ");
if (databaseProductVersion != null)
builder.append("databaseProductVersion=").append(databaseProductVersion).append(", ");
if (driverName != null)
builder.append("driverName=").append(driverName).append(", ");
if (driverVersion != null)
builder.append("driverVersion=").append(driverVersion).append(", ");
if (schema != null)
builder.append("schema=").append(schema).append(", ");
if (catalogy != null)
builder.append("catalogy=").append(catalogy).append(", ");
if (database != null)
builder.append("database=").append(database);
builder.append("]");
return builder.toString();
}
}
public static class TableInfo implements Serializable {
private String name ;
private String catalog ;
private String schema;
private Column primaryKey ;
private List<Column> columns ;
public TableInfo(Table table) {
this.name = table.getName();
this.catalog = table.getCatalog();
this.schema = table.getSchema();
this.primaryKey = table.getPrimaryKey();
this.columns = new ArrayList<Column>();
for( String c : table.getColumnNames()) {
this.columns.add(table.getColumn(c));
}
}
public String getName() {
return name;
}
public String getCatalog() {
return catalog;
}
public String getSchema() {
return schema;
}
public Column getPrimaryKey() {
return primaryKey;
}
public List<Column> getColumns() {
return columns;
}
}
} | 35.853565 | 181 | 0.72184 |
828412ea785375e616a3436e53308b8c04da6a70 | 9,972 | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Objects;
import java.util.Optional;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public final class MainPanel extends JPanel {
private static final String HELP = String.join("\n",
" Start editing: Double-Click",
" Commit rename: field-focusLost, Enter-Key",
"Cancel editing: Esc-Key, title.isEmpty"
);
private MainPanel() {
super(new GridLayout(0, 1, 5, 5));
JScrollPane l1 = new JScrollPane(new JTree());
l1.setBorder(new EditableTitledBorder("JTree 111111111111111", l1));
JScrollPane l2 = new JScrollPane(new JTextArea(HELP));
l2.setBorder(new EditableTitledBorder(null, "JTextArea", TitledBorder.RIGHT, TitledBorder.BOTTOM, l2));
add(l1);
add(l2);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class EditableTitledBorder extends TitledBorder implements MouseListener {
protected final Container glassPane = new EditorGlassPane();
protected final JTextField editor = new JTextField();
protected final JLabel renderer = new JLabel();
protected final Rectangle rect = new Rectangle();
protected Component comp;
protected final Action startEditing = new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
if (comp instanceof JComponent) {
Optional.ofNullable(((JComponent) comp).getRootPane())
.ifPresent(r -> r.setGlassPane(glassPane));
}
glassPane.removeAll();
glassPane.add(editor);
glassPane.setVisible(true);
Point p = SwingUtilities.convertPoint(comp, rect.getLocation(), glassPane);
rect.setLocation(p);
rect.grow(2, 2);
editor.setBounds(rect);
editor.setText(getTitle());
editor.selectAll();
editor.requestFocusInWindow();
}
};
protected final Action cancelEditing = new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
glassPane.setVisible(false);
}
};
protected final Action renameTitle = new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
String str = editor.getText().trim();
if (!str.isEmpty()) {
setTitle(str);
}
glassPane.setVisible(false);
}
};
protected EditableTitledBorder(String title, Component c) {
this(null, title, LEADING, DEFAULT_POSITION, null, null, c);
}
// protected EditableTitledBorder(Border border, Component c) {
// this(border, "", LEADING, DEFAULT_POSITION, null, null, c);
// }
// protected EditableTitledBorder(Border border, String title, Component c) {
// this(border, title, LEADING, DEFAULT_POSITION, null, null, c);
// }
protected EditableTitledBorder(Border border, String title, int justification, int pos, Component c) {
this(border, title, justification, pos, null, null, c);
}
// protected EditableTitledBorder(
// Border border,
// String title,
// int justification,
// int pos,
// Font font,
// Component c) {
// this(border, title, justification, pos, font, null, c);
// }
protected EditableTitledBorder(
Border border,
String title,
int justification,
int pos,
Font font,
Color color,
Component c) {
super(border, title, justification, pos, font, color);
this.comp = c;
comp.addMouseListener(this);
InputMap im = editor.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap am = editor.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "rename-title");
am.put("rename-title", renameTitle);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel-editing");
am.put("cancel-editing", cancelEditing);
}
@Override public boolean isBorderOpaque() {
return true;
}
@Override public void mouseClicked(MouseEvent e) {
boolean isDoubleClick = e.getClickCount() >= 2;
if (isDoubleClick) {
Component src = e.getComponent();
rect.setBounds(getTitleBounds(src));
if (rect.contains(e.getPoint())) {
startEditing.actionPerformed(new ActionEvent(src, ActionEvent.ACTION_PERFORMED, ""));
}
}
}
@Override public void mouseEntered(MouseEvent e) {
/* not needed */
}
@Override public void mouseExited(MouseEvent e) {
/* not needed */
}
@Override public void mousePressed(MouseEvent e) {
/* not needed */
}
@Override public void mouseReleased(MouseEvent e) {
/* not needed */
}
private JLabel getLabel2(Component c) {
renderer.setText(getTitle());
renderer.setFont(getFont(c));
// renderer.setForeground(getColor(c));
renderer.setComponentOrientation(c.getComponentOrientation());
renderer.setEnabled(c.isEnabled());
return renderer;
}
private int getJustification2(Component c) {
int justification = getTitleJustification();
if (justification == LEADING || justification == DEFAULT_JUSTIFICATION) {
return c.getComponentOrientation().isLeftToRight() ? LEFT : RIGHT;
}
if (justification == TRAILING) {
return c.getComponentOrientation().isLeftToRight() ? RIGHT : LEFT;
}
return justification;
}
// @see public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
private Rectangle getTitleBounds(Component c) {
String title = getTitle();
if (Objects.nonNull(title) && !title.isEmpty()) {
Border border = getBorder();
int edge = border instanceof TitledBorder ? 0 : EDGE_SPACING;
Insets i = getBorderInsets(border, c);
JLabel label = getLabel2(c);
Dimension size = label.getPreferredSize();
Rectangle r = new Rectangle(c.getWidth() - i.left - i.right, size.height);
calcLabelPosition(c, edge, i, r);
calcLabelJustification(c, size, i, r);
return r;
}
return new Rectangle();
}
private void calcLabelPosition(Component c, int edge, Insets insets, Rectangle lblR) {
switch (getTitlePosition()) {
case ABOVE_TOP:
insets.left = 0;
insets.right = 0;
break;
case TOP:
insets.top = edge + insets.top / 2 - lblR.height / 2;
if (insets.top >= edge) {
lblR.y += insets.top;
}
break;
case BELOW_TOP:
lblR.y += insets.top + edge;
break;
case ABOVE_BOTTOM:
lblR.y += c.getHeight() - lblR.height - insets.bottom - edge;
break;
case BOTTOM:
lblR.y += c.getHeight() - lblR.height;
insets.bottom = edge + (insets.bottom - lblR.height) / 2;
if (insets.bottom >= edge) {
lblR.y -= insets.bottom;
}
break;
case BELOW_BOTTOM:
insets.left = 0;
insets.right = 0;
lblR.y += c.getHeight() - lblR.height;
break;
default:
break;
}
insets.left += edge + TEXT_INSET_H;
insets.right += edge + TEXT_INSET_H;
}
private void calcLabelJustification(Component c, Dimension size, Insets insets, Rectangle lblR) {
if (lblR.width > size.width) {
lblR.width = size.width;
}
switch (getJustification2(c)) {
case LEFT:
lblR.x += insets.left;
break;
case RIGHT:
lblR.x += c.getWidth() - insets.right - lblR.width;
break;
case CENTER:
lblR.x += (c.getWidth() - lblR.width) / 2;
break;
default:
break;
}
}
// @SuppressWarnings("PMD.AvoidReassigningParameters")
// @see private Insets getBorderInsets(Border border, Component c, Insets insets) {
private static Insets getBorderInsets(Border border, Component c) {
Insets insets = new Insets(0, 0, 0, 0);
if (Objects.isNull(border)) {
insets.set(0, 0, 0, 0);
} else if (border instanceof AbstractBorder) {
AbstractBorder ab = (AbstractBorder) border;
insets = ab.getBorderInsets(c, insets);
} else {
Insets i = border.getBorderInsets(c);
insets.set(i.top, i.left, i.bottom, i.right);
}
return insets;
}
protected JTextField getEditorTextField() {
return editor;
}
private class EditorGlassPane extends JComponent {
protected EditorGlassPane() {
super();
setOpaque(false);
setFocusTraversalPolicy(new DefaultFocusTraversalPolicy() {
@Override public boolean accept(Component c) {
return Objects.equals(c, getEditorTextField());
}
});
addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
if (!getEditorTextField().getBounds().contains(e.getPoint())) {
renameTitle.actionPerformed(new ActionEvent(e.getComponent(), ActionEvent.ACTION_PERFORMED, ""));
}
}
});
}
@Override public void setVisible(boolean flag) {
super.setVisible(flag);
setFocusTraversalPolicyProvider(flag);
setFocusCycleRoot(flag);
}
}
}
| 31.457413 | 125 | 0.655636 |
0128f5c345e289963aba3ea9388700e96fefe756 | 1,592 | package allPay.payment.integration.domain;
/**
* �H�Υd�w���w�B�q��d�ߪ���
* @author mark.chiu
*
*/
public class QueryCreditCardPeriodInfoObj {
/**
* MerchantID
* �|���s��
*/
private String MerchantID = "";
/**
* MerchantTradeNo
* �|������s��
*/
private String MerchantTradeNo = "";
/**
* TimeStamp
* ���Үɶ�
*/
private String TimeStamp = "";
/********************* getters and setters *********************/
/**
* ���oMerchantID �|���s��
* @return MerchantID
*/
public String getMerchantID() {
return MerchantID;
}
/**
* �]�wMerchantID �|���s��
* @param merchantID
*/
public void setMerchantID(String merchantID) {
MerchantID = merchantID;
}
/**
* ���oMerchantTradeNo �|������s���A�q�沣�ͮɶǰe��O��Pay���|������s���C
* @return MerchantTradeNo
*/
public String getMerchantTradeNo() {
return MerchantTradeNo;
}
/**
* �]�wMerchantTradeNo �|������s���A�q�沣�ͮɶǰe��O��Pay���|������s���C
* @param merchantTradeNo
*/
public void setMerchantTradeNo(String merchantTradeNo) {
MerchantTradeNo = merchantTradeNo;
}
/**
* ���oTimeStamp ���Үɶ�
* @return TimeStamp
*/
public String getTimeStamp() {
return TimeStamp;
}
/**
* �]�wTimeStamp ���Үɶ�
* @param timeStamp
*/
public void setTimeStamp(String timeStamp) {
TimeStamp = timeStamp;
}
@Override
public String toString() {
return "QueryCreditCardPeriodInfoObj [MerchantID=" + MerchantID + ", MerchantTradeNo=" + MerchantTradeNo
+ ", TimeStamp=" + TimeStamp + "]";
}
}
| 20.410256 | 107 | 0.557789 |
d503dde7f72c3dbc47a5f0e0abbfd6da56b57ca7 | 4,501 | package seraphaestus.factoriores.block;
import java.util.Random;
import java.util.function.ToIntFunction;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.ForgeHooks;
import seraphaestus.factoriores.ConfigHandler;
import seraphaestus.factoriores.tile.TileEntityBurnerMiner;
public class BlockBurnerMiner extends BlockMiner {
public static final BooleanProperty LIT = BlockStateProperties.LIT;
public BlockBurnerMiner(Properties properties) {
super(properties.luminance(createLightLevelFromBlockState(13)));
this.setDefaultState(this.stateContainer.getBaseState()
.with(ENABLED, false)
.with(LIT, false));
}
// -------- TileEntity stuff
@Override
public TileEntity createNewTileEntity(IBlockReader reader) {
return new TileEntityBurnerMiner();
}
// -------- State/Property management
@Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
builder.add(ENABLED, LIT);
}
private static ToIntFunction<BlockState> createLightLevelFromBlockState(int level) {
return (state) -> {
return state.get(BlockStateProperties.LIT) ? level : 0;
};
}
// -------- Events
@Override
public ActionResultType onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) {
boolean isHandFull = !player.getHeldItem(hand).isEmpty();
// on client side, don't do anything
if (world.isRemote) return isHandFull ? ActionResultType.PASS : ActionResultType.SUCCESS;
TileEntity tileentity = world.getTileEntity(pos);
if (tileentity instanceof TileEntityBurnerMiner) {
TileEntityBurnerMiner tileEntityMiner = (TileEntityBurnerMiner) tileentity;
ItemStack heldItem = player.getHeldItem(hand);
if (ForgeHooks.getBurnTime(heldItem) > 0) {
// add fuel to the miner
boolean success = tileEntityMiner.addFuel(new ItemStack(heldItem.getItem(), 1));
if (success && !player.abilities.isCreativeMode) heldItem.shrink(1);
} else {
if (isHandFull) return ActionResultType.PASS;
// retrieve products from the miner
player.addItemStackToInventory(tileEntityMiner.retrieveItems());
}
}
return ActionResultType.SUCCESS;
}
// -------- Client-side effects
@OnlyIn(Dist.CLIENT)
@Override
public void animateTick(BlockState state, World world, BlockPos pos, Random rnd) {
if (state.get(LIT)) {
double d0 = (double) pos.getX() + 0.5D;
double d1 = (double) pos.getY();
double d2 = (double) pos.getZ() + 0.5D;
if (rnd.nextDouble() < 0.1D && !ConfigHandler.COMMON.silentMiners.get()) {
world.playSound(d0, d1, d2, SoundEvents.BLOCK_FURNACE_FIRE_CRACKLE, SoundCategory.BLOCKS, 1.0F, 1.0F, false);
}
if (rnd.nextDouble() < ConfigHandler.CLIENT.furnaceParticleFrequency.get()) {
for (Direction direction : Direction.values()) {
if (direction == Direction.UP || direction == Direction.DOWN) continue;
Direction.Axis direction$axis = direction.getAxis();
//double d3 = 0.52D;
double d4 = rnd.nextDouble() * 0.6D - 0.3D;
double d5 = direction$axis == Direction.Axis.X ? (double) direction.getXOffset() * 0.52D : d4;
double d6 = (rnd.nextDouble() * 6.0D + 2.0D) / 16.0D;
double d7 = direction$axis == Direction.Axis.Z ? (double) direction.getZOffset() * 0.52D : d4;
world.addParticle(ParticleTypes.SMOKE, d0 + d5, d1 + d6, d2 + d7, 0.0D, 0.0D, 0.0D);
world.addParticle(ParticleTypes.FLAME, d0 + d5, d1 + d6, d2 + d7, 0.0D, 0.0D, 0.0D);
}
}
}
super.animateTick(state, world, pos, rnd);
}
}
| 37.198347 | 146 | 0.720507 |
f2ed856b8473824a00ca784b0bbec546c673a21b | 512 | package com.keimons.platform.executor;
/**
* 任务执行策略
*
* @author monkey1993
* @version 1.0
* @since 1.8
**/
public abstract class BaseExecutorStrategy implements IExecutorStrategy {
/**
* 策略名称
*/
protected final String name;
/**
* 线程数量
*/
protected final int nThreads;
public BaseExecutorStrategy(String name, int nThreads) {
this.name = name;
this.nThreads = nThreads;
}
@Override
public String getName() {
return name;
}
@Override
public int size() {
return nThreads;
}
} | 14.222222 | 73 | 0.673828 |
b53a2d5e7bdb819a98e8cbbad934efe62d002dca | 945 | package at.dse.g14.entity;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.persistence.Entity;
import java.time.LocalDateTime;
/**
* An entity which represents a notification, by providing the necessary information.
*
* @author Michael Sober
* @since 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
public abstract class Notification implements at.dse.g14.entity.Entity<Long> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String receiver;
private LocalDateTime date;
public Notification(Long id, String receiver) {
this.id = id;
this.receiver = receiver;
this.date = LocalDateTime.now();
}
}
| 23.04878 | 85 | 0.767196 |
582198c2af3485e096f807182fac1d2a82120c48 | 404 | package jobapp.controller;
import org.noear.solon.extend.cron4j.Cron4j;
import java.util.Date;
@Cron4j(cron5x = "2s", name = "job1")
public class Cron4jRun1 implements Runnable {
@Override
public void run() {
System.out.println("我是定时任务: Cron4jRun1(2s) -- " + new Date().toString());
//throw new RuntimeException("异常");
System.out.println("如果间隔太长,我可能被配置给控制了");
}
}
| 23.764706 | 81 | 0.660891 |
03ca7ea541d815f32474545d35ca81dc83cf0983 | 7,035 | package com.sap.cloud.samples.ariba.discovery.rfx.api;
import java.io.IOException;
import java.text.MessageFormat;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sap.cloud.samples.ariba.discovery.rfx.dtos.EventsDto;
/**
* Facade for Ariba Discovery RFX Publication to External Marketplace API.
*
*/
public class PublicSourcingApiFacade {
private static final String RETRIEVE_EVENTS_PATH = "/site/{0}/events/?rsqlfilter=(count=={1})";
private static final String ACKNOWLEDGE_EVENTS_PATH = "/action/site/{0}/events/{1}/acknowledge";
private static final String DEBUG_ACKNOWLEDGING_EVENT_MESSAGE = "Acknowledging event [{}]...";
private static final String DEBUG_EVENT_ACKNOWLEDGED_MESSAGE = "Acknowledging event [{}] done.";
private static final String DEBUG_RETRIEVING_EVENTS_MESSAGE = "Retrieving [{}] events...";
private static final String DEBUG_EVENTS_RETRIEVED_MESSAGE = "Events retrieved: [{}]";
private static final String DEBUG_CALLING_MESSAGE = "Calling [{}]...";
private static final String DEBUG_CALLING_URI_RETURNED_STATUS_MESSAGE = "Calling [{}] returned status: {}";
private static final String ERROR_PROBLEM_OCCURED_WHILE_CALLING_MESSAGE = "Problem occured while calling [{0}].";
private static final int DEFAULT_NUMBER_OF_EVENTS_REQUESTED = 10;
private final String siteId;
private final OpenApisEndpoint openApisEndpoint;
private static final Logger logger = LoggerFactory.getLogger(PublicSourcingApiFacade.class);
/**
* Constructor used for production environment.
*
* @param aribaOpenApisEnvironmentUrl
* the URL of the Ariba OpenAPIs environment to be called.
* @param proxyType
* the proxy type.
* @param siteId
* the site ID.
* @param serviceProviderUser
* the service provider user.
* @param serviceProviderPassword
* the service provider password.
* @param apiKey
* API key to be used for the API calls.
*/
public PublicSourcingApiFacade(String aribaOpenApisEnvironmentUrl, String proxyType, String siteId,
String serviceProviderUser, String serviceProviderPassword, String apiKey) {
this.siteId = siteId;
this.openApisEndpoint = new OpenApisEndpoint(aribaOpenApisEnvironmentUrl, proxyType, serviceProviderUser,
serviceProviderPassword, apiKey);
}
/**
* Constructor used for sandbox environment.
*
* @param aribaOpenApisEnvironmentUrl
* the URL of the Ariba OpenAPIs environment to be called.
* @param proxyType
* the proxy type.
* @param siteId
* the site ID.
* @param apiKey
* API key to be used for the API calls.
*/
public PublicSourcingApiFacade(String aribaOpenApisEnvironmentUrl, String proxyType, String siteId, String apiKey) {
this.siteId = siteId;
this.openApisEndpoint = new OpenApisEndpoint(aribaOpenApisEnvironmentUrl, proxyType, apiKey);
}
/**
* Retrieve {@value #DEFAULT_NUMBER_OF_EVENTS_REQUESTED} events.
*
* @return the {@value #DEFAULT_NUMBER_OF_EVENTS_REQUESTED} most recent
* events from the Extension Queue or null in case of no events.
*
* @throws UnsuccessfulOperationException
* when retrieving the events was not successful.
*/
public EventsDto retrieveEvents() throws UnsuccessfulOperationException {
return retrieveEvents(DEFAULT_NUMBER_OF_EVENTS_REQUESTED);
}
/**
* Retrieves the "count" most recent events from Extension Queue.
*
* @param count
* the number of events to be retrieved from the Extension Queue.
* @return the "count" most recent events from the Extension Queue or null
* in case of no events.
* @throws UnsuccessfulOperationException
* when retrieving the events was not successful.
*/
public EventsDto retrieveEvents(int count) throws UnsuccessfulOperationException {
logger.debug(DEBUG_RETRIEVING_EVENTS_MESSAGE, count);
EventsDto result = null;
String retrieveEventsPath = MessageFormat.format(RETRIEVE_EVENTS_PATH, siteId, count);
logger.debug(DEBUG_CALLING_MESSAGE, retrieveEventsPath);
try (CloseableHttpResponse retrieveEventsResponse = openApisEndpoint.executeHttpGet(retrieveEventsPath)) {
int retrieveEventsResponseStatusCode = HttpResponseUtils.validateHttpStatusResponse(retrieveEventsResponse,
HttpStatus.SC_OK, HttpStatus.SC_NO_CONTENT);
logger.debug(DEBUG_CALLING_URI_RETURNED_STATUS_MESSAGE, retrieveEventsPath,
retrieveEventsResponseStatusCode);
if (retrieveEventsResponseStatusCode == HttpStatus.SC_OK) {
HttpEntity retrieveEventsResponseEntity = retrieveEventsResponse.getEntity();
if (retrieveEventsResponseEntity != null) {
try {
result = HttpResponseUtils.convertHttpResponse(retrieveEventsResponseEntity, EventsDto.class);
} finally {
EntityUtils.consume(retrieveEventsResponseEntity);
}
}
}
} catch (IOException | HttpResponseException e) {
String errorMessage = MessageFormat.format(ERROR_PROBLEM_OCCURED_WHILE_CALLING_MESSAGE, retrieveEventsPath);
logger.error(errorMessage);
throw new UnsuccessfulOperationException(errorMessage, e);
}
logger.debug(DEBUG_EVENTS_RETRIEVED_MESSAGE, result);
return result;
}
/**
* Acknowledges event. Acknowledged event is not returned in subsequent Get
* Event calls. Subsequent API calls for the event, such as Post Document
* Update and Resume, will not work until Acknowledge has been called.
*
* @param eventId
* event id to be acknowledged.
* @throws UnsuccessfulOperationException
* when acknowledge fails. when there is a problem with the HTTP
* request.
*/
public void acknowledgeEvent(String eventId) throws UnsuccessfulOperationException {
logger.debug(DEBUG_ACKNOWLEDGING_EVENT_MESSAGE, eventId);
String acknowledgeEventUrl = MessageFormat.format(ACKNOWLEDGE_EVENTS_PATH, siteId, eventId);
logger.debug(DEBUG_CALLING_MESSAGE, acknowledgeEventUrl);
try (CloseableHttpResponse acknowledgeEventResponse = openApisEndpoint.executeHttpPost(acknowledgeEventUrl)) {
int acknowledgeEventsResponseStatusCode = HttpResponseUtils
.validateHttpStatusResponse(acknowledgeEventResponse, HttpStatus.SC_OK);
logger.debug(DEBUG_CALLING_URI_RETURNED_STATUS_MESSAGE, acknowledgeEventUrl,
acknowledgeEventsResponseStatusCode);
} catch (IOException | HttpResponseException e) {
String errorMessage = MessageFormat.format(ERROR_PROBLEM_OCCURED_WHILE_CALLING_MESSAGE,
acknowledgeEventUrl);
logger.error(errorMessage);
throw new UnsuccessfulOperationException(errorMessage, e);
}
logger.debug(DEBUG_EVENT_ACKNOWLEDGED_MESSAGE, eventId);
}
}
| 40.66474 | 118 | 0.742004 |
8c02a38d120000e434915e1d080855534b405e8d | 4,954 | package com.runtimeverification.rvmonitor.java.rt;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
/**
* A singleton class to record violations of properties and where they happen.
* @author A. Cody Schuffelen
*/
public class ViolationRecorder {
private final HashMap<String, HashMap<List<StackTraceElement>, Integer>> occurrences;
/**
* Private constructor to make it a singleton.
*/
private ViolationRecorder() {
occurrences = new HashMap<String, HashMap<List<StackTraceElement>, Integer>>();
}
private static final ViolationRecorder instance = new ViolationRecorder();
/**
* Retrieve the singleton instance.
* @return The one ViolationRecorder instance.
*/
public static final ViolationRecorder get() {
return instance;
}
/**
* Retrieve the current stack frames.
* @return An array of stack frames.
*/
private static StackTraceElement[] getStack() {
return new Exception().getStackTrace();
}
/**
* Retrieve the relevant parts of the current stack frames.
* @return A list of stack frames.
*/
private static List<StackTraceElement> getRelevantStack() {
return makeRelevantList(getStack());
}
/**
* Retrieve the current line of code in the monitored program.
* @return A string of the current line of code.
*/
public static String getLineOfCode() {
final List<StackTraceElement> relevantStack = getRelevantStack();
if(relevantStack.size() > 0) {
return relevantStack.get(0).toString();
} else {
return "(Unknown)";
}
}
/**
* Record a violation.
* @param name The name of the property that was violated.
* @param stack The stack trace at time of violation.
*/
public void record(String name) {
final List<StackTraceElement> relevantList = getRelevantStack();
if(!occurrences.containsKey(name)) {
occurrences.put(name, new HashMap<List<StackTraceElement>, Integer>());
}
final HashMap<List<StackTraceElement>, Integer> violations = occurrences.get(name);
if(!violations.containsKey(relevantList)) {
violations.put(relevantList, new Integer(1));
} else {
violations.put(relevantList, new Integer(violations.get(relevantList).intValue()
+ 1));
}
}
/**
* Filter out the javamop and rv-monitor classes from the stack trace, as they are
* not relevant to the property.
* @param elements The stack trace at time of violation.
* @return The relevant parts of the stack trace at time of violation.
*/
private static List<StackTraceElement> makeRelevantList(StackTraceElement[] elements) {
final ArrayList<StackTraceElement> relevantList = new ArrayList<StackTraceElement>();
for(int i = 0; i < elements.length; i++) {
final String fileName = elements[i].getFileName();
final String className = elements[i].getClassName();
if(className.startsWith("com.runtimeverification.rvmonitor.") ||
className.startsWith("javamop.") || fileName.contains(".aj") ||
className.startsWith("mop.") || className.startsWith("rvm.")) {
} else {
relevantList.add(elements[i]);
}
}
return relevantList;
}
/**
* Produce a minimal summary of the properties violated, and how often they were violated.
* @return A shorter string with the violated properties and counts.
*/
public String toStringMinimal() {
final StringBuilder ret = new StringBuilder();
for(Map.Entry<String, HashMap<List<StackTraceElement>, Integer>> type :
occurrences.entrySet()) {
int total = 0;
for(Integer count : type.getValue().values()) {
total += count.intValue();
}
ret.append(type.getKey()).append(": ").append(total).append("\n");
}
return ret.toString();
}
/**
* Verbose output of violated properties. Has more detailed stack trace output on where
* properties are violated.
* @return A long string with violated properties and stack traces.
*/
@Override
public String toString() {
final StringBuilder ret = new StringBuilder();
for(Map.Entry<String, HashMap<List<StackTraceElement>, Integer>> type :
occurrences.entrySet()) {
for(Map.Entry<List<StackTraceElement>, Integer> traces : type.getValue().entrySet()) {
ret.append(type.getKey()).append(": ").append(traces.getValue()).append("\n");
ret.append(traces.getKey()).append("\n");
}
}
return ret.toString();
}
} | 36.426471 | 98 | 0.615664 |
2c8b89fb021e31ca1cceb36e86d6cf444611b188 | 1,417 | package com.lls.comics.exception;
/************************************
* ComicsResponseException
* @author liliangshan
* @date 2019/1/8
************************************/
public class ComicsResponseException extends ComicsException {
private static final long serialVersionUID = 90448836938089400L;
public ComicsResponseException() {
super(ComicsExceptionConstants.SERVICE_RESPONSE_ERROR);
}
public ComicsResponseException(ComicsExceptionMessage exceptionMessage) {
super(exceptionMessage);
}
public ComicsResponseException(String message) {
super(message, ComicsExceptionConstants.SERVICE_RESPONSE_ERROR);
}
public ComicsResponseException(String message, ComicsExceptionMessage exceptionMessage) {
super(message, exceptionMessage);
}
public ComicsResponseException(String message, Throwable cause) {
super(message, cause, ComicsExceptionConstants.SERVICE_RESPONSE_ERROR);
}
public ComicsResponseException(String message, Throwable cause, ComicsExceptionMessage exceptionMessage) {
super(message, cause, exceptionMessage);
}
public ComicsResponseException(Throwable cause) {
super(cause, ComicsExceptionConstants.SERVICE_RESPONSE_ERROR);
}
public ComicsResponseException(Throwable cause, ComicsExceptionMessage exceptionMessage) {
super(cause, exceptionMessage);
}
}
| 32.204545 | 110 | 0.718419 |
cd924ad83a95af7187046e573c27e3dd17ae914c | 1,897 | package com.kurdi.utils;
import org.apache.commons.codec.binary.Base64;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* Created by kudrjavtsev on 09/11/16.
*/
public class GeneralUtils {
public static String getByteArrayToPrintFormat(List<byte[]> values) {
StringBuilder stringBuilder = new StringBuilder();
for (byte[] value : values) {
stringBuilder.append("<return>").append(Base64.encodeBase64String(value))
.append("</return>");
}
return stringBuilder.toString();
}
public static String getDateInFormat(LocalDateTime dateTime) {
return dateTime.format(DateTimeFormatter.ofPattern("dd_MM_yyyy"));
}
public static boolean checkFileExistence(String filePath) {
try {
if (filePath != null && filePath.length() > 0 && Files.exists(Paths.get(filePath))) {
return true;
}
} catch (Exception ex) {
return false;
}
return false;
}
public static byte[] arrayReverse(byte[] arrayOriginal) {
byte [] arrayReversed = arrayOriginal;
for(int i = 0; i < arrayReversed.length / 2; i++)
{
byte temp = arrayReversed[i];
arrayReversed[i] = arrayReversed[arrayReversed.length - i - 1];
arrayReversed[arrayReversed.length - i - 1] = temp;
}
return arrayReversed;
}
public static String defineRemovableDevice(String filePath) {
if (filePath.length()<3){
throw new RuntimeException("File path cannot be shorter than 3 symbols");
}
StringBuilder stringBuilder = new StringBuilder().append(filePath.charAt(0)).append(filePath.charAt(1));
return stringBuilder.toString();
}
}
| 29.640625 | 112 | 0.628361 |
3e032713782bf8bc3bc6198976f3ed991ff043e4 | 1,148 | package cn.zhuhongqing.utils.loader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import cn.zhuhongqing.exception.UtilsException;
import cn.zhuhongqing.utils.StringPool;
/**
* Load reource from jar which is under the WEB-INF/lib.(Suppose this jar is
* inside your WEB-INF/lib)
*
* @author HongQing.Zhu
*
*/
public class WebResourceLoader implements ResourceLoader {
static String root;
static {
try {
String path = ClassLoader.getSystemClassLoader()
.getResource(StringPool.EMPTY).toURI().getPath();
root = new File(path).getParentFile().getParentFile()
.getCanonicalPath();
root = root == null ? StringPool.EMPTY : root;
} catch (IOException | URISyntaxException e) {
throw new UtilsException(e);
}
}
public File loadAsFile(String path) {
return new File(root, path);
}
public InputStream loaderAsStream(String path) {
try {
return new FileInputStream(loadAsFile(path));
} catch (FileNotFoundException e) {
throw new UtilsException(e);
}
}
}
| 22.509804 | 76 | 0.730836 |
af8608788421cbfe6785f580fc941a417350105d | 928 | package io.walkers.planes.pandora.jvm.book;
/**
* 10.3 语法糖
* @get 1. 包装类的“==”运算在遇到算术运算的情况下会自动拆箱
* @get 2. 包装类 equals() 方法不处理数据转型的关系
* @author Planeswalker23
* @date Created in 2020/4/7
*/
public class Chapter10No3PrimitiveTypeEqualsDemo {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer c = 3;
Integer d = 3;
Integer e = 321;
Integer f = 321;
Long g = 3L;
// 常量池对象
System.out.println(c==d);
// Integer 常量池缓存对象 -128~127
System.out.println(e==f);
// 包装类的“==”运算在遇到算术运算的情况下会自动拆箱
System.out.println(c==(a+b));
// 包装类 equals() 方法不处理数据转型的关系,即首先判断是否属于本类型
System.out.println(c.equals(a+b));
// 包装类的“==”运算在遇到算术运算的情况下会自动拆箱
System.out.println(g==(a+b));
// 包装类 equals() 方法不处理数据转型的关系,即首先判断是否属于本类型
System.out.println(g.equals(a+b));
}
}
| 23.2 | 50 | 0.573276 |
80b09d5f3c547aa2836ed2897f634d246bd309af | 5,391 | /*******************************************************************************
* Copyright (c) 2011 GigaSpaces Technologies Ltd. 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.cloudifysource.shell.commands;
import java.util.concurrent.TimeUnit;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.cloudifysource.shell.AdminFacade;
import org.cloudifysource.shell.Constants;
import org.cloudifysource.shell.exceptions.CLIException;
import org.cloudifysource.shell.installer.CLILocalhostBootstrapperListener;
import org.cloudifysource.shell.installer.LocalhostGridAgentBootstrapper;
/**
* @author rafi, barakm
* @since 2.0.0
*
* Starts Cloudify Agent with the specified zone.
*
* Required arguments: zone - The agent zone that specifies the name of the service that can run on the machine
*
* Optional arguments: lookup-groups - A unique name that is used to group together Cloudify components. Override
* in order to group together cloudify managements/agents on a network that supports multicast. nic-address - The
* ip address of the local host network card. Specify when local machine has more than one network adapter, and a
* specific network card should be used for network communication. timeout - The number of minutes to wait until
* the operation is completed (default: 5 minutes) lookup-locators - A list of IP addresses used to identify all
* management machines. Override when using a network without multicast support (Default: null). auto-shutdown -
* etermines if undeploying or scaling-in the last service instance on the machine also triggers agent shutdown
* (default: false).
*
* Command syntax: start-agent -zone zone [-lookup-groups lookup-groups] [-nicAddress nicAddress] [-timeout
* timeout] [-lookup-locators lookup-locators]
*/
@Command(scope = "cloudify", name = "start-agent", description = "For internal use only! Starts Cloudify Agent with "
+ "the specified zone. The agent communicates with other agent and management machines.")
public class StartAgent extends AbstractGSCommand {
private static final int DEFAULT_POLLING_INTERVAL = 10;
private static final int DEFAULT_TIMEOUT_MINUTES = 5;
@Option(required = false, name = "-lookup-groups", description = "A unique name that is used to group together"
+ " different Cloudify machines. Default is based on the product version. Override in order to group"
+ " together cloudify managements/agents on a network that supports multicast.")
private String lookupGroups = null;
@Option(required = false, name = "-lookup-locators", description = "A list of ip addresses used to identify all"
+ " management machines. Default is null. Override when using a network without multicast.")
private String lookupLocators = null;
@Option(required = false, name = "-nic-address", description = "The ip address of the local host network card."
+ " Specify when local machine has more than one network adapter, and a specific network card should be"
+ " used for network communication.")
private String nicAddress;
@Option(required = false, name = "-timeout", description = "The number of minutes to wait until the operation is"
+ " done. By default waits 5 minutes.")
private int timeoutInMinutes = DEFAULT_TIMEOUT_MINUTES;
/**
* {@inheritDoc}
*/
@Override
protected Object doExecute()
throws Exception {
if (getTimeoutInMinutes() < 0) {
throw new CLIException("-timeout cannot be negative");
}
final LocalhostGridAgentBootstrapper installer = new LocalhostGridAgentBootstrapper();
installer.setVerbose(verbose);
installer.setLookupGroups(getLookupGroups());
installer.setLookupLocators(getLookupLocators());
installer.setNicAddress(nicAddress);
installer.setProgressInSeconds(DEFAULT_POLLING_INTERVAL);
installer.setAdminFacade((AdminFacade) session.get(Constants.ADMIN_FACADE));
installer.addListener(new CLILocalhostBootstrapperListener());
installer.startAgentOnLocalhostAndWait("", "", getTimeoutInMinutes(),
TimeUnit.MINUTES);
return "Agent started succesfully. Use the shutdown-agent command to shutdown agent running on local machine.";
}
public int getTimeoutInMinutes() {
return timeoutInMinutes;
}
public void setTimeoutInMinutes(final int timeoutInMinutes) {
this.timeoutInMinutes = timeoutInMinutes;
}
public String getLookupGroups() {
return lookupGroups;
}
public void setLookupGroups(final String lookupGroups) {
this.lookupGroups = lookupGroups;
}
public String getLookupLocators() {
return lookupLocators;
}
public void setLookupLocators(final String lookupLocators) {
this.lookupLocators = lookupLocators;
}
} | 44.553719 | 120 | 0.734929 |
08d6019514853bc61971033c1c65bce6cb763d1d | 2,238 | package io.github.riesenpilz.nmsUtilities.packet.playOut;
import org.apache.commons.lang.Validate;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import io.github.riesenpilz.nmsUtilities.packet.PacketUtils;
import io.github.riesenpilz.nmsUtilities.reflections.Field;
import net.minecraft.server.v1_16_R3.Item;
import net.minecraft.server.v1_16_R3.Packet;
import net.minecraft.server.v1_16_R3.PacketListenerPlayOut;
import net.minecraft.server.v1_16_R3.PacketPlayOutSetCooldown;
/**
* https://wiki.vg/Protocol#Set_Cooldown
* <p>
* Applies a cooldown period to all items with the given type. Used by the
* Notchian server with enderpearls. This packet should be sent when the
* cooldown starts and also when the cooldown ends (to compensate for lag),
* although the client will end the cooldown automatically. Can be applied to
* any item, note that interactions still get sent to the server with the item
* but the client does not play the animation nor attempt to predict results
* (i.e block placing).
* <p>
* Packet ID: 0x16<br>
* State: Play<br>
* Bound To: Client
*
* @author Martin
*
*/
public class PacketPlayOutSetCooldownEvent extends PacketPlayOutEvent {
private Material material;
/**
* Number of ticks to apply a cooldown for, or 0 to clear the cooldown.
*/
private int cooldown;
public PacketPlayOutSetCooldownEvent(Player injectedPlayer, PacketPlayOutSetCooldown packet) {
super(injectedPlayer);
Validate.notNull(packet);
material = PacketUtils.toMaterial(Field.get(packet, "a", Item.class));
cooldown = Field.get(packet, "b", int.class);
}
public PacketPlayOutSetCooldownEvent(Player injectedPlayer, Material material, int cooldown) {
super(injectedPlayer);
Validate.notNull(material);
this.material = material;
this.cooldown = cooldown;
}
public Material getMaterial() {
return material;
}
public int getCooldown() {
return cooldown;
}
@Override
public Packet<PacketListenerPlayOut> getNMS() {
return new PacketPlayOutSetCooldown(PacketUtils.toItem(material), cooldown);
}
@Override
public int getPacketID() {
return 0x16;
}
@Override
public String getProtocolURLString() {
return "https://wiki.vg/Protocol#Set_Cooldown";
}
}
| 27.292683 | 95 | 0.763628 |
f6061a3bf7ce80e1e5d88aa181f844377ece30ed | 544 | /* */ package src.jojobadv.Entities.Stands;
/* */
/* */ import net.minecraft.world.World;
/* */
/* */
/* */
/* */ public class EntityOutBomb
/* */ extends EntityBomb
/* */ {
/* */ public EntityOutBomb(World par1World) {
/* 11 */ super(par1World);
/* 12 */ setSize(0.1F, 0.1F);
/* */ }
/* */ }
/* Location: /Volumes/NO NAME/JojoBAdv-0.2.4-1.7.10-deobf.jar!/src/jojobadv/Entities/Stands/EntityOutBomb.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.0.2
*/ | 27.2 | 124 | 0.534926 |
4a0cf8912c3b67decf902d6a39f62165add95c49 | 2,235 | package com.jspxcms.common.orm;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaEntityInformationSupport;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
/**
* Simple JPA Repository
*
* @author liufang
*
* @param <T>
* @param <ID>
*/
public class MySimpleJpaRepository<T, ID extends Serializable> extends
SimpleJpaRepository<T, ID> implements MyJpaRepository<T, ID>,
MyJpaSpecificationExecutor<T> {
private final EntityManager em;
public MySimpleJpaRepository(JpaEntityInformation<T, ?> entityInformation,
EntityManager entityManager) {
super(entityInformation, entityManager);
this.em = entityManager;
}
public MySimpleJpaRepository(Class<T> domainClass, EntityManager em) {
// this(JpaEntityInformationSupport.getMetadata(domainClass, em), em);
this(JpaEntityInformationSupport.getEntityInformation(domainClass, em),em);
}
public List<T> findAll(Limitable limitable) {
if (limitable != null) {
TypedQuery<T> query = getQuery(null, limitable.getSort());
Integer firstResult = limitable.getFirstResult();
if (firstResult != null && firstResult > 0) {
query.setFirstResult(firstResult);
}
Integer maxResults = limitable.getMaxResults();
if (maxResults != null && maxResults > 0) {
query.setMaxResults(maxResults);
}
return query.getResultList();
} else {
return findAll();
}
}
public void refresh(T entity) {
em.refresh(entity);
}
public List<T> findAll(Specification<T> spec, Limitable limitable) {
if (limitable != null) {
TypedQuery<T> query = getQuery(spec, limitable.getSort());
if (limitable.getFirstResult() != null) {
query.setFirstResult(limitable.getFirstResult());
}
if (limitable.getMaxResults() != null) {
query.setMaxResults(limitable.getMaxResults());
}
return query.getResultList();
} else {
return findAll(spec);
}
}
}
| 29.407895 | 84 | 0.714989 |
830b8d4b5d6a5ebf7b02e04b38ecf7573a69df3c | 3,594 | package dao;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import model.Arketuar;
import model.Bojra;
import model.Klient;
import model.Shitje;
public class ShitjeDao extends DAO {
public ShitjeDao() {
super();
}
public DecimalFormat decimalFormat = new DecimalFormat("#.##");
public List<Shitje> getShitje(LocalDate date_from, LocalDate date_to) throws SQLException {
List<Shitje> data = new ArrayList<Shitje>();
String query = "select sh.lloji_fatures, sh.created_date, b.emri, b.id, " +
"sh.sasia, sh.cmimi, k.klienti, k.id, sh.id, a.id, a.menyra, sh.date_likujduar " +
"from toner.shitje sh join toner.bojra b " +
"on sh.bojra_id = b.id join toner.arketuar a " +
"on sh.arketim_id = a.id join toner.klient k " +
"on sh.klient_id = k.id where sh.deleted = 0 " +
"and sh.created_date between '"+date_from+"' and '"+date_to+"' ";
stm = connector.prepareStatement(query);
rs = stm.executeQuery(query);
while(rs.next()) {
Bojra bojra = new Bojra();
bojra.setId(rs.getInt(4));
bojra.setEmri(rs.getString(3));
Klient klient = new Klient();
klient.setId(rs.getInt(8));
klient.setKlienti(rs.getString(7));
Arketuar arketuar = new Arketuar();
arketuar.setId(rs.getInt(10));
arketuar.setMenyra(rs.getString(11));
Shitje shitje = new Shitje();
shitje.setLloji_fatures(rs.getString(1));
shitje.setCreated_date(rs.getDate(2));
shitje.setBojra_id(bojra);
shitje.setSasia(rs.getDouble(5));
shitje.setCmimi(rs.getDouble(6));
shitje.setVlera(Double.parseDouble(decimalFormat.format(shitje.getSasia() * shitje.getCmimi())));
shitje.setKlient_id(klient);
shitje.setId(rs.getInt(9));
shitje.setArketim_id(arketuar);
shitje.setDate_likujduar(rs.getDate(12));
data.add(shitje);
}
return data;
}
public void addShitje(Shitje shitje) throws SQLException {
String insertBojra = "INSERT INTO toner.shitje " +
"(lloji_fatures, klient_id, arketim_id, date_likujduar, bojra_id, sasia, cmimi)"
+ " VALUES (?,?,?,?,?,?,?)";
stm = connector.prepareStatement(insertBojra);
stm.setString(1, shitje.getLloji_fatures());
stm.setInt(2, shitje.getKlient_id().getId());
stm.setInt(3, shitje.getArketim_id().getId());
if(shitje.getDate_likujduar() == null)
stm.setDate(4, shitje.getEmptyDate());
else
stm.setDate(4, new java.sql.Date(shitje.getDate_likujduar().getTime()));
stm.setInt(5, shitje.getBojra_id().getId());
stm.setDouble(6, shitje.getSasia());
stm.setDouble(7, shitje.getCmimi());
stm.execute();
stm.close();
}
public void updateShitje(Shitje shitje) throws SQLException {
String update = "UPDATE toner.shitje SET lloji_fatures = ?, klient_id = ?, arketim_id = ?, date_likujduar = ?, "
+ "bojra_id = ?, sasia = ?, cmimi = ? WHERE id = ?";
stm = connector.prepareStatement(update);
stm.setString(1, shitje.getLloji_fatures());
stm.setInt(2, shitje.getKlient_id().getId());
stm.setInt(3, shitje.getArketim_id().getId());
stm.setDate(4, new java.sql.Date(shitje.getDate_likujduar().getTime()));
stm.setInt(5, shitje.getBojra_id().getId());
stm.setDouble(6, shitje.getSasia());
stm.setDouble(7, shitje.getCmimi());
stm.setInt(8, shitje.getId());
stm.executeUpdate();
stm.close();
}
public void deleteShitje(int id) throws SQLException {
String query = "DELETE FROM toner.shitje where id=?";
stm = connector.prepareStatement(query);
stm.setInt(1, id);
stm.execute();
stm.close();
}
}
| 30.982759 | 114 | 0.6867 |
bfdf3a63fcf2b1e57b22c2044c625e973d1dc8e0 | 2,089 | package com.example.chihurmnanyanwanevu.popularmovies.adapter;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.example.chihurmnanyanwanevu.popularmovies.databinding.ItemReviewBinding;
import com.example.chihurmnanyanwanevu.popularmovies.model.Review;
import com.example.chihurmnanyanwanevu.popularmovies.ui.DetailActivity;
import java.util.ArrayList;
import java.util.List;
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.ReviewAdapterViewHolder> {
private final Activity mActivity;
private List<Review> mList;
public ReviewAdapter(Activity activity) {
this.mActivity = activity;
}
@NonNull
@Override
public ReviewAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mActivity);
ItemReviewBinding binding = ItemReviewBinding.inflate(layoutInflater, parent, false);
return new ReviewAdapterViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ReviewAdapterViewHolder holder, int position) {
Review review = mList.get(position);
holder.bind(review);
}
@Override
public int getItemCount() {
if (mList == null) {
return 0;
}
return mList.size();
}
public void addReviewsList(List<Review> reviewsList) {
mList = reviewsList;
notifyDataSetChanged();
}
public ArrayList<Review> getList() {
return (ArrayList<Review>) mList;
}
public class ReviewAdapterViewHolder extends RecyclerView.ViewHolder {
ItemReviewBinding binding;
ReviewAdapterViewHolder(ItemReviewBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
void bind(Review review) {
binding.setReview(review);
binding.setPresenter((DetailActivity) mActivity);
}
}
} | 30.275362 | 96 | 0.711345 |
5e9657baca95b1e995f9652c0201f38bef79658f | 526 | package grafioschtrader.algo;
import java.util.List;
import grafioschtrader.entities.AlgoTop;
public class AlgoTopCreate extends AlgoTop {
private static final long serialVersionUID = 1L;
public List<AssetclassPercentage> assetclassPercentageList;
public static class AssetclassPercentage {
public Integer idAssetclass;
public Float percentage;
@Override
public String toString() {
return "AssetclassPercentage [idAssetclass=" + idAssetclass + ", percentage=" + percentage + "]";
}
}
}
| 23.909091 | 103 | 0.747148 |
f919d990b7e6abcfbfa946af1f98c984766d4535 | 9,383 | package com.hcw2175.library.qrscan;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.hcw2175.library.qrscan.camera.CameraManager;
import com.hcw2175.library.qrscan.decode.DecodeMatcher;
import com.hcw2175.library.qrscan.listener.ActivityLiveTaskTimer;
import java.io.IOException;
import java.util.regex.Pattern;
/**
* 二维码扫码Activity
*
* @author hucw
* @version 0.0.3
*/
public class QRScanActivity extends AppCompatActivity implements SurfaceHolder.Callback, View.OnClickListener {
private static final String TAG = "QRScanActivity";
/** 扫码成功提示音音量,值:{@value} **/
private static final float BEEP_VOLUME = 0.50f;
/** 震动提示时长,值:{@value} **/
private static final long VIBRATE_DURATION = 200L;
private QRScanActivityHandler mHandler;
private ActivityLiveTaskTimer mInactivityTimer;
private MediaPlayer mMediaPlayer;
private DecodeMatcher mDecodeMatcher = null;
// UI Fields
private RelativeLayout mContainer = null;
private RelativeLayout mCropLayout = null;
private ImageView mBtnFlashLight = null;
private boolean hasSurface = false;
private boolean playBeep = true;
private boolean vibrate = true;
private boolean isFlashLightOpen = false;
private int x = 0;
private int y = 0;
private int cropWidth = 0;
private int cropHeight = 0;
// 校验扫码结果正则表达式
private String mPattern = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qrscan_act);
Bundle params = getIntent().getExtras();
if (null != params && params.containsKey("pattern")) {
this.mPattern = params.getString("pattern");
}
// 界面控件初始化
mContainer = (RelativeLayout) findViewById(R.id.capture_containter);
mCropLayout = (RelativeLayout) findViewById(R.id.capture_crop_layout);
mBtnFlashLight = (ImageView) findViewById(R.id.btn_flash_light);
// 扫描动画初始化
initScannerAnimation();
// 初始化 CameraManager
CameraManager.init(this);
//
mInactivityTimer = new ActivityLiveTaskTimer(this);
}
@Override
protected void onResume() {
super.onResume();
// 初始化相机取景器
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
initCamera(surfaceHolder);
} else {
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
// 初始化铃声播放服务
AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
playBeep = audioService.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
initBeepSound();
}
@Override
protected void onPause() {
super.onPause();
if (mHandler != null) {
mHandler.quitSynchronously();
mHandler = null;
}
CameraManager.getInstance().closeDriver();
}
@Override
protected void onDestroy() {
mInactivityTimer.shutdown();
super.onDestroy();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
@Override
public void onClick(View v) {
/*switch (v.getId()) {
case :
break;
}*/
}
/**
* 扫码结果解析成功回调处理
*
* @param result 扫描结果
*/
public void onDecodeSuccess(String result) {
mInactivityTimer.init();
// 空结果继续扫描
if (null == result || result == "") {
// 连续扫描,不发送此消息扫描一次结束后就不能再次扫描
//Toast.makeText(this, "扫描结果不合法,请重新扫描", Toast.LENGTH_SHORT).show();
mHandler.sendEmptyMessage(R.id.restart_preview);
return;
}
// 正则校验结果
boolean isMatch = true;
if (null != mPattern && mPattern != "") {
isMatch = Pattern.matches(mPattern, result);
}
if (isMatch) {
playBeepSoundAndVibrate();
Log.d(TAG, "二维码/条形码 扫描结果: " + result);
Intent intent = new Intent();
intent.putExtra(QRCodeConstants.SCAR_RESULT, result);
this.setResult(RESULT_OK, intent);
finish();
} else {
// 连续扫描,不发送此消息扫描一次结束后就不能再次扫描
//Toast.makeText(this, "扫描结果不合法,请重新扫描", Toast.LENGTH_SHORT).show();
mHandler.sendEmptyMessage(R.id.restart_preview);
}
}
//----------------------------------------------------------------------------------------------扫描成功之后的振动与声音提示 start
//==============================================================================================扫描成功之后的振动与声音提示 end
// ==========================================================================
// private methods ==========================================================
/**
* 初始化相机
*
* @param surfaceHolder
*/
private void initCamera(SurfaceHolder surfaceHolder) {
try {
CameraManager.getInstance().openDriver(surfaceHolder);
Point point = CameraManager.getInstance().getCameraResolution();
int width = point.y;
int height = point.x;
this.x = mCropLayout.getLeft() * width / mContainer.getWidth();
this.y = mCropLayout.getTop() * height / mContainer.getHeight();
this.cropWidth = mCropLayout.getWidth() * width / mContainer.getWidth();
this.cropHeight = mCropLayout.getHeight() * height / mContainer.getHeight();
if (mHandler == null) {
mHandler = new QRScanActivityHandler(QRScanActivity.this);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
/**
* 初始化扫描框动画
*/
private void initScannerAnimation() {
ImageView scanView = (ImageView) findViewById(R.id.capture_scan_line);
if (null != scanView) {
ScaleAnimation animation = new ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f);
animation.setRepeatCount(-1);
animation.setRepeatMode(Animation.RESTART);
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(1200);
scanView.startAnimation(animation);
}
}
/**
* 播放提示音
*/
private void initBeepSound() {
if (playBeep && mMediaPlayer == null) {
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mMediaPlayer) {
mMediaPlayer.seekTo(0);
}
});
AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
try {
mMediaPlayer.setDataSource(file.getFileDescriptor(),
file.getStartOffset(), file.getLength());
file.close();
mMediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mMediaPlayer.prepare();
} catch (IOException e) {
mMediaPlayer = null;
}
}
}
/**
* 播放提示音并震动
*/
private void playBeepSoundAndVibrate() {
if (playBeep && mMediaPlayer != null) {
mMediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
// ==================================================================
// setter/getter ====================================================
public Handler getQRScanActivityHandler() {
return mHandler;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getCropWidth() {
return cropWidth;
}
public int getCropHeight() {
return cropHeight;
}
public DecodeMatcher getDecodeMatcher() {
return mDecodeMatcher;
}
public void setDecodeMatcher(DecodeMatcher mDecodeMatcher) {
this.mDecodeMatcher = mDecodeMatcher;
}
}
| 30.073718 | 120 | 0.589364 |
4ebf4abaa8a2aeb0a2210f7ae6b5ef7298e38cf0 | 1,135 | /**
* __ __ __
* ____/ /_ ____/ /______ _ ___ / /_
* / __ / / ___/ __/ ___/ / __ `/ __/
* / /_/ / (__ ) / / / / / /_/ / /
* \__,_/_/____/_/ /_/ /_/\__, /_/
* / /
* \/
* http://distriqt.com
*
* @file FirebaseExtension.java
* @brief Main Extension implementation for this ANE
* @author Michael Archbold
* @created Jan 19, 2012
* @updated $Date:$
* @copyright http://distriqt.com/copyright/license.txt
*
*/
package com.distriqt.extension.exceptions;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREExtension;
import com.distriqt.extension.exceptions.util.FREUtils;
public class ExceptionsExtension implements FREExtension
{
public static ExceptionsContext context;
public static String ID = "com.distriqt.Exceptions";
@Override
public FREContext createContext(String arg0)
{
context = new ExceptionsContext();
FREUtils.context = context;
FREUtils.ID = ID;
return context;
}
@Override
public void dispose()
{
context = null;
}
@Override
public void initialize()
{
}
}
| 20.636364 | 56 | 0.604405 |
b56460d00d08aafd0f2e2736a716a1dffac06df0 | 3,345 | package de.otto.synapse.endpoint.receiver.kinesis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
import software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest;
import software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse;
import software.amazon.awssdk.services.kinesis.model.ResourceNotFoundException;
import software.amazon.awssdk.services.kinesis.model.Shard;
import java.util.concurrent.atomic.AtomicReference;
import static de.otto.synapse.endpoint.receiver.kinesis.KinesisStreamInfo.builder;
import static java.lang.String.format;
public class KinesisStreamInfoProvider {
private static final Logger LOG = LoggerFactory.getLogger(KinesisStreamInfoProvider.class);
private final KinesisAsyncClient kinesisAsyncClient;
public KinesisStreamInfoProvider(final KinesisAsyncClient kinesisAsyncClient) {
this.kinesisAsyncClient = kinesisAsyncClient;
}
/**
* Returns stream information for the given Kinesis stream.
*
* @param channelName the name of the stream
* @return KinesisStreamInfo
* @throws IllegalArgumentException if the stream does not exist
*/
public KinesisStreamInfo getStreamInfo(final String channelName) {
try {
final DescribeStreamRequest request = DescribeStreamRequest.builder().streamName(channelName).build();
DescribeStreamResponse response = kinesisAsyncClient.describeStream(request).join();
final KinesisStreamInfo.Builder streamInfoBuilder = builder()
.withChannelName(channelName)
.withArn(response.streamDescription().streamARN());
String lastSeenShardId = addShardInfoFromResponse(response, streamInfoBuilder);
while (response.streamDescription().hasMoreShards()) {
response = kinesisAsyncClient.describeStream(DescribeStreamRequest.builder()
.streamName(channelName)
.exclusiveStartShardId(lastSeenShardId)
.build())
.join();
lastSeenShardId = addShardInfoFromResponse(response, streamInfoBuilder);
}
return streamInfoBuilder.build();
} catch (final ResourceNotFoundException e) {
throw new IllegalArgumentException(format("Kinesis channel %s does not exist: %s", channelName, e.getMessage()));
}
}
private String addShardInfoFromResponse(DescribeStreamResponse response, KinesisStreamInfo.Builder streamInfoBuilder) {
AtomicReference<String> lastShardId = new AtomicReference<>(null);
response
.streamDescription()
.shards()
.stream()
.forEach(shard -> {
lastShardId.set(shard.shardId());
streamInfoBuilder.withShard(shard.shardId(), isShardOpen(shard));
});
return lastShardId.get();
}
private boolean isShardOpen(Shard shard) {
if (shard.sequenceNumberRange().endingSequenceNumber() == null) {
return true;
} else {
LOG.warn("Shard with id {} is closed. Cannot retrieve data.", shard.shardId());
return false;
}
}
}
| 39.821429 | 125 | 0.678326 |
3044f7b401df71e96eac1829f7a78c2f586c7784 | 852 | package us.ihmc.exampleSimulations.exampleContact;
import javax.vecmath.Vector3d;
import us.ihmc.robotics.geometry.RigidBodyTransform;
import us.ihmc.simulationconstructionset.util.ground.CombinedTerrainObject3D;
public class ExampleTerrainWithTable extends CombinedTerrainObject3D
{
public ExampleTerrainWithTable()
{
super("ExampleTerrainWithTable");
// this.addTable(0.0, 0.0, 1.0, 0.5, 0.0, 1.0);
RigidBodyTransform configuration = new RigidBodyTransform();
configuration.setRotationEulerAndZeroTranslation(new Vector3d(0.0, 0.0, Math.PI/4.0));
configuration.setTranslation(new Vector3d(3.0, 0.0, 0.6));
this.addRotatableTable(configuration, 2.0, 1.0, 1.2, 0.05);
this.addTable(-1.5, -1.0, 1.5, 1.0, 0.45, 0.5);
this.addBox(-10.0, -10.0, 10.0, 10.0, -0.05, 0.0);
}
}
| 32.769231 | 92 | 0.696009 |
52486f576f8daf8b57c22d12c23fbd10596a6550 | 353 | package com.google.android.material.transition;
import android.graphics.RectF;
public interface FitModeEvaluator {
void applyMask(RectF rectF, float f, FitModeResult fitModeResult);
FitModeResult evaluate(float f, float f2, float f3, float f4, float f5, float f6, float f7);
boolean shouldMaskStartBounds(FitModeResult fitModeResult);
}
| 29.416667 | 96 | 0.78187 |
857c232ef69ccbb65395af6ef5a18f596f6b6643 | 907 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
public class GetQuijote {
public static void main(String[] args) {
int pag = 0;
while (pag <= 35) {
try {
String pagina = "https://www.elmundo.es/quijote/capitulo.html?cual=" + pag;
URL url = new URL(pagina);
InputStreamReader reader = new InputStreamReader(url.openStream());
BufferedReader in = new BufferedReader(reader);
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
sb.append(inputLine);
}
PrintWriter writer = new PrintWriter("Capitulo"+pag+".txt", "UTF-8");
writer.write(sb.toString());
writer.flush();
writer.close();
in.close();
pag++;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
} | 25.194444 | 79 | 0.643881 |
2df6929c05c7a59aabce9a31067b7d383e17dfc2 | 11,334 | package gov.nasa.jpl.aerie.scheduler.server.remotes.postgres;
import gov.nasa.jpl.aerie.merlin.driver.ActivityInstanceId;
import gov.nasa.jpl.aerie.scheduler.server.ResultsProtocol;
import gov.nasa.jpl.aerie.scheduler.server.exceptions.NoSuchRequestException;
import gov.nasa.jpl.aerie.scheduler.server.exceptions.NoSuchSpecificationException;
import gov.nasa.jpl.aerie.scheduler.server.models.GoalId;
import gov.nasa.jpl.aerie.scheduler.server.models.SpecificationId;
import gov.nasa.jpl.aerie.scheduler.server.remotes.ResultsCellRepository;
import gov.nasa.jpl.aerie.scheduler.server.services.ScheduleResults;
import gov.nasa.jpl.aerie.scheduler.server.services.ScheduleResults.GoalResult;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Optional;
public final class PostgresResultsCellRepository implements ResultsCellRepository {
private final DataSource dataSource;
public PostgresResultsCellRepository(final DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public ResultsProtocol.OwnerRole allocate(final SpecificationId specificationId)
{
try (final var connection = this.dataSource.getConnection()) {
final var spec = getSpecification(connection, specificationId);
final var request = createRequest(connection, spec);
return new PostgresResultsCell(
this.dataSource,
new SpecificationId(request.specificationId()),
request.specificationRevision(),
request.analysisId());
} catch (final SQLException ex) {
throw new DatabaseException("Failed to get schedule specification", ex);
} catch (final NoSuchSpecificationException ex) {
throw new Error("Cannot allocate scheduling cell for nonexistent specification", ex);
}
}
@Override
public Optional<ResultsProtocol.ReaderRole> lookup(final SpecificationId specificationId)
{
try (final var connection = this.dataSource.getConnection()) {
final var spec = getSpecification(connection, specificationId);
final var request = getRequest(connection, specificationId, spec.revision());
return Optional.of(new PostgresResultsCell(
this.dataSource,
new SpecificationId(request.specificationId()),
request.specificationRevision(),
request.analysisId()));
} catch (final SQLException ex) {
throw new DatabaseException("Failed to get schedule specification", ex);
} catch (final NoSuchSpecificationException | NoSuchRequestException ex) {
return Optional.empty();
}
}
@Override
public void deallocate(final ResultsProtocol.OwnerRole resultsCell)
{
if (!(resultsCell instanceof PostgresResultsCell cell)) {
throw new Error("Unable to deallocate results cell of unknown type");
}
try (final var connection = this.dataSource.getConnection()) {
deleteRequest(connection, cell.specId, cell.specRevision);
} catch (final SQLException ex) {
throw new DatabaseException("Failed to delete scheduling request", ex);
}
}
private static SpecificationRecord getSpecification(final Connection connection, final SpecificationId specificationId)
throws SQLException, NoSuchSpecificationException {
try (final var getSpecificationAction = new GetSpecificationAction(connection)) {
return getSpecificationAction
.get(specificationId.id())
.orElseThrow(() -> new NoSuchSpecificationException(specificationId));
}
}
private static RequestRecord getRequest(
final Connection connection,
final SpecificationId specificationId,
final long specificationRevision
) throws SQLException, NoSuchRequestException {
try (final var getRequestAction = new GetRequestAction(connection)) {
return getRequestAction
.get(specificationId.id(), specificationRevision)
.orElseThrow(() -> new NoSuchRequestException(specificationId, specificationRevision));
}
}
private static RequestRecord createRequest(
final Connection connection,
final SpecificationRecord specification
) throws SQLException {
try (final var createRequestAction = new CreateRequestAction(connection)) {
return createRequestAction.apply(specification);
}
}
private static void deleteRequest(
final Connection connection,
final SpecificationId specId,
final long specRevision
) throws SQLException {
try (final var deleteRequestAction = new DeleteRequestAction(connection)) {
deleteRequestAction.apply(specId.id(), specRevision);
}
}
private static void cancelRequest(
final Connection connection,
final SpecificationId specId,
final long specRevision
) throws SQLException, NoSuchRequestException
{
try (final var cancelSchedulingRequestAction = new CancelSchedulingRequestAction(connection)) {
cancelSchedulingRequestAction.apply(specId.id(), specRevision);
} catch (final FailedUpdateException ex) {
throw new NoSuchRequestException(specId, specRevision);
}
}
private static void failRequest(
final Connection connection,
final SpecificationId specId,
final long specRevision,
final String reason
) throws SQLException {
try (final var setRequestStateAction = new SetRequestStateAction(connection)) {
setRequestStateAction.apply(
specId.id(),
specRevision,
RequestRecord.Status.FAILED,
reason);
}
}
private static void succeedRequest(
final Connection connection,
final SpecificationId specId,
final long specRevision,
final long analysisId,
final ScheduleResults results
) throws SQLException {
postResults(connection, analysisId, results);
try (final var setRequestStateAction = new SetRequestStateAction(connection)) {
setRequestStateAction.apply(
specId.id(),
specRevision,
RequestRecord.Status.SUCCESS,
null);
}
}
private static void postResults(
final Connection connection,
final long analysisId,
final ScheduleResults results
) throws SQLException {
final var numGoals = results.goalResults().size();
final var goalSatisfaction = new HashMap<GoalId, Boolean>(numGoals);
final var createdActivities = new HashMap<GoalId, Collection<ActivityInstanceId>>(numGoals);
final var satisfyingActivities = new HashMap<GoalId, Collection<ActivityInstanceId>>(numGoals);
results.goalResults().forEach((goalId, result) -> {
goalSatisfaction.put(goalId, result.satisfied());
createdActivities.put(goalId, result.createdActivities());
satisfyingActivities.put(goalId, result.satisfyingActivities());
});
try (
final var insertGoalSatisfactionAction = new InsertGoalSatisfactionAction(connection);
final var insertCreatedActivitiesAction = new InsertCreatedActivitiesAction(connection);
final var insertSatisfyingActivitiesAction = new InsertSatisfyingActivitiesAction(connection)
) {
insertGoalSatisfactionAction.apply(analysisId, goalSatisfaction);
insertCreatedActivitiesAction.apply(analysisId, createdActivities);
insertSatisfyingActivitiesAction.apply(analysisId, satisfyingActivities);
}
}
private static ScheduleResults getResults(
final Connection connection,
final long analysisId
) throws SQLException {
try (
final var getGoalSatisfactionAction = new GetGoalSatisfactionAction(connection);
final var getCreatedActivitiesAction = new GetCreatedActivitiesAction(connection);
final var getSatisfyingActivitiesAction = new GetSatisfyingActivitiesAction(connection)
) {
final var goalSatisfaction = getGoalSatisfactionAction.get(analysisId);
final var createdActivities = getCreatedActivitiesAction.get(analysisId);
final var satisfyingActivities = getSatisfyingActivitiesAction.get(analysisId);
final var goalResults = new HashMap<GoalId, GoalResult>(goalSatisfaction.size());
for (final var goalId : goalSatisfaction.keySet()) {
goalResults.put(goalId, new GoalResult(
createdActivities.get(goalId),
satisfyingActivities.get(goalId),
goalSatisfaction.get(goalId)
));
}
return new ScheduleResults(goalResults);
}
}
public static final class PostgresResultsCell implements ResultsProtocol.OwnerRole {
private final DataSource dataSource;
private final SpecificationId specId;
private final long specRevision;
private final long analysisId;
public PostgresResultsCell(
final DataSource dataSource,
final SpecificationId specId,
final long specRevision,
final long analysisId
) {
this.dataSource = dataSource;
this.specId = specId;
this.specRevision = specRevision;
this.analysisId = analysisId;
}
@Override
public ResultsProtocol.State get() {
try (final var connection = dataSource.getConnection()) {
final var request = getRequest(connection, specId, specRevision);
return switch(request.status()) {
case INCOMPLETE -> new ResultsProtocol.State.Incomplete();
case FAILED -> new ResultsProtocol.State.Failed(request.failureReason());
case SUCCESS -> new ResultsProtocol.State.Success(getResults(connection, request.analysisId()));
};
} catch (final NoSuchRequestException ex) {
throw new Error("Scheduling request no longer exists");
} catch(final SQLException ex) {
throw new DatabaseException("Failed to get scheduling request status", ex);
}
}
@Override
public void cancel() {
try (final var connection = dataSource.getConnection()) {
cancelRequest(connection, specId, specRevision);
} catch (final NoSuchRequestException ex) {
throw new Error("Scheduling request no longer exists");
} catch(final SQLException ex) {
throw new DatabaseException("Failed to cancel scheduling request", ex);
}
}
@Override
public boolean isCanceled() {
try (final var connection = dataSource.getConnection()) {
return getRequest(connection, specId, specRevision).canceled();
} catch (final NoSuchRequestException ex) {
throw new Error("Scheduling request no longer exists");
} catch(final SQLException ex) {
throw new DatabaseException("Failed to determine if scheduling request is canceled", ex);
}
}
@Override
public void succeedWith(final ScheduleResults results) {
try (final var connection = dataSource.getConnection()) {
succeedRequest(connection, specId, specRevision, analysisId, results);
} catch (final SQLException ex) {
throw new DatabaseException("Failed to update scheduling request state", ex);
}
}
@Override
public void failWith(final String reason) {
try (final var connection = dataSource.getConnection()) {
failRequest(connection, specId, specRevision, reason);
} catch (final SQLException ex) {
throw new DatabaseException("Failed to update scheduling request state", ex);
}
}
}
}
| 38.948454 | 121 | 0.721987 |
843d793c0ce1f26bc6aa08990f655e77ba5e6b98 | 1,618 | package com.codewalle.tra.Model;
import android.app.Application;
import android.content.Context;
import com.codewalle.tra.LoginActivity;
import com.codewalle.tra.utils.Constants;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.AsyncHttpRequest;
import com.koushikdutta.ion.future.ResponseFuture;
import org.json.JSONObject;
import java.util.List;
import java.util.concurrent.Future;
/**
* Created by xiangzhipan on 14-9-29.
*/
public interface TRAApp {
// TODO 支持多帐号时可用
// public List<AccountInfo> getCachedAccounts();
public AccountInfo getCachedAccount();
public void cacheAccount(AccountInfo account);
com.koushikdutta.async.future.Future<JSONObject> doJSONRequest(Constants requestType,
AsyncHttpRequest request,
AsyncHttpClient.JSONObjectCallback callback);
boolean isAutoLogin();
Future doLogin(String username, String password, FutureCallback callback);
Future getJoinedActivityInfo(FutureCallback callback);
Future getActivityInfo(String activityId,FutureCallback callback);
Future getTRAList(boolean expired, FutureCallback callback);
Future joinActivity(String activityId,FutureCallback callback);
Future quitActivity(String actiivtyId,FutureCallback callback);
Future postComment(TRAInfo info, ActivityComment comment, FutureCallback callback);
int getBgColor();
}
| 36.772727 | 112 | 0.73733 |
e15cd3c8cff439bc00ec0ebda4723618acc6ad7a | 999 | package org.schooldesk.intergrationtests;
import org.junit.After;
import org.junit.Before;
import org.schooldesk.core.services.IServiceFactory;
import org.schooldesk.core.services.ServiceFactory;
import org.schooldesk.dao.DaoFactory;
import org.schooldesk.dao.IDaoFactory;
import org.schooldesk.dao.inmemory.inmemory.*;
//import org.schooldesk.dao.hibernateimpl.DbHelper;
//import org.schooldesk.dao.hibernateimpl.HibernateDaoFactory;
public class AbstractTest {
private IDaoFactory daoFactory;
// private DbHelper dbHelper;
private IServiceFactory serviceFactory;
@Before
public final void init() {
daoFactory = DaoFactory.create();
// dbHelper = new DbHelper((HibernateDaoFactory) daoFactory);
serviceFactory = ServiceFactory.create(daoFactory);
}
@After
public final void dispose() {
// dbHelper.clearDb();
Database.resetDB();
}
protected IDaoFactory getDaoFactory() {
return daoFactory;
}
protected IServiceFactory getServiceFactory() {
return serviceFactory;
}
}
| 24.975 | 62 | 0.787788 |
7dc1f34ac81ae6e2218ae1d889e45a68bb24bbf9 | 712 | package org.zstack.network.service.portforwarding;
import org.zstack.header.network.service.NetworkServiceProviderType;
public interface RevokePortForwardingRuleExtensionPoint {
void preRevokePortForwardingRule(PortForwardingRuleInventory inv, NetworkServiceProviderType serviceProviderType) throws PortForwardingException;
void beforeRevokePortForwardingRule(PortForwardingRuleInventory inv, NetworkServiceProviderType serviceProviderType);
void afterRevokePortForwardingRule(PortForwardingRuleInventory inv, NetworkServiceProviderType serviceProviderType);
void failToRevokePortForwardingRule(PortForwardingRuleInventory inv, NetworkServiceProviderType serviceProviderType);
}
| 50.857143 | 149 | 0.869382 |
223e7ef0963056cec5177851a5ee6bdf2955fe2b | 2,411 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.googleanalytics;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;
/**
* @author Pavel Sakun
*/
@RunWith( Parameterized.class )
public class GoogleAnalyticsApiFacadeTest {
@Parameterized.Parameters
public static List<Object[]> primeNumbers() {
return Arrays.asList(
new Object[] { "C:/key.p12", FileNotFoundException.class },
new Object[] { "C:\\key.p12", FileNotFoundException.class },
new Object[] { "/key.p12", FileNotFoundException.class },
new Object[] { "file:///C:/key.p12", FileNotFoundException.class },
new Object[] { "file:///C:\\key.p12", FileNotFoundException.class },
// KettleFileException on Windows, FileNotFoundException on Ubuntu
new Object[] { "file:///key.p12", Exception.class }
);
}
@Rule
public final ExpectedException expectedException;
private final String path;
public GoogleAnalyticsApiFacadeTest( String path, Class<Exception> expectedExceptionClass ) {
this.path = path;
this.expectedException = ExpectedException.none();
this.expectedException.expect( expectedExceptionClass );
}
@Test
public void exceptionIsThrowsForNonExistingFiles() throws Exception {
GoogleAnalyticsApiFacade.createFor( "application-name", "account", path );
}
}
| 33.957746 | 95 | 0.654085 |
c91f465382c45a3359ee4df449393d1ee856bcea | 730 | package de.qaware.oss.cloud.nativ.wjax2016;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
/**
* Custom configuration for the required Spring Social Twitter beans.
*/
@Configuration
public class ZwitscherConfiguration {
@Bean
public Twitter twitter(final @Value("${spring.social.twitter.appId}") String appId,
final @Value("${spring.social.twitter.appSecret}") String appSecret) {
return new TwitterTemplate(appId, appSecret);
}
}
| 36.5 | 97 | 0.760274 |
592e260790e9324a3aee207ea0276e9c7fe455ce | 279 | package com.desertkun.brainout.common.msg.server;
public class AchievementCompletedMsg
{
public String achievementId;
public AchievementCompletedMsg() {}
public AchievementCompletedMsg(String achievementId)
{
this.achievementId = achievementId;
}
}
| 21.461538 | 56 | 0.74552 |
b9b9acd2264022d79489b1d004c661803a420b63 | 117,514 | /*
* Signing Today Web
* *Signing Today* is the perfect Digital Signature Gateway. Whenever in Your workflow You need to add one or more Digital Signatures to Your document, *Signing Today* is the right choice. You prepare Your documents, *Signing Today* takes care of all the rest: send invitations (`signature tickets`) to signers, collects their signatures, send You back the signed document. Integrating *Signing Today* in Your existing applications is very easy. Just follow these API specifications and get inspired by the many examples presented hereafter.
*
* The version of the OpenAPI document: 2.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package signingToday.client.api;
import signingToday.client.ApiCallback;
import signingToday.client.ApiClient;
import signingToday.client.ApiException;
import signingToday.client.ApiResponse;
import signingToday.client.Configuration;
import signingToday.client.Pair;
import signingToday.client.ProgressRequestBody;
import signingToday.client.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import signingToday.client.model.AuditRecord;
import signingToday.client.model.DSTSigningAddressResponse;
import signingToday.client.model.DSTsGetResponse;
import signingToday.client.model.DigitalSignatureTransaction;
import signingToday.client.model.ErrorResponse;
import signingToday.client.model.FillableForm;
import signingToday.client.model.ServiceFailureResponse;
import java.util.UUID;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Bit4idPathgroupDigitalSignatureTransactionsApi {
private ApiClient localVarApiClient;
public Bit4idPathgroupDigitalSignatureTransactionsApi() {
this(Configuration.getDefaultApiClient());
}
public Bit4idPathgroupDigitalSignatureTransactionsApi(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public ApiClient getApiClient() {
return localVarApiClient;
}
public void setApiClient(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
/**
* Build call for dSTIdAuditGet
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The audit associated to the DST sorted by date. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdAuditGetCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}/audit"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdAuditGetValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdAuditGet(Async)");
}
okhttp3.Call localVarCall = dSTIdAuditGetCall(id, _callback);
return localVarCall;
}
/**
* Retrieve the audit records associated to the DST
* This API allows to retrieves the audit records associated to the DST.
* @param id The value of _the unique id_ (required)
* @return List<AuditRecord>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The audit associated to the DST sorted by date. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public List<AuditRecord> dSTIdAuditGet(UUID id) throws ApiException {
ApiResponse<List<AuditRecord>> localVarResp = dSTIdAuditGetWithHttpInfo(id);
return localVarResp.getData();
}
/**
* Retrieve the audit records associated to the DST
* This API allows to retrieves the audit records associated to the DST.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<List<AuditRecord>>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The audit associated to the DST sorted by date. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<List<AuditRecord>> dSTIdAuditGetWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdAuditGetValidateBeforeCall(id, null);
Type localVarReturnType = new TypeToken<List<AuditRecord>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Retrieve the audit records associated to the DST (asynchronously)
* This API allows to retrieves the audit records associated to the DST.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The audit associated to the DST sorted by date. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdAuditGetAsync(UUID id, final ApiCallback<List<AuditRecord>> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdAuditGetValidateBeforeCall(id, _callback);
Type localVarReturnType = new TypeToken<List<AuditRecord>>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdDelete
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdDeleteCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdDeleteValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdDelete(Async)");
}
okhttp3.Call localVarCall = dSTIdDeleteCall(id, _callback);
return localVarCall;
}
/**
* Delete a DST
* This API allows to delete a DST. Actually the DST is marked as deleted thus not displayed anymore into the organization, but it will still be present in the database.
* @param id The value of _the unique id_ (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public void dSTIdDelete(UUID id) throws ApiException {
dSTIdDeleteWithHttpInfo(id);
}
/**
* Delete a DST
* This API allows to delete a DST. Actually the DST is marked as deleted thus not displayed anymore into the organization, but it will still be present in the database.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<Void> dSTIdDeleteWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdDeleteValidateBeforeCall(id, null);
return localVarApiClient.execute(localVarCall);
}
/**
* Delete a DST (asynchronously)
* This API allows to delete a DST. Actually the DST is marked as deleted thus not displayed anymore into the organization, but it will still be present in the database.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdDeleteAsync(UUID id, final ApiCallback<Void> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdDeleteValidateBeforeCall(id, _callback);
localVarApiClient.executeAsync(localVarCall, _callback);
return localVarCall;
}
/**
* Build call for dSTIdFillPatch
* @param id The value of _the unique id_ (required)
* @param fillableForm The form filled by the user. (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The DST has been modified according to the operation. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdFillPatchCall(UUID id, FillableForm fillableForm, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = fillableForm;
// create path and map variables
String localVarPath = "/DST/{id}/fill"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdFillPatchValidateBeforeCall(UUID id, FillableForm fillableForm, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdFillPatch(Async)");
}
// verify the required parameter 'fillableForm' is set
if (fillableForm == null) {
throw new ApiException("Missing the required parameter 'fillableForm' when calling dSTIdFillPatch(Async)");
}
okhttp3.Call localVarCall = dSTIdFillPatchCall(id, fillableForm, _callback);
return localVarCall;
}
/**
* Fill a form of a DST
* This API allows to fill a form of a DST.
* @param id The value of _the unique id_ (required)
* @param fillableForm The form filled by the user. (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The DST has been modified according to the operation. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTIdFillPatch(UUID id, FillableForm fillableForm) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTIdFillPatchWithHttpInfo(id, fillableForm);
return localVarResp.getData();
}
/**
* Fill a form of a DST
* This API allows to fill a form of a DST.
* @param id The value of _the unique id_ (required)
* @param fillableForm The form filled by the user. (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The DST has been modified according to the operation. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTIdFillPatchWithHttpInfo(UUID id, FillableForm fillableForm) throws ApiException {
okhttp3.Call localVarCall = dSTIdFillPatchValidateBeforeCall(id, fillableForm, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Fill a form of a DST (asynchronously)
* This API allows to fill a form of a DST.
* @param id The value of _the unique id_ (required)
* @param fillableForm The form filled by the user. (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The DST has been modified according to the operation. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdFillPatchAsync(UUID id, FillableForm fillableForm, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdFillPatchValidateBeforeCall(id, fillableForm, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdGet
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The data matching the selection parameters. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdGetCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdGetValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdGet(Async)");
}
okhttp3.Call localVarCall = dSTIdGetCall(id, _callback);
return localVarCall;
}
/**
* Retrieve a DST
* This API allows to retrieve a DST.
* @param id The value of _the unique id_ (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The data matching the selection parameters. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTIdGet(UUID id) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTIdGetWithHttpInfo(id);
return localVarResp.getData();
}
/**
* Retrieve a DST
* This API allows to retrieve a DST.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The data matching the selection parameters. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTIdGetWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdGetValidateBeforeCall(id, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Retrieve a DST (asynchronously)
* This API allows to retrieve a DST.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The data matching the selection parameters. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdGetAsync(UUID id, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdGetValidateBeforeCall(id, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdInstantiatePost
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as an instance of the template. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdInstantiatePostCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}/instantiate"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdInstantiatePostValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdInstantiatePost(Async)");
}
okhttp3.Call localVarCall = dSTIdInstantiatePostCall(id, _callback);
return localVarCall;
}
/**
* Instantiate a DST from a template
* This API allows to instantiate a DST from a template by specifying the template Id.
* @param id The value of _the unique id_ (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as an instance of the template. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTIdInstantiatePost(UUID id) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTIdInstantiatePostWithHttpInfo(id);
return localVarResp.getData();
}
/**
* Instantiate a DST from a template
* This API allows to instantiate a DST from a template by specifying the template Id.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as an instance of the template. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTIdInstantiatePostWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdInstantiatePostValidateBeforeCall(id, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Instantiate a DST from a template (asynchronously)
* This API allows to instantiate a DST from a template by specifying the template Id.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as an instance of the template. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdInstantiatePostAsync(UUID id, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdInstantiatePostValidateBeforeCall(id, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdModifyPost
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The modified DST in DRAFT state. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdModifyPostCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}/modify"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdModifyPostValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdModifyPost(Async)");
}
okhttp3.Call localVarCall = dSTIdModifyPostCall(id, _callback);
return localVarCall;
}
/**
* Modify a published DST template
* This API allows to move a published DST to DRAFT, allowing the modification. This way is possible to modify a _DST Template_.
* @param id The value of _the unique id_ (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The modified DST in DRAFT state. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTIdModifyPost(UUID id) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTIdModifyPostWithHttpInfo(id);
return localVarResp.getData();
}
/**
* Modify a published DST template
* This API allows to move a published DST to DRAFT, allowing the modification. This way is possible to modify a _DST Template_.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The modified DST in DRAFT state. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTIdModifyPostWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdModifyPostValidateBeforeCall(id, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Modify a published DST template (asynchronously)
* This API allows to move a published DST to DRAFT, allowing the modification. This way is possible to modify a _DST Template_.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The modified DST in DRAFT state. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdModifyPostAsync(UUID id, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdModifyPostValidateBeforeCall(id, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdNotifyPost
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdNotifyPostCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}/notify"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdNotifyPostValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdNotifyPost(Async)");
}
okhttp3.Call localVarCall = dSTIdNotifyPostCall(id, _callback);
return localVarCall;
}
/**
* Send notifications for a DST
* This API allows to send notifications to pending users for an active _DST_.
* @param id The value of _the unique id_ (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public void dSTIdNotifyPost(UUID id) throws ApiException {
dSTIdNotifyPostWithHttpInfo(id);
}
/**
* Send notifications for a DST
* This API allows to send notifications to pending users for an active _DST_.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<Void> dSTIdNotifyPostWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdNotifyPostValidateBeforeCall(id, null);
return localVarApiClient.execute(localVarCall);
}
/**
* Send notifications for a DST (asynchronously)
* This API allows to send notifications to pending users for an active _DST_.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdNotifyPostAsync(UUID id, final ApiCallback<Void> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdNotifyPostValidateBeforeCall(id, _callback);
localVarApiClient.executeAsync(localVarCall, _callback);
return localVarCall;
}
/**
* Build call for dSTIdPublishPost
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The DST has been modified according to the operation. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdPublishPostCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}/publish"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdPublishPostValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdPublishPost(Async)");
}
okhttp3.Call localVarCall = dSTIdPublishPostCall(id, _callback);
return localVarCall;
}
/**
* Publish a DST
* This API allows to publish a DST, the new state becomes published. It will automatically evolve to a new state where it will be filled or signed.
* @param id The value of _the unique id_ (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The DST has been modified according to the operation. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTIdPublishPost(UUID id) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTIdPublishPostWithHttpInfo(id);
return localVarResp.getData();
}
/**
* Publish a DST
* This API allows to publish a DST, the new state becomes published. It will automatically evolve to a new state where it will be filled or signed.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The DST has been modified according to the operation. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTIdPublishPostWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdPublishPostValidateBeforeCall(id, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Publish a DST (asynchronously)
* This API allows to publish a DST, the new state becomes published. It will automatically evolve to a new state where it will be filled or signed.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The DST has been modified according to the operation. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdPublishPostAsync(UUID id, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdPublishPostValidateBeforeCall(id, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdPut
* @param id The value of _the unique id_ (required)
* @param digitalSignatureTransaction DST replacing current object. (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The updated DST. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdPutCall(UUID id, DigitalSignatureTransaction digitalSignatureTransaction, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = digitalSignatureTransaction;
// create path and map variables
String localVarPath = "/DST/{id}"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdPutValidateBeforeCall(UUID id, DigitalSignatureTransaction digitalSignatureTransaction, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdPut(Async)");
}
// verify the required parameter 'digitalSignatureTransaction' is set
if (digitalSignatureTransaction == null) {
throw new ApiException("Missing the required parameter 'digitalSignatureTransaction' when calling dSTIdPut(Async)");
}
okhttp3.Call localVarCall = dSTIdPutCall(id, digitalSignatureTransaction, _callback);
return localVarCall;
}
/**
* Update a DST
* This API allows to update a DST.
* @param id The value of _the unique id_ (required)
* @param digitalSignatureTransaction DST replacing current object. (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The updated DST. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTIdPut(UUID id, DigitalSignatureTransaction digitalSignatureTransaction) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTIdPutWithHttpInfo(id, digitalSignatureTransaction);
return localVarResp.getData();
}
/**
* Update a DST
* This API allows to update a DST.
* @param id The value of _the unique id_ (required)
* @param digitalSignatureTransaction DST replacing current object. (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The updated DST. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTIdPutWithHttpInfo(UUID id, DigitalSignatureTransaction digitalSignatureTransaction) throws ApiException {
okhttp3.Call localVarCall = dSTIdPutValidateBeforeCall(id, digitalSignatureTransaction, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Update a DST (asynchronously)
* This API allows to update a DST.
* @param id The value of _the unique id_ (required)
* @param digitalSignatureTransaction DST replacing current object. (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The updated DST. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdPutAsync(UUID id, DigitalSignatureTransaction digitalSignatureTransaction, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdPutValidateBeforeCall(id, digitalSignatureTransaction, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdReplacePost
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as a replace of the referred DST. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdReplacePostCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}/replace"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdReplacePostValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdReplacePost(Async)");
}
okhttp3.Call localVarCall = dSTIdReplacePostCall(id, _callback);
return localVarCall;
}
/**
* Replace a rejected DST
* This API allows to replace a rejected DST instantiating a new one. The replacing DST is created in DRAFT state.
* @param id The value of _the unique id_ (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as a replace of the referred DST. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTIdReplacePost(UUID id) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTIdReplacePostWithHttpInfo(id);
return localVarResp.getData();
}
/**
* Replace a rejected DST
* This API allows to replace a rejected DST instantiating a new one. The replacing DST is created in DRAFT state.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as a replace of the referred DST. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTIdReplacePostWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdReplacePostValidateBeforeCall(id, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Replace a rejected DST (asynchronously)
* This API allows to replace a rejected DST instantiating a new one. The replacing DST is created in DRAFT state.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as a replace of the referred DST. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdReplacePostAsync(UUID id, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdReplacePostValidateBeforeCall(id, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdSignDocIdSignIdGet
* @param id The value of _the unique id_ (required)
* @param docId Reference to _docId_ has to be signed (required)
* @param signId Reference to the signature request id (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The URL where to sign. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdSignDocIdSignIdGetCall(UUID id, Integer docId, Integer signId, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}/sign/{docId}/{signId}"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()))
.replaceAll("\\{" + "docId" + "\\}", localVarApiClient.escapeString(docId.toString()))
.replaceAll("\\{" + "signId" + "\\}", localVarApiClient.escapeString(signId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdSignDocIdSignIdGetValidateBeforeCall(UUID id, Integer docId, Integer signId, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdSignDocIdSignIdGet(Async)");
}
// verify the required parameter 'docId' is set
if (docId == null) {
throw new ApiException("Missing the required parameter 'docId' when calling dSTIdSignDocIdSignIdGet(Async)");
}
// verify the required parameter 'signId' is set
if (signId == null) {
throw new ApiException("Missing the required parameter 'signId' when calling dSTIdSignDocIdSignIdGet(Async)");
}
okhttp3.Call localVarCall = dSTIdSignDocIdSignIdGetCall(id, docId, signId, _callback);
return localVarCall;
}
/**
* Return the address for signing
* This API returns the address to perform the signature.
* @param id The value of _the unique id_ (required)
* @param docId Reference to _docId_ has to be signed (required)
* @param signId Reference to the signature request id (required)
* @return DSTSigningAddressResponse
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The URL where to sign. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DSTSigningAddressResponse dSTIdSignDocIdSignIdGet(UUID id, Integer docId, Integer signId) throws ApiException {
ApiResponse<DSTSigningAddressResponse> localVarResp = dSTIdSignDocIdSignIdGetWithHttpInfo(id, docId, signId);
return localVarResp.getData();
}
/**
* Return the address for signing
* This API returns the address to perform the signature.
* @param id The value of _the unique id_ (required)
* @param docId Reference to _docId_ has to be signed (required)
* @param signId Reference to the signature request id (required)
* @return ApiResponse<DSTSigningAddressResponse>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The URL where to sign. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DSTSigningAddressResponse> dSTIdSignDocIdSignIdGetWithHttpInfo(UUID id, Integer docId, Integer signId) throws ApiException {
okhttp3.Call localVarCall = dSTIdSignDocIdSignIdGetValidateBeforeCall(id, docId, signId, null);
Type localVarReturnType = new TypeToken<DSTSigningAddressResponse>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Return the address for signing (asynchronously)
* This API returns the address to perform the signature.
* @param id The value of _the unique id_ (required)
* @param docId Reference to _docId_ has to be signed (required)
* @param signId Reference to the signature request id (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The URL where to sign. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdSignDocIdSignIdGetAsync(UUID id, Integer docId, Integer signId, final ApiCallback<DSTSigningAddressResponse> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdSignDocIdSignIdGetValidateBeforeCall(id, docId, signId, _callback);
Type localVarReturnType = new TypeToken<DSTSigningAddressResponse>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTIdTemplatizePost
* @param id The value of _the unique id_ (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as a template of the referred DST. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdTemplatizePostCall(UUID id, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DST/{id}/templatize"
.replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTIdTemplatizePostValidateBeforeCall(UUID id, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling dSTIdTemplatizePost(Async)");
}
okhttp3.Call localVarCall = dSTIdTemplatizePostCall(id, _callback);
return localVarCall;
}
/**
* Create a template from a DST
* This API allows to creates a new template starting from a DST. Currently implemented only for published DST templates.
* @param id The value of _the unique id_ (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as a template of the referred DST. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTIdTemplatizePost(UUID id) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTIdTemplatizePostWithHttpInfo(id);
return localVarResp.getData();
}
/**
* Create a template from a DST
* This API allows to creates a new template starting from a DST. Currently implemented only for published DST templates.
* @param id The value of _the unique id_ (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as a template of the referred DST. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTIdTemplatizePostWithHttpInfo(UUID id) throws ApiException {
okhttp3.Call localVarCall = dSTIdTemplatizePostValidateBeforeCall(id, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Create a template from a DST (asynchronously)
* This API allows to creates a new template starting from a DST. Currently implemented only for published DST templates.
* @param id The value of _the unique id_ (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The new DST that has been generated as a template of the referred DST. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr>
<tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTIdTemplatizePostAsync(UUID id, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTIdTemplatizePostValidateBeforeCall(id, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTsGet
* @param template Select templates or instances (optional, default to false)
* @param userId Select the objects relative to the user specified by the parameter. If not specified will be used the id of the current authenticated user (optional)
* @param $top A number of results to return. Applied after **$skip** (optional)
* @param $skip An offset into the collection of results (optional)
* @param $count If true, the server includes the count of all the items in the response (optional)
* @param $orderBy An ordering definition (eg. $orderBy=updatedAt,desc) (optional)
* @param $filter A filter definition (eg. $filter=name == \"Milk\" or surname == \"Bread\") (optional)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The data matching the selection parameters. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTsGetCall(Boolean template, UUID userId, Integer $top, Long $skip, Boolean $count, String $orderBy, String $filter, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/DSTs";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (template != null) {
localVarQueryParams.addAll(localVarApiClient.parameterToPair("template", template));
}
if (userId != null) {
localVarQueryParams.addAll(localVarApiClient.parameterToPair("userId", userId));
}
if ($top != null) {
localVarQueryParams.addAll(localVarApiClient.parameterToPair("$top", $top));
}
if ($skip != null) {
localVarQueryParams.addAll(localVarApiClient.parameterToPair("$skip", $skip));
}
if ($count != null) {
localVarQueryParams.addAll(localVarApiClient.parameterToPair("$count", $count));
}
if ($orderBy != null) {
localVarQueryParams.addAll(localVarApiClient.parameterToPair("$orderBy", $orderBy));
}
if ($filter != null) {
localVarQueryParams.addAll(localVarApiClient.parameterToPair("$filter", $filter));
}
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTsGetValidateBeforeCall(Boolean template, UUID userId, Integer $top, Long $skip, Boolean $count, String $orderBy, String $filter, final ApiCallback _callback) throws ApiException {
okhttp3.Call localVarCall = dSTsGetCall(template, userId, $top, $skip, $count, $orderBy, $filter, _callback);
return localVarCall;
}
/**
* Retrieve DSTs
* This API allows to list the DSTs of an organization.
* @param template Select templates or instances (optional, default to false)
* @param userId Select the objects relative to the user specified by the parameter. If not specified will be used the id of the current authenticated user (optional)
* @param $top A number of results to return. Applied after **$skip** (optional)
* @param $skip An offset into the collection of results (optional)
* @param $count If true, the server includes the count of all the items in the response (optional)
* @param $orderBy An ordering definition (eg. $orderBy=updatedAt,desc) (optional)
* @param $filter A filter definition (eg. $filter=name == \"Milk\" or surname == \"Bread\") (optional)
* @return DSTsGetResponse
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The data matching the selection parameters. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DSTsGetResponse dSTsGet(Boolean template, UUID userId, Integer $top, Long $skip, Boolean $count, String $orderBy, String $filter) throws ApiException {
ApiResponse<DSTsGetResponse> localVarResp = dSTsGetWithHttpInfo(template, userId, $top, $skip, $count, $orderBy, $filter);
return localVarResp.getData();
}
/**
* Retrieve DSTs
* This API allows to list the DSTs of an organization.
* @param template Select templates or instances (optional, default to false)
* @param userId Select the objects relative to the user specified by the parameter. If not specified will be used the id of the current authenticated user (optional)
* @param $top A number of results to return. Applied after **$skip** (optional)
* @param $skip An offset into the collection of results (optional)
* @param $count If true, the server includes the count of all the items in the response (optional)
* @param $orderBy An ordering definition (eg. $orderBy=updatedAt,desc) (optional)
* @param $filter A filter definition (eg. $filter=name == \"Milk\" or surname == \"Bread\") (optional)
* @return ApiResponse<DSTsGetResponse>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The data matching the selection parameters. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DSTsGetResponse> dSTsGetWithHttpInfo(Boolean template, UUID userId, Integer $top, Long $skip, Boolean $count, String $orderBy, String $filter) throws ApiException {
okhttp3.Call localVarCall = dSTsGetValidateBeforeCall(template, userId, $top, $skip, $count, $orderBy, $filter, null);
Type localVarReturnType = new TypeToken<DSTsGetResponse>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Retrieve DSTs (asynchronously)
* This API allows to list the DSTs of an organization.
* @param template Select templates or instances (optional, default to false)
* @param userId Select the objects relative to the user specified by the parameter. If not specified will be used the id of the current authenticated user (optional)
* @param $top A number of results to return. Applied after **$skip** (optional)
* @param $skip An offset into the collection of results (optional)
* @param $count If true, the server includes the count of all the items in the response (optional)
* @param $orderBy An ordering definition (eg. $orderBy=updatedAt,desc) (optional)
* @param $filter A filter definition (eg. $filter=name == \"Milk\" or surname == \"Bread\") (optional)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> The data matching the selection parameters. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTsGetAsync(Boolean template, UUID userId, Integer $top, Long $skip, Boolean $count, String $orderBy, String $filter, final ApiCallback<DSTsGetResponse> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTsGetValidateBeforeCall(template, userId, $top, $skip, $count, $orderBy, $filter, _callback);
Type localVarReturnType = new TypeToken<DSTsGetResponse>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
/**
* Build call for dSTsPost
* @param digitalSignatureTransaction DST to append to the current resources. (required)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 201 </td><td> The new DST added to the list. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTsPostCall(DigitalSignatureTransaction digitalSignatureTransaction, final ApiCallback _callback) throws ApiException {
Object localVarPostBody = digitalSignatureTransaction;
// create path and map variables
String localVarPath = "/DSTs";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json", "*/*"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "OAuth2" };
return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call dSTsPostValidateBeforeCall(DigitalSignatureTransaction digitalSignatureTransaction, final ApiCallback _callback) throws ApiException {
// verify the required parameter 'digitalSignatureTransaction' is set
if (digitalSignatureTransaction == null) {
throw new ApiException("Missing the required parameter 'digitalSignatureTransaction' when calling dSTsPost(Async)");
}
okhttp3.Call localVarCall = dSTsPostCall(digitalSignatureTransaction, _callback);
return localVarCall;
}
/**
* Create a new DST
* This API allows to creates a new DST. A DST is created in the Draft state and then updated using PUT. Example of creation request: ``` { status: \"draft\", publishedAt: null, tags: [], urgent: false, template: false } ``` To add documents use the Resources Patch endpoint `/DST/{id}/resources`. If the *template* flag is set true the DST is a Template. If the *publicTemplate* flag is set true the Template is visible to all users with rights to create a DST. A DST is made made available to users using *publish* end point. A template generates a DST with the *instantiate* endpoint.
* @param digitalSignatureTransaction DST to append to the current resources. (required)
* @return DigitalSignatureTransaction
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 201 </td><td> The new DST added to the list. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public DigitalSignatureTransaction dSTsPost(DigitalSignatureTransaction digitalSignatureTransaction) throws ApiException {
ApiResponse<DigitalSignatureTransaction> localVarResp = dSTsPostWithHttpInfo(digitalSignatureTransaction);
return localVarResp.getData();
}
/**
* Create a new DST
* This API allows to creates a new DST. A DST is created in the Draft state and then updated using PUT. Example of creation request: ``` { status: \"draft\", publishedAt: null, tags: [], urgent: false, template: false } ``` To add documents use the Resources Patch endpoint `/DST/{id}/resources`. If the *template* flag is set true the DST is a Template. If the *publicTemplate* flag is set true the Template is visible to all users with rights to create a DST. A DST is made made available to users using *publish* end point. A template generates a DST with the *instantiate* endpoint.
* @param digitalSignatureTransaction DST to append to the current resources. (required)
* @return ApiResponse<DigitalSignatureTransaction>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 201 </td><td> The new DST added to the list. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public ApiResponse<DigitalSignatureTransaction> dSTsPostWithHttpInfo(DigitalSignatureTransaction digitalSignatureTransaction) throws ApiException {
okhttp3.Call localVarCall = dSTsPostValidateBeforeCall(digitalSignatureTransaction, null);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Create a new DST (asynchronously)
* This API allows to creates a new DST. A DST is created in the Draft state and then updated using PUT. Example of creation request: ``` { status: \"draft\", publishedAt: null, tags: [], urgent: false, template: false } ``` To add documents use the Resources Patch endpoint `/DST/{id}/resources`. If the *template* flag is set true the DST is a Template. If the *publicTemplate* flag is set true the Template is visible to all users with rights to create a DST. A DST is made made available to users using *publish* end point. A template generates a DST with the *instantiate* endpoint.
* @param digitalSignatureTransaction DST to append to the current resources. (required)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 201 </td><td> The new DST added to the list. </td><td> - </td></tr>
<tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr>
<tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr>
<tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr>
<tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr>
</table>
*/
public okhttp3.Call dSTsPostAsync(DigitalSignatureTransaction digitalSignatureTransaction, final ApiCallback<DigitalSignatureTransaction> _callback) throws ApiException {
okhttp3.Call localVarCall = dSTsPostValidateBeforeCall(digitalSignatureTransaction, _callback);
Type localVarReturnType = new TypeToken<DigitalSignatureTransaction>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
}
| 60.017365 | 656 | 0.653386 |
1e95361d4cdb2f25166866f1caf37c66cdd26464 | 730 | package com.ant.ipush.domain;
import lombok.Getter;
public enum BehaviorEvent {
favorites("收藏"), unfavorites("取消收藏"), follow("关注"), unfollow("取消关注"), like("点赞"), cancelLike("取消点赞"), comments("评论"),
purchase("交易待支付"), dailyAttendance("每日签到"), share("分享"),
glance("浏览"), exchange("兑换"), paid("已付"),
birthday("生日"), payRefund("退款"), Festivals("节假日"),
login("登录"), cancelGoods("商品下架"),
New("生成订单"), Shipped("已经发货"), Receive("收货"), Accounted("入账/可提现"), Cancel("取消订单"),
shoppingCart("加入购物车"), cancelShoppingCart("移除购物车"), coupon("优惠卷"), inviteMember("邀请注册会员"), inviteLoginUser("邀请用户登陆"), register("会员注册");
@Getter
String desc;
BehaviorEvent(String desc) {
this.desc = desc;
}
}
| 31.73913 | 139 | 0.631507 |
954e993adcd50542dc436a65ff171d07e83c208f | 2,130 | /*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at http://www.netbeans.org/cddl.html
* or http://www.netbeans.org/cddl.txt.
*
* When distributing Covered Code, include this CDDL Header Notice in each file
* and include the License file at http://www.netbeans.org/cddl.txt.
* If applicable, add the following below the CDDL Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
*/
package org.netbeans.modules.portalpack.servers.core;
import java.io.OutputStream;
import org.netbeans.modules.j2ee.deployment.common.api.ConfigurationException;
import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
import org.netbeans.modules.j2ee.deployment.plugins.spi.config.DeploymentPlanConfiguration;
import org.netbeans.modules.j2ee.deployment.plugins.spi.config.ModuleConfiguration;
import org.openide.util.Lookup;
import org.openide.util.lookup.Lookups;
/**
*
* @author Satyaranjan
*/
public class PSModuleConfiguration implements ModuleConfiguration, DeploymentPlanConfiguration{
private J2eeModule j2eeModule;
private Lookup lookup;
public PSModuleConfiguration(J2eeModule j2eeModule) {
this.j2eeModule = j2eeModule;
createConfiguration();
}
public Lookup getLookup() {
if (null == lookup) {
lookup = Lookups.fixed(this);
}
return lookup;
}
public J2eeModule getJ2eeModule() {
return j2eeModule;
}
public void dispose() {
//DO NOTHING
}
public void createConfiguration()
{
}
public void save(OutputStream outputStream) throws ConfigurationException {
//do nothing.
}
}
| 32.272727 | 95 | 0.72723 |
cd9e8d1094aabf8c31dba6b258a8cffbab9d2542 | 328 | package resources.lang;
import settings.Settings;
import java.util.ResourceBundle;
public class Language {
private static Settings settings = Settings.getInstance();
public static String get(String selector) {
return ResourceBundle.getBundle("resources.lang.lang", settings.lang.getValue()).getString(selector);
}
}
| 20.5 | 103 | 0.777439 |
db49a364ec94a705696960abfb7151fa0f22b202 | 1,413 | package incrementodecremento;
/**
*
* @author Yasmin
*/
public class IncrementoDecremento {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Incremento");
int num1 = 8;
num1++;
System.out.println(num1);
System.out.println("--------------------------");
System.out.println("Decremento");
int num2 = 8;
num2--;
System.out.println(num2);
System.out.println("---------------------------");
System.out.println("Incremento pós variável");
int num3 = 6;
int valor1 = 5 + num3++;
System.out.println(valor1);
System.out.println("---------------------------");
System.out.println("Incremento pré variável");
int num4 = 6;
int valor2 = 5 + ++num4;
System.out.println(valor2);
System.out.println("---------------------------");
System.out.println("Decremento pós variável");
int num5 = 7;
int valor3 = 6 + num5--;
System.out.println(valor3);
System.out.println("---------------------------");
System.out.println("Decremento pré variável");
int num6 = 7;
int valor4 = 6 + --num6;
System.out.println(valor4);
}
}
| 25.690909 | 58 | 0.46143 |
369e61cd00b8949bef17561e3076381e0725e339 | 1,067 | package io.searchbox.indices.mapping;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class GetMappingTest {
@Test
public void testBasicUriGeneration() {
GetMapping getMapping = new GetMapping.Builder().addIndex("twitter").build();
assertEquals("GET", getMapping.getRestMethodName());
assertEquals("twitter/_mapping", getMapping.getURI());
}
@Test
public void equalsReturnsTrueForSameIndex() {
GetMapping getMapping1 = new GetMapping.Builder().addIndex("twitter").build();
GetMapping getMapping1Duplicate = new GetMapping.Builder().addIndex("twitter").build();
assertEquals(getMapping1, getMapping1Duplicate);
}
@Test
public void equalsReturnsFalseForDifferentIndex() {
GetMapping getMapping1 = new GetMapping.Builder().addIndex("twitter").build();
GetMapping getMapping2 = new GetMapping.Builder().addIndex("myspace").build();
assertNotEquals(getMapping1, getMapping2);
}
} | 31.382353 | 95 | 0.712277 |
dc30207a9c0b2aa7f1ba5ac7564b9ecca65bf40a | 3,321 | /*
Copyright 2018 Gaurav Kumar
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.gauravk.audiovisualizer.visualizer;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import com.gauravk.audiovisualizer.base.BaseVisualizer;
/**
* Custom view to create blast visualizer
* <p>
* Created by gk
*/
public class BlastVisualizer extends BaseVisualizer {
private static final int BLAST_MAX_POINTS = 1000;
private static final int BLAST_MIN_POINTS = 3;
private Path mSpikePath;
private int mRadius;
private int nPoints;
public BlastVisualizer(Context context) {
super(context);
}
public BlastVisualizer(Context context,
@Nullable AttributeSet attrs) {
super(context, attrs);
}
public BlastVisualizer(Context context,
@Nullable AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void init() {
mRadius = -1;
nPoints = (int) (BLAST_MAX_POINTS * mDensity);
if (nPoints < BLAST_MIN_POINTS)
nPoints = BLAST_MIN_POINTS;
mSpikePath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
//first time initialization
if (mRadius == -1) {
mRadius = getHeight() < getWidth() ? getHeight() : getWidth();
mRadius = (int) (mRadius * 0.65 / 2);
}
//create the path and draw
if (isVisualizationEnabled && mRawAudioBytes != null) {
if (mRawAudioBytes.length == 0) {
return;
}
mSpikePath.rewind();
double angle = 0;
for (int i = 0; i < nPoints; i++, angle += (360.0f / nPoints)) {
int x = (int) Math.ceil(i * (mRawAudioBytes.length / nPoints));
int t = 0;
if (x < 1024)
t = ((byte) (-Math.abs(mRawAudioBytes[x]) + 128)) * (canvas.getHeight() / 4) / 128;
float posX = (float) (getWidth() / 2
+ (mRadius + t)
* Math.cos(Math.toRadians(angle)));
float posY = (float) (getHeight() / 2
+ (mRadius + t)
* Math.sin(Math.toRadians(angle)));
if (i == 0)
mSpikePath.moveTo(posX, posY);
else
mSpikePath.lineTo(posX, posY);
}
mSpikePath.close();
canvas.drawPath(mSpikePath, mPaint);
}
super.onDraw(canvas);
}
} | 29.389381 | 103 | 0.5676 |
67f208385b17d9f17821df96d69bfdc7de3f1e98 | 544 | package org.bougainvillea.java.designpattern.pattern.creation.factory.no.pizza;
/**
* @Description: pizza 制作过程
* @Author caddy
* @date 2020-02-10 10:26:53
* @version 1.0
*/
public class Pizza {
String name;
public void setName(String name) {
this.name = name;
}
public void prepare(){
}
public void bake(){
System.err.println(name+" bake");
}
public void cut(){
System.err.println(name+" cut");
}
public void box(){
System.err.println(name+" box");
}
}
| 15.542857 | 79 | 0.586397 |
274f307184ceb94a8b845aebbc07a2701127e0c4 | 5,606 | package main;
import java.io.PrintWriter;
import java.util.Date;
import network.DiffusionNetwork;
import network.DiffusionNetworkFactory;
import network.DiffusionNetworkScorer;
import network.Network;
import network.NetworkFactory;
import predictor.ClassifierGuidedKNeighborsPredictorCV;
import predictor.GuidedKNeighborsPredictor;
import predictor.HdPredictor;
import predictor.ICOneStepPredictor;
import utility.Utility;
/**
* This file is modified from Main_PredictorCv.java
* */
@SuppressWarnings("unused")
public class Main_BaselineDiffusionModelCV {
public static double aucAll = 0.0;
public static double aucSDAll = 0.0;
public static double aucCIAll = 0.0;
public static void main(String[] args) throws Exception {
// Test
boolean doTest = true;
// Task
int predictionTask = 1;
// Parameter
int fold = Integer.parseInt(args[3]);
String type =args[0] ;
String hd_type = args[1];
int hd_type_code =-1;
if( hd_type.compareTo("indegree")==0){
hd_type_code = HdPredictor.INDEGREE;
}else if( hd_type.compareTo("outdegree")==0){
hd_type_code = HdPredictor.OUTDEGREE;
}else if( hd_type.compareTo("degree")==0 ){
hd_type_code = HdPredictor.DEGREE;
}
double time = Double.parseDouble(args[2]);
// Parameters
int k = 12;
int d = 1;
int support = 5;
int repeat = 50;
double confidenceLevel = 0.95;
String substring = "";
// Result name
String result = "";
// File names
String trainListFileName = "list/cv" + fold + "_train.txt";
String testListFileName = "list/cv" + fold + "_test.txt";
String relationFileName = "data/plurk_iii/relation_plurk.txt";
// Dataset
String dataset = "plurk";
// Timer start
long startTime = (new Date()).getTime();
System.out.println("Timer start ... ");
// Diffusion Network
System.out.print("Loading networks ... ");
//Network n = new Network();
//n = NetworkFactory.loadRelation(true, n, relationFileName);
DiffusionNetwork dntrain = DiffusionNetworkFactory.getDiffusionNetworkWithContent("dna/dn_cv" + fold + "_train_content.txt");
DiffusionNetwork dn = dntrain;
System.out.println("done.");
// Predictor and parameters
GuidedKNeighborsPredictor p = null;
if( type.compareTo("ic") == 0){
p = new ICOneStepPredictor(dn, dntrain);
result += "basline_"+ type;
}else if( type.compareTo("hd")==0){
p = new HdPredictor(hd_type_code, time, dn, dntrain);
result += "basline_"+ type+ "_type_"+hd_type + "_time_"+time;
}
// Prediction and evaluation
String resultFileName = "result/cv" + fold + "_result" + result + ".txt";
PrintWriter pw = new PrintWriter(resultFileName);
System.out.println();
System.out.println("^Topic^ACC^T^F^AUC^Stdev^95%CI^");
pw.println("^Topic^ACC^T^F^AUC^Stdev^95%CI^");
int[] testConcepts = Utility.loadIntegerArray(testListFileName);
double aucSum = 0.0;
double aucSDSum = 0.0;
double aucCISum = 0.0;
for(int testConcept : testConcepts) {
String positive = "data/" + dataset + "_iii/cv" + fold + "/test/dn_" + testConcept + "_test.txt";
DiffusionNetwork gdn = DiffusionNetworkFactory.getDiffusionNetwork(positive);
DiffusionNetwork pdn = null;
if(predictionTask == 0) {
long[] aggresives = Utility.loadLongArray("data/" + dataset + "_iii/cv" + fold + "/test/aggresive_" + testConcept + "_test.txt");
pdn = p.predict(testConcept, aggresives);
}
else {
String negative = null;
if(predictionTask == 1) {
negative = "data/" + dataset + "_iii/negative/cv" + fold + "/test/unweighted/dn_" + testConcept + "_test.txt";
}
else if(predictionTask == 2) {
negative = "data/" + dataset + "_iii/negative/cv" + fold + "/test/dn_" + testConcept + "_test.txt";
}
DiffusionNetwork testdn = DiffusionNetworkFactory.combineDiffusionNetwork(positive, negative);
pdn = p.predict(testConcept, testdn);
}
DiffusionNetworkScorer dns = new DiffusionNetworkScorer(gdn, pdn, testConcept, repeat, confidenceLevel);
double auc = dns.getAuc();
double aucSD = dns.getAucSD();
double aucCI = dns.getAucCI();
aucSum += auc;
aucSDSum += aucSD;
aucCISum += aucCI;
System.out.printf("|" + testConcept + "|%.2f%%|%.2f%%|%.2f%%|\n", auc*100, aucSD*100, aucCI*100);
pw.printf("|" + testConcept + "|%.2f%%|%.2f%%|%.2f%%|\n", auc*100, aucSD*100, aucCI*100);
}
aucAll = (double)aucSum / (double)testConcepts.length;
aucSDAll = (double)aucSDSum / (double)testConcepts.length;
aucCIAll = (double)aucCISum / (double)testConcepts.length;
System.out.printf("|%d|**%.2f%%**|%.2f%%|%.2f%%|\n", fold, aucAll*100, aucSDAll*100, aucCIAll*100);
pw.printf("|%d|**%.2f%%**|%.2f%%|%.2f%%|\n", fold, aucAll*100, aucSDAll*100, aucCIAll*100);
pw.flush();
pw.close();
// Print parameters
Utility.printStringArray(args, args.length);
// Timer stop
long stopTime = (new Date()).getTime();
long elapsedTime = stopTime - startTime;
System.out.println("Timer stop, elapsed minutes = " + elapsedTime/60000);
}
/**
* @return the aucAll
*/
public static double getAucAll() {
return aucAll;
}
/**
* @return the aucSDAll
*/
public static double getAucSDAll() {
return aucSDAll;
}
/**
* @return the aucCIAll
*/
public static double getAucCIAll() {
return aucCIAll;
}
}
| 32.218391 | 134 | 0.637888 |
5e6cc0f6c51168ddfdc84119c532f6de348d9bc7 | 11,038 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.git.config;
import com.intellij.dvcs.branch.DvcsSyncSettings;
import com.intellij.dvcs.ui.DvcsBundle;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.execution.ParametersListUtil;
import consulo.disposer.Disposable;
import consulo.git.localize.GitLocalize;
import consulo.ide.ui.FileChooserTextBoxBuilder;
import consulo.localize.LocalizeValue;
import consulo.ui.*;
import consulo.ui.annotation.RequiredUIAccess;
import consulo.ui.border.BorderPosition;
import consulo.ui.border.BorderStyle;
import consulo.ui.layout.DockLayout;
import consulo.ui.layout.HorizontalLayout;
import consulo.ui.layout.VerticalLayout;
import consulo.ui.util.LabeledBuilder;
import git4idea.GitVcs;
import git4idea.config.*;
import git4idea.repo.GitRepositoryManager;
import javax.annotation.Nonnull;
import java.util.List;
/**
* Git VCS configuration panel
*/
public class GitVcsPanel
{
private final GitVcsApplicationSettings myAppSettings;
private final GitVcs myVcs;
private final VerticalLayout myRootPanel;
private final FileChooserTextBoxBuilder.Controller myGitField;
private final ComboBox<GitVcsApplicationSettings.SshExecutable> mySSHExecutableComboBox; // Type of SSH executable to use
private final CheckBox myAutoUpdateIfPushRejected;
private final CheckBox mySyncControl;
private final CheckBox myAutoCommitOnCherryPick;
private final CheckBox myWarnAboutCrlf;
private final CheckBox myWarnAboutDetachedHead;
private final CheckBox myEnableForcePush;
private final TextBoxWithExpandAction myProtectedBranchesButton;
private final Label myProtectedBranchesLabel;
private final ComboBox<UpdateMethod> myUpdateMethodComboBox;
@Nonnull
private final Project myProject;
@RequiredUIAccess
public GitVcsPanel(@Nonnull Project project, @Nonnull Disposable uiDisposable)
{
myProject = project;
myVcs = GitVcs.getInstance(project);
myAppSettings = GitVcsApplicationSettings.getInstance();
myRootPanel = VerticalLayout.create();
FileChooserTextBoxBuilder gitPathBuilder = FileChooserTextBoxBuilder.create(project);
gitPathBuilder.uiDisposable(uiDisposable);
gitPathBuilder.dialogTitle(GitLocalize.findGitTitle());
gitPathBuilder.dialogDescription(GitLocalize.findGitDescription());
gitPathBuilder.fileChooserDescriptor(FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor());
myAutoUpdateIfPushRejected = CheckBox.create(LocalizeValue.localizeTODO("Auto-update if &push of the current branch was rejected"));
myEnableForcePush = CheckBox.create(LocalizeValue.localizeTODO("Allow &force push"));
mySyncControl = CheckBox.create(DvcsBundle.message("sync.setting"));
myAutoCommitOnCherryPick = CheckBox.create(LocalizeValue.localizeTODO("Commit automatically on cherry-pick"));
myWarnAboutCrlf = CheckBox.create(LocalizeValue.localizeTODO("Warn if &CRLF line separators are about to be committed"));
myWarnAboutDetachedHead = CheckBox.create(LocalizeValue.localizeTODO("Warn when committing in detached HEAD or during rebase"));
myGitField = gitPathBuilder.build();
mySSHExecutableComboBox = ComboBox.create(GitVcsApplicationSettings.SshExecutable.values());
mySSHExecutableComboBox.setValue(GitVcsApplicationSettings.SshExecutable.IDEA_SSH);
mySSHExecutableComboBox.setTextRender(sshExecutable -> {
switch(sshExecutable)
{
case IDEA_SSH:
return GitLocalize.gitVcsConfigSshModeIdea();
case NATIVE_SSH:
return GitLocalize.gitVcsConfigSshModeNative();
case PUTTY:
return GitLocalize.gitVcsConfigSshModePutty();
default:
throw new IllegalArgumentException(sshExecutable.name());
}
});
myUpdateMethodComboBox = ComboBox.create(UpdateMethod.values());
myUpdateMethodComboBox.selectFirst();
Button testButton = Button.create(GitLocalize.cloneTest());
testButton.addClickListener(e -> testConnection());
final GitRepositoryManager repositoryManager = ServiceManager.getService(project, GitRepositoryManager.class);
mySyncControl.setVisible(repositoryManager != null && repositoryManager.moreThanOneRoot());
myProtectedBranchesLabel = Label.create(LocalizeValue.localizeTODO("Protected branches:"));
myProtectedBranchesButton = TextBoxWithExpandAction.create(AllIcons.Actions.ShowViewer, "Protected Branches", ParametersListUtil.COLON_LINE_PARSER, ParametersListUtil.COLON_LINE_JOINER);
myEnableForcePush.addValueListener(e -> {
myProtectedBranchesButton.setEnabled(myEnableForcePush.getValueOrError());
myProtectedBranchesLabel.setEnabled(myEnableForcePush.getValueOrError());
});
myRootPanel.add(DockLayout.create().left(Label.create(GitLocalize.gitVcsConfigPathLabel())).center(myGitField).right(testButton));
myRootPanel.add(LabeledBuilder.sided(GitLocalize.gitVcsConfigSshMode(), mySSHExecutableComboBox));
myRootPanel.add(mySyncControl);
myRootPanel.add(myAutoCommitOnCherryPick);
myRootPanel.add(myWarnAboutCrlf);
myRootPanel.add(myWarnAboutDetachedHead);
Component updateMethodLabeled = LabeledBuilder.sided(LocalizeValue.localizeTODO("Update method:"), myUpdateMethodComboBox);
updateMethodLabeled.addBorder(BorderPosition.LEFT, BorderStyle.EMPTY, 18);
myRootPanel.add(updateMethodLabeled);
myRootPanel.add(myAutoUpdateIfPushRejected);
myRootPanel.add(DockLayout.create().left(myEnableForcePush).right(HorizontalLayout.create(5).add(myProtectedBranchesLabel).add(myProtectedBranchesButton)));
}
/**
* Test availability of the connection
*/
@RequiredUIAccess
private void testConnection()
{
final String executable = getCurrentExecutablePath();
if(myAppSettings != null)
{
myAppSettings.setPathToGit(executable);
}
UIAccess uiAccess = UIAccess.current();
Task.Backgroundable.queue(myProject, "Checking git version...", true, indicator ->
{
final GitVersion version;
try
{
version = GitVersion.identifyVersion(executable);
}
catch(Exception e)
{
uiAccess.give(() -> Alerts.okInfo(LocalizeValue.of(e.getLocalizedMessage())).title(GitLocalize.findGitErrorTitle()).showAsync(myRootPanel));
return;
}
uiAccess.give(() ->
{
Alert<Object> alert;
if(version.isSupported())
{
alert = Alerts.okInfo(String.format("Git version is %s", version.toString()));
}
else
{
alert = Alerts.okWarning(String.format("This version is unsupported, and some plugin functionality could fail to work. The minimal supported version is '%s'", GitVersion.MIN));
}
alert = alert.title(GitLocalize.findGitSuccessTitle());
alert.showAsync(myRootPanel);
});
});
}
@RequiredUIAccess
private String getCurrentExecutablePath()
{
return myGitField.getValue().trim();
}
/**
* @return the configuration panel
*/
public VerticalLayout getPanel()
{
return myRootPanel;
}
/**
* Load settings into the configuration panel
*
* @param settings the settings to load
*/
@RequiredUIAccess
public void load(@Nonnull GitVcsSettings settings, @Nonnull GitSharedSettings sharedSettings)
{
myGitField.setValue(settings.getAppSettings().getPathToGit());
mySSHExecutableComboBox.setValue(settings.getAppSettings().getSshExecutableType());
myAutoUpdateIfPushRejected.setValue(settings.autoUpdateIfPushRejected());
mySyncControl.setValue(settings.getSyncSetting() == DvcsSyncSettings.Value.SYNC);
myAutoCommitOnCherryPick.setValue(settings.isAutoCommitOnCherryPick());
myWarnAboutCrlf.setValue(settings.warnAboutCrlf());
myWarnAboutDetachedHead.setValue(settings.warnAboutDetachedHead());
myEnableForcePush.setValue(settings.isForcePushAllowed());
myUpdateMethodComboBox.setValue(settings.getUpdateType());
myProtectedBranchesButton.setValue(ParametersListUtil.COLON_LINE_JOINER.fun(sharedSettings.getForcePushProhibitedPatterns()));
}
/**
* Check if fields has been modified with respect to settings object
*
* @param settings the settings to load
*/
@RequiredUIAccess
public boolean isModified(@Nonnull GitVcsSettings settings, @Nonnull GitSharedSettings sharedSettings)
{
return !settings.getAppSettings().getPathToGit().equals(getCurrentExecutablePath()) ||
(settings.getAppSettings().getSshExecutableType() != mySSHExecutableComboBox.getValueOrError()) ||
!settings.autoUpdateIfPushRejected() == myAutoUpdateIfPushRejected.getValueOrError() ||
((settings.getSyncSetting() == DvcsSyncSettings.Value.SYNC) != mySyncControl.getValueOrError() ||
settings.isAutoCommitOnCherryPick() != myAutoCommitOnCherryPick.getValueOrError() ||
settings.warnAboutCrlf() != myWarnAboutCrlf.getValueOrError() ||
settings.warnAboutDetachedHead() != myWarnAboutDetachedHead.getValueOrError() ||
settings.isForcePushAllowed() != myEnableForcePush.getValueOrError() ||
settings.getUpdateType() != myUpdateMethodComboBox.getValueOrError() ||
!ContainerUtil.sorted(sharedSettings.getForcePushProhibitedPatterns()).equals(ContainerUtil.sorted
(getProtectedBranchesPatterns())));
}
/**
* Save configuration panel state into settings object
*
* @param settings the settings object
*/
@RequiredUIAccess
public void save(@Nonnull GitVcsSettings settings, GitSharedSettings sharedSettings)
{
settings.getAppSettings().setPathToGit(getCurrentExecutablePath());
myVcs.checkVersion();
settings.getAppSettings().setIdeaSsh(mySSHExecutableComboBox.getValueOrError());
settings.setAutoUpdateIfPushRejected(myAutoUpdateIfPushRejected.getValueOrError());
settings.setSyncSetting(mySyncControl.getValueOrError() ? DvcsSyncSettings.Value.SYNC : DvcsSyncSettings.Value.DONT_SYNC);
settings.setAutoCommitOnCherryPick(myAutoCommitOnCherryPick.getValueOrError());
settings.setWarnAboutCrlf(myWarnAboutCrlf.getValueOrError());
settings.setWarnAboutDetachedHead(myWarnAboutDetachedHead.getValueOrError());
settings.setForcePushAllowed(myEnableForcePush.getValueOrError());
settings.setUpdateType(myUpdateMethodComboBox.getValueOrError());
sharedSettings.setForcePushProhibitedPatters(getProtectedBranchesPatterns());
}
@Nonnull
@RequiredUIAccess
private List<String> getProtectedBranchesPatterns()
{
return ParametersListUtil.COLON_LINE_PARSER.fun(myProtectedBranchesButton.getValueOrError());
}
}
| 41.340824 | 188 | 0.796974 |
118aa3f9ab58c08a35f5eea59eed7b27435420c7 | 791 | package com.mongo.transactions.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.annotation.Version;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
@Data
@Builder
@Document(collection = "books")
@NoArgsConstructor
@AllArgsConstructor
public class Book {
@Id
private String id;
private String name;
private String genre;
@Version
private Long version;
@CreatedDate
private Date createDate;
@LastModifiedDate
private Date modificationDate;
}
| 20.815789 | 62 | 0.786346 |
016645e5695087c8993201ed34bfb46a811b0216 | 4,132 | /*
* Copyright (C) 2009 [email protected]
*
* The GPG fingerprint for [email protected] is:
* 6DD3 EAA2 9990 29BC 4AD2 7486 1E2C 7B61 76DC DC12
*
* This file is part of I2P-Bote.
* I2P-Bote 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.
*
* I2P-Bote 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 I2P-Bote. If not, see <http://www.gnu.org/licenses/>.
*/
package i2p.bote.service.seedless;
import i2p.bote.I2PBote;
import i2p.bote.network.DhtPeerSource;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.data.Destination;
import net.i2p.util.I2PAppThread;
import net.i2p.util.Log;
/**
* Waits for Seedless to become available and then starts the other Seedless
* background threads (<code>SeedlessAnnounce</code>,
* <code>SeedlessRequestPeers</code>, <code>SeedlessScrapePeers</code>, and
* <code>SeedlessScrapeServers</code>).
* <p/>
* The only reason why this is an <code>I2PBoteThread</code> rather than just a
* <code>Runnable</code> is so it can be handled the same way as all the other
* background threads (see {@link I2PBote}).
*/
public class SeedlessInitializer extends I2PAppThread implements DhtPeerSource {
private Log log = new Log(SeedlessInitializer.class);
private I2PSocketManager socketManager;
private SeedlessAnnounce seedlessAnnounce;
private SeedlessRequestPeers seedlessRequestPeers;
private SeedlessScrapePeers seedlessScrapePeers;
private SeedlessScrapeServers seedlessScrapeServers;
public SeedlessInitializer(I2PSocketManager socketManager) {
super("SeedlessInit");
this.socketManager = socketManager;
}
@Override
public void run() {
SeedlessParameters seedlessParameters = SeedlessParameters.getInstance();
while (!Thread.interrupted()) {
try {
// the following call may take some time
if (seedlessParameters.isSeedlessAvailable()) {
log.info("Seedless found.");
seedlessRequestPeers = new SeedlessRequestPeers(seedlessParameters, 60);
seedlessRequestPeers.start();
seedlessScrapePeers = new SeedlessScrapePeers(seedlessParameters, 10);
seedlessScrapePeers.start();
seedlessScrapeServers = new SeedlessScrapeServers(seedlessParameters, 10);
seedlessScrapeServers.start();
seedlessAnnounce = new SeedlessAnnounce(socketManager, seedlessScrapeServers, 60);
seedlessAnnounce.start();
break;
}
else
log.info("Seedless NOT found. Trying again shortly.");
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
break;
}
}
}
/** Interrupts this and all other Seedless threads */
@Override
public void interrupt() {
if (seedlessAnnounce != null)
seedlessAnnounce.interrupt();
if (seedlessRequestPeers != null)
seedlessRequestPeers.interrupt();
if (seedlessScrapePeers != null)
seedlessScrapePeers.interrupt();
if (seedlessScrapeServers != null)
seedlessScrapeServers.interrupt();
super.interrupt();
}
@Override
public Collection<Destination> getPeers() {
if (seedlessScrapePeers == null)
return Collections.emptyList();
else
return seedlessScrapePeers.getPeers();
}
} | 37.908257 | 102 | 0.663359 |
3d6996e244fb1dae75a2352ea24755a3d8b2d9ad | 1,305 | package com.rwa.services;
import org.concordion.api.FullOGNL;
import org.concordion.cubano.driver.http.HttpEasy;
import org.concordion.cubano.template.AppConfig;
import org.concordion.cubano.template.driver.logger.TestLoggerLogWriter;
import org.concordion.cubano.template.framework.CubanoTemplateFixture;
import org.concordion.ext.StoryboardMarkerFactory;
import org.concordion.ext.storyboard.CardResult;
import org.concordion.ext.storyboard.StockCardImage;
import org.concordion.slf4j.ext.MediaType;
import org.concordion.slf4j.ext.ReportLogger;
import org.concordion.slf4j.ext.ReportLoggerFactory;
@FullOGNL
public class BaseService {
protected ReportLogger log = ReportLoggerFactory.getReportLogger(BankAccountService.class);
protected HttpEasy easy = HttpEasy.request().baseUrl(AppConfig.getInstance().getApiUrl());
protected TestLoggerLogWriter testLoggerLogWriter = new TestLoggerLogWriter();
protected void addNotification(String name, String data) {
log
.with()
.message(name)
.attachment(data, name + ".json", MediaType.PLAIN_TEXT)
.marker(StoryboardMarkerFactory.addCard(
name,
StockCardImage.JSON, CardResult.SUCCESS))
.debug();
}
}
| 39.545455 | 95 | 0.732567 |
244104b089942bfd8f8dc1df8ae6f46978ed5f9f | 5,585 | /*
* Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
*
* License for BK-BASE 蓝鲸基础平台:
* --------------------------------------------------------------------
* 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.tencent.bk.base.dataflow.spark.sql.topology.builder.udfdebug;
import com.tencent.bk.base.dataflow.spark.sql.topology.BatchSQLJavaEnumerations.BatchSQLType;
import com.tencent.bk.base.dataflow.spark.sql.topology.BatchSQLTopology;
import com.tencent.bk.base.dataflow.spark.sql.topology.builder.sqldebug.SQLDebugTopoBuilder;
import com.tencent.bk.base.dataflow.spark.topology.BatchTopology.AbstractBatchTopologyBuilder;
import com.tencent.bk.base.dataflow.core.topo.Node;
import com.tencent.bk.base.dataflow.spark.topology.nodes.sink.BatchDebugHTTPSinkNode;
import com.tencent.bk.base.dataflow.spark.topology.nodes.source.BatchJsonSourceNode;
import com.tencent.bk.base.dataflow.spark.topology.nodes.transform.BatchSQLTransformNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class UDFDebugTopoBuilder extends AbstractBatchTopologyBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(SQLDebugTopoBuilder.class);
public UDFDebugTopoBuilder(Map<String, Object> parameters) {
super(parameters);
this.enableMetrics = false;
buildNodes(parameters);
this.fillNodesFromSinkParents();
Map<String, Object> udfMap = (Map<String, Object>)parameters.get("udf");
this.buildUDF(udfMap);
}
private void buildNodes(Map<String, Object> parameters) {
Map<String, Object> udfMap = (Map<String, Object>)parameters.get("udf");
Map<String, Object> nodesConfMap = (Map<String, Object>)parameters.get("nodes");
Map<String, Object> sourceNodesConfMap = (Map<String, Object>)nodesConfMap.get("source");
List<Node> sourceNodeList = new LinkedList<>();
Map<String, Object> sourceConf =
(Map<String, Object>)sourceNodesConfMap.entrySet().stream().findFirst().get().getValue();
List<Map<String, Object>> sourceData = (List<Map<String, Object>>)udfMap.get("source_data");
sourceConf.put("source_data", sourceData);
BatchJsonSourceNode jsonSourceNode =
(new BatchJsonSourceNode.BatchJsonSourceNodeBuilder(sourceConf)).build();
sourceNodeList.add(jsonSourceNode);
Map<String, Object> transformNodesConfMap = (Map<String, Object>)nodesConfMap.get("transform");
Map<String, Object> transformParameters =
(Map<String, Object>)transformNodesConfMap.entrySet().stream().findFirst().get().getValue();
Map<String, Object> transformConf = new HashMap<>();
String transformNodeId = transformParameters.get("id").toString();
transformConf.put("id", transformNodeId);
transformConf.put("name", transformParameters.get("name").toString());
Map<String, Object> processorConf = (Map<String, Object>)transformParameters.get("processor");
transformConf.put("sql", processorConf.get("processor_args").toString());
BatchSQLTransformNode transformNode =
(new BatchSQLTransformNode.BatchSQLTransformNodeBuilder(transformConf)).build();
transformNode.setParents(sourceNodeList);
List<Node> transformNodeList = new LinkedList<>();
transformNodeList.add(transformNode);
Map<String, Object> debugHttpSinkConf = new HashMap<>();
debugHttpSinkConf.put("id", transformNodeId);
debugHttpSinkConf.put("name", transformNodeId);
debugHttpSinkConf.put("debug_id", this.getJobId());
debugHttpSinkConf.put("execute_id", this.executeId);
debugHttpSinkConf.put("enable_throw_exception", true);
BatchDebugHTTPSinkNode debugHTTPSinkNode =
new BatchDebugHTTPSinkNode.BatchDebugHTTPSinkNodeBuilder(debugHttpSinkConf).build();
debugHTTPSinkNode.setParents(transformNodeList);
this.sinkNodes.put(transformNodeId, debugHTTPSinkNode);
}
@Override
public BatchSQLTopology build() {
this.fillNodesFromSinkParents();
BatchSQLTopology batchSQLTopology = new BatchSQLTopology(this);
batchSQLTopology.setBatchType(BatchSQLType.UDF_DEBUG);
return batchSQLTopology;
}
}
| 52.196262 | 114 | 0.726768 |
7020fb9ca0bcdc38719c5151dc64f9dc656e5c62 | 2,299 | package foodguide.controller;
import foodguide.model.Gender;
import javax.validation.constraints.NotBlank;
/**
* A POJO that parses the name-gender-age identification string used by the
* controller to identify a person.
*/
public class Identification {
public final String name;
public final Gender gender;
public final int age;
public Identification(final String name, final Gender gender, final int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
/**
* Identification is parsed from the pattern:
* <p>
* <code>
* $NAME-$GENDER-$AGE
* </code>
* <p>
* For example, <code>Steve:M:29</code> or <code>April%20ONneal:F:32</code>
*
* @param idString The raw id string
* @return The parsed object
*/
public static Identification parse(@NotBlank String idString) throws BadIdentificationException {
final String[] parts = idString.split(":");
if (parts.length == 3) {
// Parse the name
final String name = parts[0];
// Parse the gender
final Gender gender;
if ("M".equalsIgnoreCase(parts[1])) {
gender = Gender.Male;
} else if ("F".equalsIgnoreCase(parts[1])) {
gender = Gender.Female;
} else {
throw new BadIdentificationException(String.format("No gender matches %s. Expected one of 'M' or 'F'.", parts[1]));
}
// Parse the age
final int age = parseAge(parts[2]);
return new Identification(name, gender, age);
}
throw new BadIdentificationException("Expected <name>:<Gender>:<age> such as \"Steve:M:25\"");
}
private static int parseAge(final String ageString) throws BadIdentificationException {
try {
final int age = Integer.parseUnsignedInt(ageString);
if (age < 2) {
throw new BadIdentificationException(String.format("Age must be greater than or equal to 0, but was '%s'.", ageString));
}
return age;
} catch (NumberFormatException ex) {
throw new BadIdentificationException(String.format("Cannot read age - %s", ex.getMessage()));
}
}
}
| 32.842857 | 136 | 0.593301 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.