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
|
---|---|---|---|---|---|
14cff77cc0c98ddd010c10629805fa074f5255f9 | 2,976 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.mavenrepositorymanager;
import org.commonjava.aprox.client.core.Aprox;
import org.commonjava.aprox.model.core.Group;
import org.commonjava.aprox.model.core.StoreKey;
import org.commonjava.aprox.model.core.StoreType;
import org.jboss.pnc.mavenrepositorymanager.fixture.TestBuildExecution;
import org.jboss.pnc.spi.repositorymanager.BuildExecution;
import org.jboss.pnc.spi.repositorymanager.model.RepositorySession;
import org.jboss.pnc.test.category.ContainerTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import static org.apache.commons.lang.StringUtils.join;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
@Category(ContainerTest.class)
public class BuildGroupIncludesProductVersionGroupTest extends AbstractRepositoryManagerDriverTest {
@Test
public void verifyGroupComposition_ProductVersion_NoConfSet() throws Exception {
// create a dummy non-chained build execution and repo session based on it
BuildExecution execution = new TestBuildExecution("build_myproject_12345");
Aprox aprox = driver.getAprox();
RepositorySession repositoryConfiguration = driver.createBuildRepository(execution);
String repoId = repositoryConfiguration.getBuildRepositoryId();
assertThat(repoId, equalTo(execution.getBuildContentId()));
// check that the build group includes:
// - the build's hosted repo
// - the product version repo group
// - the "shared-releases" repo group
// - the "shared-imports" repo
// - the public group
// ...in that order
Group buildGroup = aprox.stores().load(StoreType.group, repoId, Group.class);
System.out.printf("Constituents:\n %s\n", join(buildGroup.getConstituents(), "\n "));
assertGroupConstituents(buildGroup, new StoreKey(StoreType.hosted, execution.getBuildContentId()),
new StoreKey(StoreType.group,
MavenRepositoryConstants.UNTESTED_BUILDS_GROUP), new StoreKey(StoreType.hosted,
MavenRepositoryConstants.SHARED_IMPORTS_ID), new StoreKey(StoreType.group,
MavenRepositoryConstants.PUBLIC_GROUP_ID));
}
}
| 44.41791 | 106 | 0.739583 |
373c47b60df33aef05246a0bda77a49831a58a0b | 1,943 | package io.gitlab.allenb1.todolist;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.Window;
import java.io.IOException;
import java.util.function.Function;
public class TaskHelper {
public static interface DeleteCallback {
public void ondelete(TodoTask task);
}
public static void deleteTask(final Activity ctx, final TodoTask.TodoList todoList, final int position, final DeleteCallback ondelete) {
final TodoTask task = todoList.get(position);
AlertDialog dialog = new AlertDialog.Builder(ctx)
.setTitle(R.string.dialog_delete_title)
.setMessage(R.string.dialog_delete_message)
.setPositiveButton(R.string.dialog_delete_button_delete, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int i) {
try {
todoList.remove(position);
todoList.save();
if(ondelete != null)
ondelete.ondelete(task);
} catch(IOException e) {
Snackbar.make(ctx.findViewById(android.R.id.content), R.string.generic_error, Snackbar.LENGTH_LONG).show();
}
}
})
.setNegativeButton(R.string.dialog_button_cancel, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int i) {
dialog.cancel();
}
})
.create();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.show();
}
}
| 38.86 | 140 | 0.602162 |
25b7c227f09f0279f1f29c9c05d09c507a02f656 | 645 | package org.rjava.test;
import org.rjava.restriction.rulesets.RJavaCore;
@RJavaCore
public class RJavaDynamicLoading {
int i;
float f;
static {
String a = "test";
}
public static void main(String[] args) {
double d = 0;
for (int i = 0; i < 5; i++) {
d += i;
}
RJavaDynamicLoading symTab = new RJavaDynamicLoading();
symTab.foo(args);
}
public void foo(Object... objects) {
try{
Class a = Class.forName("java.lang.Object");
Class b = ClassLoader.getSystemClassLoader().loadClass("java.lang.Object");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| 20.806452 | 84 | 0.624806 |
4d3a9f1ddf528adf388b2eb04e0d85776ed6986e | 1,012 | package org.ddljen;
public class Column extends AbstractSchemaObject {
private DataType dataType = null;
private boolean nullable = true;
private boolean autoIncrement = false;
private boolean unique = false;
private String description = null;
public Column() {
}
public Column(String name) {
super(name);
}
public DataType getDataType() {
return dataType;
}
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
public boolean isAutoIncrement() {
return autoIncrement;
}
public void setAutoIncrement(boolean autoIncrement) {
this.autoIncrement = autoIncrement;
}
public boolean isNullable() {
return nullable;
}
public void setNullable(boolean nullable) {
this.nullable = nullable;
}
public boolean isUnique() {
return unique;
}
public void setUnique(boolean unique) {
this.unique = unique;
}
public String getDescription() {
return description;
}
public void setDescription(String desc) {
this.description = desc;
}
}
| 16.590164 | 54 | 0.721344 |
ddec5ac52245ebb4ef9367818e3592e2142d1a2a | 901 | package com.fun.learning.DynamicProgramming;
import java.math.BigInteger;
import java.util.Scanner;
public class SubStringWithString {
static BigInteger substrings(String balls) {
BigInteger sum = new BigInteger("0");
while (balls.length() > 0) {
int i = balls.length();
while (i > 0) {
String innerBalls = balls.substring(0, i);
BigInteger ballsNum = new BigInteger(innerBalls);
sum = sum.add(ballsNum);
i--;
}
balls = balls.substring(1, balls.length());
}
return (sum.mod(new BigInteger("1000000007")));
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String balls = in.next();
BigInteger result = substrings(balls);
System.out.println(result);
in.close();
}
}
| 27.30303 | 65 | 0.563818 |
c8618935588802b22d59c875fb2aef723ac1ad7d | 1,181 | package com.twu.biblioteca;
import com.twu.biblioteca.constants.BibliotecaBooksList;
import com.twu.biblioteca.service.BibliotecaService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
public class ExampleTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
BibliotecaService bibliotecaService = new BibliotecaService();
@Test
public void test() {
assertEquals(1, 1);
}
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@After
public void cleanUpStreams() {
System.setOut(null);
}
@Test
public void applicationStartShowsWelcomeMessage() {
bibliotecaService.showWelcomeMessage();
assertEquals("Welcome to Bangalore library!", outContent.toString());
}
@Test
public void applicationShowsBooksListAfterWelcomeMessage() {
bibliotecaService.showBooksList();
assertEquals(BibliotecaBooksList.libraryBooksList.toString(), outContent.toString());
}
}
| 24.102041 | 93 | 0.723116 |
65d9f7c1342cdd87f0f9f15bf28410635c17c795 | 7,018 | package com.tle.jpfclasspath;
import com.tle.jpfclasspath.model.IPluginModel;
import com.tle.jpfclasspath.model.IResolvedPlugin;
import com.tle.jpfclasspath.model.JPFPluginModelManager;
import com.tle.jpfclasspath.model.JPFProject;
import com.tle.jpfclasspath.model.ResolvedImport;
import com.tle.jpfclasspath.parser.ModelPluginManifest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
public class JPFManifestBuilder extends IncrementalProjectBuilder {
public static final String BUILDER_ID = JPFClasspathPlugin.PLUGIN_ID + ".manifestBuilder";
class ManifestVisitor implements IResourceDeltaVisitor {
boolean manifestChanged = false;
public void reset() {
manifestChanged = false;
}
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
if (resource.isDerived()) {
return false;
}
if (resource.getType() == IResource.FILE) {
IFile file = (IFile) resource;
IProject project = resource.getProject();
if (file.equals(JPFProject.getManifest(project))) {
manifestChanged = true;
return false;
}
}
return true;
}
}
private ManifestVisitor manifestVisitor = new ManifestVisitor();
@Override
protected IProject[] build(int kind, Map<String, String> args, IProgressMonitor monitor)
throws CoreException {
IProject project = getProject();
IResourceDelta delta = getDelta(project);
boolean doValidate = false;
if (delta == null) {
doValidate = true;
} else {
if (Boolean.TRUE.equals(project.getSessionProperty(JPFClasspathPlugin.TOUCH_PROJECT))) {
project.setSessionProperty(JPFClasspathPlugin.TOUCH_PROJECT, null);
doValidate = true;
} else {
manifestVisitor.reset();
delta.accept(manifestVisitor);
doValidate = manifestVisitor.manifestChanged;
}
}
if (doValidate) {
validateManifest(project);
}
return null;
}
private void validateManifest(IProject project) {
IFile manifestFile = JPFProject.getManifest(project);
try {
cleanProblems(manifestFile, IResource.DEPTH_ZERO);
} catch (CoreException e1) {
// whatevs
}
IPluginModel model = JPFPluginModelManager.instance().findModel(project);
if (model != null) {
ModelPluginManifest parsedManifest = model.getParsedManifest();
if (parsedManifest == null) {
reportError(manifestFile, "Error parsing manifest");
return;
}
IResolvedPlugin resolvedPlugin = JPFPluginModelManager.instance().getResolvedPlugin(model);
if (resolvedPlugin == null) {
reportError(manifestFile, "Manifest not registered");
return;
}
List<ResolvedImport> imports = resolvedPlugin.getImports();
for (ResolvedImport resolvedImport : imports) {
IResolvedPlugin resolved = resolvedImport.getResolved();
if (resolved.getPluginModel() == null && !resolvedImport.getPrerequisite().isOptional()) {
String missingId = resolvedImport.getPrerequisite().getPluginId();
reportError(
manifestFile,
"Plugin '"
+ missingId
+ "' cannot be found in registry '"
+ resolvedPlugin.getRegistryName()
+ "'");
}
}
}
}
private void reportError(IResource resource, String message) {
try {
IMarker marker = resource.createMarker(JPFClasspathPlugin.MARKER_ID);
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.LINE_NUMBER, 1);
} catch (CoreException e) {
// nothing
}
}
/*
* (non-Javadoc)
* @see
* org.eclipse.core.resources.IncrementalProjectBuilder#clean(org.eclipse
* .core.runtime.IProgressMonitor)
*/
@Override
protected void clean(IProgressMonitor monitor) throws CoreException {
SubMonitor localmonitor = SubMonitor.convert(monitor, "JPF Manifest validation", 1);
try {
// clean problem markers on the project
cleanProblems(getProject(), IResource.DEPTH_ZERO);
// clean the manifest directory (since errors can be created on
// manifest files with incorrect casing)
IFile manifestFile = JPFProject.getManifest(getProject());
cleanProblems(manifestFile.getParent(), IResource.DEPTH_ONE);
localmonitor.worked(1);
} finally {
localmonitor.done();
}
}
private void cleanProblems(IResource resource, int depth) throws CoreException {
if (resource.exists()) {
resource.deleteMarkers(JPFClasspathPlugin.MARKER_ID, true, depth);
}
}
public static void addBuilderToProject(IProjectDescription description) {
if (hasBuilder(description)) {
return;
}
// Associate builder with project.
ICommand[] cmds = description.getBuildSpec();
ICommand newCmd = description.newCommand();
newCmd.setBuilderName(BUILDER_ID);
List<ICommand> newCmds = new ArrayList<ICommand>();
newCmds.addAll(Arrays.asList(cmds));
newCmds.add(newCmd);
description.setBuildSpec(newCmds.toArray(new ICommand[newCmds.size()]));
}
public static boolean hasBuilder(IProjectDescription description) {
// Look for builder.
ICommand[] cmds = description.getBuildSpec();
for (int j = 0; j < cmds.length; j++) {
if (cmds[j].getBuilderName().equals(BUILDER_ID)) {
return true;
}
}
return false;
}
public static void removeBuilderFromProject(IProjectDescription description) {
// Look for builder.
int index = -1;
ICommand[] cmds = description.getBuildSpec();
for (int j = 0; j < cmds.length; j++) {
if (cmds[j].getBuilderName().equals(BUILDER_ID)) {
index = j;
break;
}
}
if (index == -1) return;
// Remove builder from project.
List<ICommand> newCmds = new ArrayList<ICommand>();
newCmds.addAll(Arrays.asList(cmds));
newCmds.remove(index);
description.setBuildSpec(newCmds.toArray(new ICommand[newCmds.size()]));
}
public static void deleteMarkers(IProject project) {
try {
project.deleteMarkers(JPFClasspathPlugin.MARKER_ID, true, IResource.DEPTH_INFINITE);
} catch (CoreException e) {
// who cares
}
}
}
| 33.740385 | 98 | 0.689228 |
f7769c27cc5d8b5aac7540eca39c64c2e2f82cb9 | 596 | package org.xdef;
import org.xdef.sys.Report;
import org.xdef.sys.SRuntimeException;
import org.xdef.sys.ReportReader;
/** XD input stream/report reader in x-script.
* @author Vaclav Trojan
*/
public interface XDInput extends XDValue {
/** Reset input stream.
* @throws SRuntimeException if an error occurs.
*/
public void reset() throws SRuntimeException;
public Report getReport();
public String readString();
public String readStream();
public void close();
public boolean isOpened();
/** Get reader.
* @return report reader.
*/
public ReportReader getReader();
}
| 18.060606 | 49 | 0.724832 |
8b1809c26410d2eca27603b32a5fab3eae2674b6 | 9,700 | package cn.wizzer.modules.controllers.platform.losys;
import cn.apiclub.captcha.filter.image.TextureFilter;
import cn.wizzer.common.annotation.SLog;
import cn.wizzer.common.base.Result;
import cn.wizzer.common.filter.PrivateFilter;
import cn.wizzer.common.page.DataTableColumn;
import cn.wizzer.common.page.DataTableOrder;
import cn.wizzer.modules.models.losys.Lo_area;
import cn.wizzer.modules.models.losys.Lo_logistics;
import cn.wizzer.modules.models.sys.Sys_menu;
import cn.wizzer.modules.models.sys.Sys_unit;
import cn.wizzer.modules.services.losys.LosysAreaService;
import cn.wizzer.modules.services.losys.LosysLogisticsService;
import cn.wizzer.modules.services.sys.SysMenuService;
import cn.wizzer.modules.services.sys.SysUnitService;
import cn.wizzer.modules.services.sys.SysUserService;
import oracle.net.aso.a;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.*;
import org.nutz.dao.Chain;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.adaptor.WhaleAdaptor;
import org.nutz.mvc.annotation.*;
import com.mysql.fabric.xmlrpc.base.Data;
@IocBean
@At("/platform/losys/area")
@Filters({@By(type = PrivateFilter.class)})
public class LosysAreaController {
private static final Log log = Logs.get();
@Inject
private LosysAreaService areaService;
/**
* 访问区域管理模块首页
*/
@At("")
@Ok("beetl:/platform/losys/area/index.html")
@RequiresAuthentication
public void index(HttpServletRequest req) {
List<Lo_area> area = areaService.query(Cnd.where("pid", "=", "").asc("opAt"));
req.setAttribute("list", area);
}
/**
* 访问区域管理模块添加区域页面
*/
@At
@Ok("beetl:/platform/losys/area/add.html")
@RequiresAuthentication
public Object add(@Param("pid") String pid, HttpServletRequest req) {
return Strings.isBlank(pid) ? null : areaService.fetch(pid);
}
/**
* 访问区域管理模块修改区域页面
*/
@At("/edit/?")
@Ok("beetl:/platform/losys/area/edit.html")
@RequiresPermissions("area.manage.edit")
public Object edit(String id,HttpServletRequest req) {
Lo_area area = areaService.fetch(id);
if (area.getPid() != null) {
Lo_area area2 = areaService.fetch(area.getPid());
req.setAttribute("areaP", area2);
}
req.setAttribute("area", area);
return area;
}
/**
* 添加区域
*/
@At
@Ok("json")
@RequiresPermissions("area.manage.add")
@SLog(tag = "添加区域", msg = "区域名称:${args[0].name}")
@AdaptBy(type = WhaleAdaptor.class)
public Object addDo(@Param("..") Lo_area area, HttpServletRequest req) {
try {
if(area.getPid()!= null && !area.getPid().equals("")) {
Lo_area areaTop = areaService.fetch(area.getPid());
areaTop.setHasChild("1");
areaService.update(areaTop);
if (areaTop.getPath() != null && areaTop.getPath() != "") {
area.setPath(areaTop.getPath() + areaTop.getId() + "-");
}else {
area.setPath(areaTop.getId() + "-");
}
}
area.setHasChild("0");
area.setOpAt((int)System.currentTimeMillis());
area.setDelFlag(false);
areaService.insert(area);
return Result.success("system.success");
} catch (Exception e) {
return Result.error("system.error");
}
}
/**
* 删除区域
*/
@At({"/delete/?", "/delete"})
@Ok("json")
@RequiresPermissions("area.manage.delete")
public Object delete(String id, HttpServletRequest req) {
try {
//查询出所有子节点
List<Lo_area> list = areaService.query(Cnd.where("pid", "=", id).or("path","like","%"+id + "-%"));
//修改上级节点
Lo_area area = areaService.fetch(id);
areaService.delete(id);
if (area.getPid() != null || !area.getPid().equals("")) {
List<Lo_area> areas = areaService.query(Cnd.where("pid", "=", area.getPid()));
if (areas.size()<1) {
areaService.dao().update(Lo_area.class, Chain.make("hasChild", 0), Cnd.where("id","=",area.getPid()));
}
}
if (list.size()>0) {
for (Lo_area lo_area : list) {
areaService.delete(lo_area.getId());
}
}
return Result.success("system.success");
} catch (Exception e) {
return Result.error("system.error");
}
}
/**
* 修改区域
*/
@At
@Ok("json")
@RequiresPermissions("area.manage.edit")
@SLog(tag = "修改区域", msg = "区域名称:${args[0].name}")
@AdaptBy(type = WhaleAdaptor.class)
public Object editDo(@Param("..") Lo_area area, HttpServletRequest req) {
try {
areaService.update(area);
return Result.success("system.success");
} catch (Exception e) {
return Result.error("system.error");
}
}
/**
* 查询数据
*/
@At
@Ok("json:full")
@RequiresAuthentication
public Object data() {
List<Lo_area> list = areaService.query(Cnd.where("pid", "is", null).asc("opAt"));
List<Map<String, Object>> tree = new ArrayList<>();
for (Lo_area area : list) {
Map<String, Object> obj = new HashMap<>();
obj.put("id", area.getId());
obj.put("name", area.getName());
obj.put("children", area.getHasChild());
tree.add(obj);
}
return tree;
}
@At("/child/?")
@Ok("beetl:/platform/losys/area/child.html")
@RequiresAuthentication
public Object child(String id) {
// Lo_area m = areaService.fetch(id);
// List<Lo_area> list = new ArrayList<>();
List<Lo_area> list = areaService.query(Cnd.where("pid", "=", id).asc("opAt"));
// for (Lo_area area : menus) {
// for (Lo_area bt : datas) {
// if (menu.getPath().equals(bt.getPath().substring(0, bt.getPath().length() - 4))) {
// menu.setHasChildren(true);
// break;
// }
// }
// list.add(menu);
// }
return list;
}
@At
@Ok("json")
@RequiresAuthentication
public Object tree(@Param("pid") String pid) {
List<Lo_area> list = areaService.query(Cnd.where("pid", "=", Strings.sBlank(pid)).asc("opAt"));
List<Map<String, Object>> tree = new ArrayList<>();
for (Lo_area area : list) {
Map<String, Object> obj = new HashMap<>();
obj.put("id", area.getId());
obj.put("text", area.getName());
if(area.getHasChild().equals("1")) {
obj.put("children", true);
}else {
obj.put("children", false);
}
tree.add(obj);
}
return tree;
}
@At("/intoArea")
@Ok("json")
@RequiresAuthentication
public Object intoArea()
{
File csv = new File("F:\\China.csv"); // CSV文件路径
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(csv));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
String line = "";
String everyLine = "";
int count = 1;
int one = 0;
try {
List<String> allString = new ArrayList<>();
String shengId ="";
String shiId = "";
while ((line = br.readLine()) != null) //读取到的内容给line变量
{
if(one==0) {
one += 1;
continue;
}
String[] areas = line.split(",");
Lo_area area = new Lo_area();
if(areas.length==2) { //省
shengId = String.valueOf(count);
area.setHasChild("1");
area.setName(areas[1]);
area.setPid("");
area.setPath("");
}else if (areas.length==3 || areas.length==5) { //市
shiId = String.valueOf(count);
area.setHasChild("1");
area.setName(areas[2]);
area.setPid(shengId);
area.setPath(shengId+"-");
}else { //区
if(areas[3].equals("")) {
shiId = String.valueOf(count);
area.setHasChild("1");
area.setName(areas[2]);
area.setPid(shengId);
area.setPath(shengId+"-");
} else {
area.setHasChild("0");
area.setName(areas[3]);
area.setPid(shiId);
area.setPath(shengId+"-"+shiId+"-");
}
}
areaService.insert(area);
count += 1;
}
System.out.println("csv表格中所有行数:"+count);
} catch (IOException e)
{
e.printStackTrace();
}
return "ok";
}
}
| 30.3125 | 110 | 0.573711 |
46b2db2b9c3600a03dc45898d7564280596adaf7 | 53 | package com.tw.parking.boy;
public class Ticket {
}
| 10.6 | 27 | 0.735849 |
cddf224b6963b759f52ac04212c38a506d42a649 | 661 | package com.github.sparkzxl.alarm.annotation;
import com.github.sparkzxl.alarm.constant.enums.MessageTye;
import java.lang.annotation.*;
/**
* description: 告警注解
*
* @author zhouxinlei
* @date 2021-12-28 09:02:31
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Alarm {
/**
* 报警名称
*
* @return String
*/
String name() default "";
MessageTye messageType() default MessageTye.TEXT;
String templateId() default "";
String extractParams() default "";
/**
* 表达式条件
*
* @return String
*/
String expressionJson() default "";
}
| 16.121951 | 59 | 0.641452 |
de6b99c5805ac9afc3a69f6e11f59ae823fb2250 | 831 | package gnova.geometry.model.operator;
import gnova.core.annotation.NotNull;
import gnova.geometry.model.Coordinate;
import gnova.geometry.model.Geometry;
/**
* 空间距离操作
*
* Created by Birderyu on 2017/6/22.
*/
public interface ProximityOperator {
/**
* 获取与另一个几何对象的最短距离
*
* @param other
* @return
*/
double distance(@NotNull Geometry other);
/**
* 判断与另一个几何对象的距离是否不大于指定的长度
*
* @param other
* @param distance
* @return
*/
boolean isWithinDistance(@NotNull Geometry other, double distance);
/**
* 获取与另一个几何对象的最短点
*
* @param other
* @return 返回一个坐标数组,其中包含两个元素,
* 第一个元素是当前几何对象上距离另一个几何对象距离最近的坐标,
* 第二个元素是另一个几何对象上距离当前几何对象距离最近的坐标,
*/
@NotNull
Coordinate[] nearestPoints(@NotNull Geometry other);
}
| 19.785714 | 71 | 0.629362 |
6b89ffb0d8a7cc50b12834b2d6884390b4d9afd0 | 6,609 | package org.aio.activities.skills.mining;
import org.aio.activities.activity.Activity;
import org.aio.activities.activity.ActivityType;
import org.aio.activities.banking.Banking;
import org.aio.util.Executable;
import org.aio.util.ResourceMode;
import org.aio.util.Sleep;
import org.osbot.rs07.api.filter.AreaFilter;
import org.osbot.rs07.api.map.Area;
import org.osbot.rs07.api.model.Entity;
import org.osbot.rs07.api.ui.EquipmentSlot;
import java.util.*;
public class MiningActivity extends Activity {
private final Mine mine;
private final Rock rock;
private final ResourceMode resourceMode;
private final EnumSet<Pickaxe> pickaxesInBank = EnumSet.noneOf(Pickaxe.class);
private final List<String> cutGems = Arrays.asList("Opal", "Jade", "Red topaz", "Sapphire", "Emerald", "Ruby", "Diamond", "Dragonstone", "Onyx");
private final List<String> uncutGems = Arrays.asList("Uncut opal", "Uncut jade", "Uncut red topaz", "Uncut sapphire", "Uncut emerald", "Uncut ruby", "Uncut diamond", "Uncut dragonstone", "Uncut onyx");
protected Pickaxe currentPickaxe;
private boolean checkedBankForPickaxes;
protected Executable miningNode, bankNode;
public MiningActivity(final Mine mine, final Rock rock, final ResourceMode resourceMode) {
super(ActivityType.MINING);
this.mine = mine;
this.rock = rock;
this.resourceMode = resourceMode;
}
@Override
public void onStart() {
// On activity start get the best pickaxe the player can use, and has in their inventory or equipment
getCurrentPickaxe();
miningNode = new MiningNode();
miningNode.exchangeContext(getBot());
bankNode = new ItemReqBankingImpl();
bankNode.exchangeContext(getBot());
}
protected void getCurrentPickaxe() {
currentPickaxe = Arrays.stream(Pickaxe.values())
.filter(pickaxe -> pickaxe.canUse(getSkills()))
.filter(pickaxe -> getInventory().contains(pickaxe.name) || getEquipment().isWearingItem(EquipmentSlot.WEAPON, pickaxe.name))
.max(Comparator.comparingInt(Pickaxe::getLevelRequired))
.orElse(null);
}
@Override
public void runActivity() throws InterruptedException {
if (currentPickaxe == null || !checkedBankForPickaxes || bankContainsBetterPickaxe() || inventoryContainsNonMiningItem() || (getInventory().isFull() && resourceMode == ResourceMode.BANK)) {
doBanking();
} else if (getBank() != null && getBank().isOpen()) {
getBank().close();
} else if (currentPickaxe.canEquip(getSkills()) && !getEquipment().isWearingItem(EquipmentSlot.WEAPON, currentPickaxe.name)) {
if (getInventory().getItem(currentPickaxe.name).interact("Wield")) {
Sleep.sleepUntil(() -> getEquipment().isWearingItem(EquipmentSlot.WEAPON, currentPickaxe.name), 2000);
}
} else if (getInventory().isFull() && resourceMode == ResourceMode.DROP) {
getInventory().dropAll(item -> !item.getName().equals(currentPickaxe.name));
} else {
mine();
}
}
private boolean bankContainsBetterPickaxe() {
return pickaxesInBank.stream().anyMatch(pickaxe -> pickaxe.canUse(getSkills()) && pickaxe.getLevelRequired() > currentPickaxe.getLevelRequired());
}
protected boolean inventoryContainsNonMiningItem() {
return getInventory().contains(item ->
!item.getName().equals(currentPickaxe.name) &&
!item.getName().contains(rock.ORE) &&
!cutGems.contains(item.getName()) &&
!uncutGems.contains(item.getName())
);
}
protected void mine() throws InterruptedException {
miningNode.run();
}
protected void doBanking() throws InterruptedException {
bankNode.run();
if (bankNode.hasFailed()) {
setFailed();
}
}
private class MiningNode extends Executable {
private Area rockArea;
private Entity currentRock;
private Area getAreaWithRock(Rock rock) {
return Arrays.stream(mine.rockAreas).filter(rockArea -> rockArea.rock == rock)
.map(rockArea -> rockArea.area).findAny().get();
}
@Override
public void run() throws InterruptedException {
if (rockArea == null) {
rockArea = getAreaWithRock(rock);
} else if (!rockArea.contains(myPosition())) {
getWalking().webWalk(rockArea);
} else if (currentRock == null || !rock.hasOre(currentRock) || !myPlayer().isAnimating()) {
mineRock();
}
}
private void mineRock() {
currentRock = rock.getClosestWithOre(getBot().getMethods(), new AreaFilter<>(rockArea));
if (currentRock != null && currentRock.interact("Mine")) {
Sleep.sleepUntil(() -> myPlayer().isAnimating() || !rock.hasOre(currentRock), 5000);
}
}
@Override
public String toString() {
return "Mining";
}
}
protected class ItemReqBankingImpl extends Banking {
@Override
public void bank() {
if (pickaxesInBank.isEmpty()) {
for (Pickaxe pickaxe : Pickaxe.values()) {
if (getBank().contains(pickaxe.name)) {
pickaxesInBank.add(pickaxe);
}
}
checkedBankForPickaxes = true;
}
if (currentPickaxe == null || bankContainsBetterPickaxe()) {
if (pickaxesInBank.isEmpty()) {
setFailed();
return;
}
if (!getInventory().isEmpty()) {
getBank().depositAll();
} else {
Optional<Pickaxe> bestPickaxe = pickaxesInBank.stream().filter(pickaxe -> pickaxe.canUse(getSkills())).max(Comparator.comparingInt(Pickaxe::getLevelRequired));
if (bestPickaxe.isPresent()) {
if (getBank().withdraw(bestPickaxe.get().name, 1)) {
currentPickaxe = bestPickaxe.get();
}
} else {
setFailed();
}
}
} else if (!getInventory().isEmptyExcept(currentPickaxe.name)) {
getBank().depositAllExcept(currentPickaxe.name);
}
}
}
}
| 40.054545 | 205 | 0.594038 |
a784a15c3d2ef61ecf4d0c879c347bd816c545f5 | 160,680 | /*
*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.cartera.presentation.swing.jinternalframes.report;
import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*;
import com.bydan.erp.cartera.presentation.swing.jinternalframes.*;
import com.bydan.erp.cartera.presentation.web.jsf.sessionbean.*;//.report;
import com.bydan.erp.cartera.presentation.swing.jinternalframes.*;
import com.bydan.erp.cartera.presentation.swing.jinternalframes.auxiliar.report.*;
import com.bydan.erp.cartera.presentation.web.jsf.sessionbean.report.*;
import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*;
import com.bydan.erp.cartera.presentation.web.jsf.sessionbean.*;
//import com.bydan.erp.cartera.presentation.report.source.report.*;
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.cartera.business.entity.report.*;
import com.bydan.erp.cartera.util.report.FacturasProveedoresConstantesFunciones;
import com.bydan.erp.cartera.business.logic.report.*;
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 FacturasProveedoresDetalleFormJInternalFrame extends FacturasProveedoresBeanSwingJInternalFrameAdditional {
private static final long serialVersionUID = 1L;
public JToolBar jTtoolBarDetalleFacturasProveedores;
protected JMenuBar jmenuBarDetalleFacturasProveedores;
protected JMenu jmenuDetalleFacturasProveedores;
protected JMenu jmenuDetalleArchivoFacturasProveedores;
protected JMenu jmenuDetalleAccionesFacturasProveedores;
protected JMenu jmenuDetalleDatosFacturasProveedores;
protected JPanel jContentPane = null;
protected JPanel jContentPaneDetalleFacturasProveedores = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
protected GridBagLayout gridaBagLayoutFacturasProveedores;
protected GridBagConstraints gridBagConstraintsFacturasProveedores;
//protected JInternalFrameBase jInternalFrameParent; //ESTA EN BASE
//protected FacturasProveedoresBeanSwingJInternalFrameAdditional jInternalFrameDetalleFacturasProveedores;
//VENTANAS PARA ACTUALIZAR Y BUSCAR FK
protected EmpresaBeanSwingJInternalFrame empresaBeanSwingJInternalFrame;
public String sFinalQueryGeneral_empresa="";
protected ClienteBeanSwingJInternalFrame clienteBeanSwingJInternalFrame;
public String sFinalQueryGeneral_cliente="";
public FacturasProveedoresSessionBean facturasproveedoresSessionBean;
public EmpresaSessionBean empresaSessionBean;
public ClienteSessionBean clienteSessionBean;
public FacturasProveedoresLogic facturasproveedoresLogic;
public JScrollPane jScrollPanelDatosFacturasProveedores;
public JScrollPane jScrollPanelDatosEdicionFacturasProveedores;
public JScrollPane jScrollPanelDatosGeneralFacturasProveedores;
protected JPanel jPanelCamposFacturasProveedores;
protected JPanel jPanelCamposOcultosFacturasProveedores;
protected JPanel jPanelAccionesFacturasProveedores;
protected JPanel jPanelAccionesFormularioFacturasProveedores;
protected Integer iXPanelCamposFacturasProveedores=0;
protected Integer iYPanelCamposFacturasProveedores=0;
protected Integer iXPanelCamposOcultosFacturasProveedores=0;
protected Integer iYPanelCamposOcultosFacturasProveedores=0;
;
;
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
public JButton jButtonNuevoFacturasProveedores;
public JButton jButtonModificarFacturasProveedores;
public JButton jButtonActualizarFacturasProveedores;
public JButton jButtonEliminarFacturasProveedores;
public JButton jButtonCancelarFacturasProveedores;
public JButton jButtonGuardarCambiosFacturasProveedores;
public JButton jButtonGuardarCambiosTablaFacturasProveedores;
protected JButton jButtonCerrarFacturasProveedores;
protected JButton jButtonProcesarInformacionFacturasProveedores;
protected JCheckBox jCheckBoxPostAccionNuevoFacturasProveedores;
protected JCheckBox jCheckBoxPostAccionSinCerrarFacturasProveedores;
protected JCheckBox jCheckBoxPostAccionSinMensajeFacturasProveedores;
//TOOLBAR
protected JButton jButtonNuevoToolBarFacturasProveedores;
protected JButton jButtonModificarToolBarFacturasProveedores;
protected JButton jButtonActualizarToolBarFacturasProveedores;
protected JButton jButtonEliminarToolBarFacturasProveedores;
protected JButton jButtonCancelarToolBarFacturasProveedores;
protected JButton jButtonGuardarCambiosToolBarFacturasProveedores;
protected JButton jButtonGuardarCambiosTablaToolBarFacturasProveedores;
protected JButton jButtonMostrarOcultarTablaToolBarFacturasProveedores;
protected JButton jButtonCerrarToolBarFacturasProveedores;
protected JButton jButtonProcesarInformacionToolBarFacturasProveedores;
//TOOLBAR
//MENU
protected JMenuItem jMenuItemNuevoFacturasProveedores;
protected JMenuItem jMenuItemModificarFacturasProveedores;
protected JMenuItem jMenuItemActualizarFacturasProveedores;
protected JMenuItem jMenuItemEliminarFacturasProveedores;
protected JMenuItem jMenuItemCancelarFacturasProveedores;
protected JMenuItem jMenuItemGuardarCambiosFacturasProveedores;
protected JMenuItem jMenuItemGuardarCambiosTablaFacturasProveedores;
protected JMenuItem jMenuItemCerrarFacturasProveedores;
protected JMenuItem jMenuItemDetalleCerrarFacturasProveedores;
protected JMenuItem jMenuItemDetalleMostarOcultarFacturasProveedores;
protected JMenuItem jMenuItemProcesarInformacionFacturasProveedores;
protected JMenuItem jMenuItemNuevoGuardarCambiosFacturasProveedores;
protected JMenuItem jMenuItemMostrarOcultarFacturasProveedores;
//MENU
protected JLabel jLabelAccionesFacturasProveedores;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposRelacionesFacturasProveedores;
@SuppressWarnings("rawtypes")
protected JComboBox jComboBoxTiposAccionesFacturasProveedores;
@SuppressWarnings("rawtypes")
public JComboBox jComboBoxTiposAccionesFormularioFacturasProveedores;
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 jPanelidFacturasProveedores;
public JLabel jLabelIdFacturasProveedores;
public JLabel jLabelidFacturasProveedores;
public JButton jButtonidFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelfecha_emision_inicioFacturasProveedores;
public JLabel jLabelfecha_emision_inicioFacturasProveedores;
//public JFormattedTextField jDateChooserfecha_emision_inicioFacturasProveedores;
public JDateChooser jDateChooserfecha_emision_inicioFacturasProveedores;
public JButton jButtonfecha_emision_inicioFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelfecha_emision_finFacturasProveedores;
public JLabel jLabelfecha_emision_finFacturasProveedores;
//public JFormattedTextField jDateChooserfecha_emision_finFacturasProveedores;
public JDateChooser jDateChooserfecha_emision_finFacturasProveedores;
public JButton jButtonfecha_emision_finFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelcodigo_clienteFacturasProveedores;
public JLabel jLabelcodigo_clienteFacturasProveedores;
public JTextField jTextFieldcodigo_clienteFacturasProveedores;
public JButton jButtoncodigo_clienteFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelnombre_clienteFacturasProveedores;
public JLabel jLabelnombre_clienteFacturasProveedores;
public JTextArea jTextAreanombre_clienteFacturasProveedores;
public JScrollPane jscrollPanenombre_clienteFacturasProveedores;
public JButton jButtonnombre_clienteFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelnumero_facturaFacturasProveedores;
public JLabel jLabelnumero_facturaFacturasProveedores;
public JTextField jTextFieldnumero_facturaFacturasProveedores;
public JButton jButtonnumero_facturaFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelfecha_emisionFacturasProveedores;
public JLabel jLabelfecha_emisionFacturasProveedores;
//public JFormattedTextField jDateChooserfecha_emisionFacturasProveedores;
public JDateChooser jDateChooserfecha_emisionFacturasProveedores;
public JButton jButtonfecha_emisionFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPaneltotalFacturasProveedores;
public JLabel jLabeltotalFacturasProveedores;
public JTextField jTextFieldtotalFacturasProveedores;
public JButton jButtontotalFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelnumero_pre_impresoFacturasProveedores;
public JLabel jLabelnumero_pre_impresoFacturasProveedores;
public JTextField jTextFieldnumero_pre_impresoFacturasProveedores;
public JButton jButtonnumero_pre_impresoFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelfechaFacturasProveedores;
public JLabel jLabelfechaFacturasProveedores;
//public JFormattedTextField jDateChooserfechaFacturasProveedores;
public JDateChooser jDateChooserfechaFacturasProveedores;
public JButton jButtonfechaFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelid_empresaFacturasProveedores;
public JLabel jLabelid_empresaFacturasProveedores;
@SuppressWarnings("rawtypes")
public JComboBox jComboBoxid_empresaFacturasProveedores;
public JButton jButtonid_empresaFacturasProveedores= new JButtonMe();
public JButton jButtonid_empresaFacturasProveedoresUpdate= new JButtonMe();
public JButton jButtonid_empresaFacturasProveedoresBusqueda= new JButtonMe();
public JPanel jPanelid_clienteFacturasProveedores;
public JLabel jLabelid_clienteFacturasProveedores;
@SuppressWarnings("rawtypes")
public JComboBox jComboBoxid_clienteFacturasProveedores;
public JButton jButtonid_clienteFacturasProveedores= new JButtonMe();
public JButton jButtonid_clienteFacturasProveedoresUpdate= new JButtonMe();
public JButton jButtonid_clienteFacturasProveedoresBusqueda= new JButtonMe();
//ELEMENTOS TABLAS PARAMETOS
//ELEMENTOS TABLAS PARAMETOS_FIN
protected JTabbedPane jTabbedPaneRelacionesFacturasProveedores;
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=false;
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=946;//(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 FacturasProveedoresDetalleFormJInternalFrame(String sTipo) throws Exception {
super(PaginaTipo.FORMULARIO);
try {
if(sTipo.equals("MINIMO")) {
/*
this.jPanelCamposFacturasProveedores=new JPanel();
this.jPanelAccionesFormularioFacturasProveedores=new JPanel();
this.jmenuBarDetalleFacturasProveedores=new JMenuBar();
this.jTtoolBarDetalleFacturasProveedores=new JToolBar();
*/
}
} catch(Exception e) {
FuncionesSwing.manageException(this, e, null);
}
}
public FacturasProveedoresDetalleFormJInternalFrame(PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("FacturasProveedores 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 FacturasProveedoresDetalleFormJInternalFrame() throws Exception {
super(PaginaTipo.FORMULARIO);
//super("FacturasProveedores 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 FacturasProveedoresDetalleFormJInternalFrame(Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("FacturasProveedores 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 FacturasProveedoresDetalleFormJInternalFrame(Boolean conGuardarRelaciones,Boolean esGuardarRelacionado,Boolean cargarRelaciones,PaginaTipo paginaTipo) throws Exception {
super(paginaTipo);
//super("FacturasProveedores 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 FacturasProveedoresDetalleFormJInternalFrame(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("FacturasProveedores 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 getjButtonActualizarToolBarFacturasProveedores() {
return this.jButtonActualizarToolBarFacturasProveedores;
}
public JButton getjButtonEliminarToolBarFacturasProveedores() {
return this.jButtonEliminarToolBarFacturasProveedores;
}
public JButton getjButtonCancelarToolBarFacturasProveedores() {
return this.jButtonCancelarToolBarFacturasProveedores;
}
public JButton getjButtonProcesarInformacionFacturasProveedores() {
return this.jButtonProcesarInformacionFacturasProveedores;
}
public void setjButtonProcesarInformacion(JButton jButtonProcesarInformacionFacturasProveedores) {
this.jButtonProcesarInformacionFacturasProveedores = jButtonProcesarInformacionFacturasProveedores;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesFacturasProveedores() {
return this.jComboBoxTiposAccionesFacturasProveedores;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposRelacionesFacturasProveedores(
JComboBox jComboBoxTiposRelacionesFacturasProveedores) {
this.jComboBoxTiposRelacionesFacturasProveedores = jComboBoxTiposRelacionesFacturasProveedores;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesFacturasProveedores(
JComboBox jComboBoxTiposAccionesFacturasProveedores) {
this.jComboBoxTiposAccionesFacturasProveedores = jComboBoxTiposAccionesFacturasProveedores;
}
@SuppressWarnings("rawtypes")
public JComboBox getjComboBoxTiposAccionesFormularioFacturasProveedores() {
return this.jComboBoxTiposAccionesFormularioFacturasProveedores;
}
@SuppressWarnings("rawtypes")
public void setjComboBoxTiposAccionesFormularioFacturasProveedores(
JComboBox jComboBoxTiposAccionesFormularioFacturasProveedores) {
this.jComboBoxTiposAccionesFormularioFacturasProveedores = jComboBoxTiposAccionesFormularioFacturasProveedores;
}
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.facturasproveedoresSessionBean=new FacturasProveedoresSessionBean();
this.facturasproveedoresSessionBean.setConGuardarRelaciones(conGuardarRelaciones);
this.facturasproveedoresSessionBean.setEsGuardarRelacionado(esGuardarRelacionado);
this.conCargarMinimo=this.facturasproveedoresSessionBean.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);
FacturasProveedoresJInternalFrame.STIPO_TAMANIO_GENERAL=this.sTipoTamanioGeneral;
FacturasProveedoresJInternalFrame.STIPO_TAMANIO_GENERAL_TABLA=this.sTipoTamanioGeneralTabla;
FacturasProveedoresJInternalFrame.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,"Facturas Proveedores MANTENIMIENTO"));
if(iWidth > 1250) {
iWidth=1250;
}
if(iHeight > 660) {
iHeight=660;
}
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.facturasproveedoresSessionBean.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;
}
}
}
FacturasProveedoresJInternalFrame.ESTA_CARGADO_PORPARTE=true;
}
public void inicializarToolBar() {
this.jTtoolBarDetalleFacturasProveedores= new JToolBar("MENU DATOS");
//TOOLBAR
//PRINCIPAL
this.jButtonProcesarInformacionToolBarFacturasProveedores=new JButtonMe();
this.jButtonModificarToolBarFacturasProveedores=new JButtonMe();
//PRINCIPAL
//DETALLE
this.jButtonActualizarToolBarFacturasProveedores=FuncionesSwing.getButtonToolBarGeneral(this.jButtonActualizarToolBarFacturasProveedores,this.jTtoolBarDetalleFacturasProveedores,
"actualizar","actualizar","Actualizar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ACTUALIZAR"),"Actualizar",false);
this.jButtonEliminarToolBarFacturasProveedores=FuncionesSwing.getButtonToolBarGeneral(this.jButtonEliminarToolBarFacturasProveedores,this.jTtoolBarDetalleFacturasProveedores,
"eliminar","eliminar","Eliminar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ELIMINAR"),"Eliminar",false);
this.jButtonCancelarToolBarFacturasProveedores=FuncionesSwing.getButtonToolBarGeneral(this.jButtonCancelarToolBarFacturasProveedores,this.jTtoolBarDetalleFacturasProveedores,
"cancelar","cancelar","Cancelar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CANCELAR"),"Cancelar",false);
this.jButtonGuardarCambiosToolBarFacturasProveedores=FuncionesSwing.getButtonToolBarGeneral(this.jButtonGuardarCambiosToolBarFacturasProveedores,this.jTtoolBarDetalleFacturasProveedores,
"guardarcambios","guardarcambios","Guardar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"),"Guardar",false);
FuncionesSwing.setBoldButtonToolBar(this.jButtonActualizarToolBarFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButtonToolBar(this.jButtonEliminarToolBarFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButtonToolBar(this.jButtonCancelarToolBarFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
}
public void cargarMenus() {
this.jmenuBarDetalleFacturasProveedores=new JMenuBarMe();
//DETALLE
this.jmenuDetalleFacturasProveedores=new JMenuMe("Datos Relacionados");
this.jmenuDetalleArchivoFacturasProveedores=new JMenuMe("Archivo");
this.jmenuDetalleAccionesFacturasProveedores=new JMenuMe("Acciones");
this.jmenuDetalleDatosFacturasProveedores=new JMenuMe("Datos");
//DETALLE_FIN
this.jMenuItemNuevoFacturasProveedores= new JMenuItem("Nuevo" + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jMenuItemNuevoFacturasProveedores.setActionCommand("Nuevo");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemNuevoFacturasProveedores,"nuevo_button","Nuevo");
FuncionesSwing.setBoldMenuItem(this.jMenuItemNuevoFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemModificarFacturasProveedores= new JMenuItem("Editar" + FuncionesSwing.getKeyMensaje("MODIFICAR"));
this.jMenuItemModificarFacturasProveedores.setActionCommand("Editar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemModificarFacturasProveedores,"modificar_button","Editar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemModificarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemActualizarFacturasProveedores= new JMenuItem("Actualizar" + FuncionesSwing.getKeyMensaje("ACTUALIZAR"));
this.jMenuItemActualizarFacturasProveedores.setActionCommand("Actualizar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemActualizarFacturasProveedores,"actualizar_button","Actualizar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemActualizarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemEliminarFacturasProveedores= new JMenuItem("Eliminar" + FuncionesSwing.getKeyMensaje("ELIMINAR"));
this.jMenuItemEliminarFacturasProveedores.setActionCommand("Eliminar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemEliminarFacturasProveedores,"eliminar_button","Eliminar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemEliminarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCancelarFacturasProveedores= new JMenuItem("Cancelar" + FuncionesSwing.getKeyMensaje("CANCELAR"));
this.jMenuItemCancelarFacturasProveedores.setActionCommand("Cancelar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCancelarFacturasProveedores,"cancelar_button","Cancelar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCancelarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemGuardarCambiosFacturasProveedores= new JMenuItem("Guardar" + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jMenuItemGuardarCambiosFacturasProveedores.setActionCommand("Guardar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemGuardarCambiosFacturasProveedores,"guardarcambios_button","Guardar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemGuardarCambiosFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemCerrarFacturasProveedores= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemCerrarFacturasProveedores.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemCerrarFacturasProveedores,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemCerrarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleCerrarFacturasProveedores= new JMenuItem("Salir" + FuncionesSwing.getKeyMensaje("CERRAR"));
this.jMenuItemDetalleCerrarFacturasProveedores.setActionCommand("Cerrar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleCerrarFacturasProveedores,"cerrar_button","Salir");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleCerrarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemMostrarOcultarFacturasProveedores= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemMostrarOcultarFacturasProveedores.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemMostrarOcultarFacturasProveedores,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemMostrarOcultarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jMenuItemDetalleMostarOcultarFacturasProveedores= new JMenuItem("Mostrar Ocultar" + FuncionesSwing.getKeyMensaje("MOSTRAR_OCULTAR"));
this.jMenuItemDetalleMostarOcultarFacturasProveedores.setActionCommand("Mostrar Ocultar");
FuncionesSwing.addImagenMenuItemGeneral(this.jMenuItemDetalleMostarOcultarFacturasProveedores,"mostrar_ocultar_button","Mostrar Ocultar");
FuncionesSwing.setBoldMenuItem(this.jMenuItemDetalleMostarOcultarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
//DETALLE
this.jmenuDetalleArchivoFacturasProveedores.add(this.jMenuItemDetalleCerrarFacturasProveedores);
this.jmenuDetalleAccionesFacturasProveedores.add(this.jMenuItemActualizarFacturasProveedores);
this.jmenuDetalleAccionesFacturasProveedores.add(this.jMenuItemEliminarFacturasProveedores);
this.jmenuDetalleAccionesFacturasProveedores.add(this.jMenuItemCancelarFacturasProveedores);
//this.jmenuDetalleDatosFacturasProveedores.add(this.jMenuItemDetalleAbrirOrderByFacturasProveedores);
this.jmenuDetalleDatosFacturasProveedores.add(this.jMenuItemDetalleMostarOcultarFacturasProveedores);
//this.jmenuDetalleAccionesFacturasProveedores.add(this.jMenuItemGuardarCambiosFacturasProveedores);
//DETALLE_FIN
//RELACIONES
//RELACIONES
//DETALLE
FuncionesSwing.setBoldMenu(this.jmenuDetalleArchivoFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDetalleAccionesFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldMenu(this.jmenuDetalleDatosFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
this.jmenuBarDetalleFacturasProveedores.add(this.jmenuDetalleArchivoFacturasProveedores);
this.jmenuBarDetalleFacturasProveedores.add(this.jmenuDetalleAccionesFacturasProveedores);
this.jmenuBarDetalleFacturasProveedores.add(this.jmenuDetalleDatosFacturasProveedores);
//DETALLE_FIN
//AGREGA MENU DETALLE A PANTALLA
this.setJMenuBar(this.jmenuBarDetalleFacturasProveedores);
}
public void inicializarElementosCamposFacturasProveedores() {
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
jLabelIdFacturasProveedores = new JLabelMe();
jLabelIdFacturasProveedores.setText(""+Constantes2.S_CODIGO_UNICO+"");
jLabelIdFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
jLabelIdFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
jLabelIdFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelIdFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelidFacturasProveedores = new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelidFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_ID);
this.gridaBagLayoutFacturasProveedores= new GridBagLayout();
this.jPanelidFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
jLabelidFacturasProveedores = new JLabel();
jLabelidFacturasProveedores.setText("Id");
jLabelidFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
jLabelidFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
jLabelidFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelfecha_emision_inicioFacturasProveedores = new JLabelMe();
this.jLabelfecha_emision_inicioFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_FECHAEMISIONINICIO+" : *");
this.jLabelfecha_emision_inicioFacturasProveedores.setToolTipText("Fecha Emision Inicio");
this.jLabelfecha_emision_inicioFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2*2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2*2,0)));
this.jLabelfecha_emision_inicioFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2*2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2*2,0)));
this.jLabelfecha_emision_inicioFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2*2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2*2,0)));
FuncionesSwing.setBoldLabel(jLabelfecha_emision_inicioFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelfecha_emision_inicioFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelfecha_emision_inicioFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_FECHAEMISIONINICIO);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelfecha_emision_inicioFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
//jFormattedTextFieldfecha_emision_inicioFacturasProveedores= new JFormattedTextFieldMe();
jDateChooserfecha_emision_inicioFacturasProveedores= new JDateChooser();
jDateChooserfecha_emision_inicioFacturasProveedores.setEnabled(false);
jDateChooserfecha_emision_inicioFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
jDateChooserfecha_emision_inicioFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
jDateChooserfecha_emision_inicioFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
FuncionesSwing.setBoldDate(jDateChooserfecha_emision_inicioFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
jDateChooserfecha_emision_inicioFacturasProveedores.setDate(new Date());
jDateChooserfecha_emision_inicioFacturasProveedores.setDateFormatString("yyyy-MM-dd");;
//jFormattedTextFieldfecha_emision_inicioFacturasProveedores.setText(Funciones.getStringMySqlCurrentDate());
this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda.setText("U");
this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jDateChooserfecha_emision_inicioFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jDateChooserfecha_emision_inicioFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"fecha_emision_inicioFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonfecha_emision_inicioFacturasProveedoresBusqueda.setVisible(false); }
this.jLabelfecha_emision_finFacturasProveedores = new JLabelMe();
this.jLabelfecha_emision_finFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_FECHAEMISIONFIN+" : *");
this.jLabelfecha_emision_finFacturasProveedores.setToolTipText("Fecha Emision Fin");
this.jLabelfecha_emision_finFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
this.jLabelfecha_emision_finFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
this.jLabelfecha_emision_finFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
FuncionesSwing.setBoldLabel(jLabelfecha_emision_finFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelfecha_emision_finFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelfecha_emision_finFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_FECHAEMISIONFIN);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelfecha_emision_finFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
//jFormattedTextFieldfecha_emision_finFacturasProveedores= new JFormattedTextFieldMe();
jDateChooserfecha_emision_finFacturasProveedores= new JDateChooser();
jDateChooserfecha_emision_finFacturasProveedores.setEnabled(false);
jDateChooserfecha_emision_finFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
jDateChooserfecha_emision_finFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
jDateChooserfecha_emision_finFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
FuncionesSwing.setBoldDate(jDateChooserfecha_emision_finFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
jDateChooserfecha_emision_finFacturasProveedores.setDate(new Date());
jDateChooserfecha_emision_finFacturasProveedores.setDateFormatString("yyyy-MM-dd");;
//jFormattedTextFieldfecha_emision_finFacturasProveedores.setText(Funciones.getStringMySqlCurrentDate());
this.jButtonfecha_emision_finFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonfecha_emision_finFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonfecha_emision_finFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonfecha_emision_finFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonfecha_emision_finFacturasProveedoresBusqueda.setText("U");
this.jButtonfecha_emision_finFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonfecha_emision_finFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonfecha_emision_finFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jDateChooserfecha_emision_finFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jDateChooserfecha_emision_finFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"fecha_emision_finFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonfecha_emision_finFacturasProveedoresBusqueda.setVisible(false); }
this.jLabelcodigo_clienteFacturasProveedores = new JLabelMe();
this.jLabelcodigo_clienteFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_CODIGOCLIENTE+" : *");
this.jLabelcodigo_clienteFacturasProveedores.setToolTipText("Codigo Cliente");
this.jLabelcodigo_clienteFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelcodigo_clienteFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelcodigo_clienteFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelcodigo_clienteFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelcodigo_clienteFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelcodigo_clienteFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_CODIGOCLIENTE);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelcodigo_clienteFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
jTextFieldcodigo_clienteFacturasProveedores= new JTextFieldMe();
jTextFieldcodigo_clienteFacturasProveedores.setEnabled(false);
jTextFieldcodigo_clienteFacturasProveedores.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)));
jTextFieldcodigo_clienteFacturasProveedores.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)));
jTextFieldcodigo_clienteFacturasProveedores.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(jTextFieldcodigo_clienteFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtoncodigo_clienteFacturasProveedoresBusqueda= new JButtonMe();
this.jButtoncodigo_clienteFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtoncodigo_clienteFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtoncodigo_clienteFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtoncodigo_clienteFacturasProveedoresBusqueda.setText("U");
this.jButtoncodigo_clienteFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtoncodigo_clienteFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtoncodigo_clienteFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jTextFieldcodigo_clienteFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jTextFieldcodigo_clienteFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"codigo_clienteFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtoncodigo_clienteFacturasProveedoresBusqueda.setVisible(false); }
this.jLabelnombre_clienteFacturasProveedores = new JLabelMe();
this.jLabelnombre_clienteFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_NOMBRECLIENTE+" : *");
this.jLabelnombre_clienteFacturasProveedores.setToolTipText("Nombre Cliente");
this.jLabelnombre_clienteFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelnombre_clienteFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelnombre_clienteFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelnombre_clienteFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelnombre_clienteFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelnombre_clienteFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_NOMBRECLIENTE);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelnombre_clienteFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
jTextAreanombre_clienteFacturasProveedores= new JTextAreaMe();
jTextAreanombre_clienteFacturasProveedores.setEnabled(false);
jTextAreanombre_clienteFacturasProveedores.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)));
jTextAreanombre_clienteFacturasProveedores.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)));
jTextAreanombre_clienteFacturasProveedores.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)));
jTextAreanombre_clienteFacturasProveedores.setLineWrap(true);
jTextAreanombre_clienteFacturasProveedores.setWrapStyleWord(true);
jTextAreanombre_clienteFacturasProveedores.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
jTextAreanombre_clienteFacturasProveedores.setRows(5);
FuncionesSwing.setBoldTextArea(jTextAreanombre_clienteFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
jscrollPanenombre_clienteFacturasProveedores = new JScrollPane(jTextAreanombre_clienteFacturasProveedores);
jscrollPanenombre_clienteFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),70));
jscrollPanenombre_clienteFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),70));
jscrollPanenombre_clienteFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL,0),70));
this.jButtonnombre_clienteFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonnombre_clienteFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonnombre_clienteFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonnombre_clienteFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonnombre_clienteFacturasProveedoresBusqueda.setText("U");
this.jButtonnombre_clienteFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonnombre_clienteFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonnombre_clienteFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jTextAreanombre_clienteFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jTextAreanombre_clienteFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"nombre_clienteFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonnombre_clienteFacturasProveedoresBusqueda.setVisible(false); }
this.jLabelnumero_facturaFacturasProveedores = new JLabelMe();
this.jLabelnumero_facturaFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_NUMEROFACTURA+" : *");
this.jLabelnumero_facturaFacturasProveedores.setToolTipText("Numero Factura");
this.jLabelnumero_facturaFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelnumero_facturaFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelnumero_facturaFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelnumero_facturaFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelnumero_facturaFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelnumero_facturaFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_NUMEROFACTURA);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelnumero_facturaFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
jTextFieldnumero_facturaFacturasProveedores= new JTextFieldMe();
jTextFieldnumero_facturaFacturasProveedores.setEnabled(false);
jTextFieldnumero_facturaFacturasProveedores.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)));
jTextFieldnumero_facturaFacturasProveedores.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)));
jTextFieldnumero_facturaFacturasProveedores.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(jTextFieldnumero_facturaFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonnumero_facturaFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonnumero_facturaFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonnumero_facturaFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonnumero_facturaFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonnumero_facturaFacturasProveedoresBusqueda.setText("U");
this.jButtonnumero_facturaFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonnumero_facturaFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonnumero_facturaFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jTextFieldnumero_facturaFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jTextFieldnumero_facturaFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"numero_facturaFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonnumero_facturaFacturasProveedoresBusqueda.setVisible(false); }
this.jLabelfecha_emisionFacturasProveedores = new JLabelMe();
this.jLabelfecha_emisionFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_FECHAEMISION+" : *");
this.jLabelfecha_emisionFacturasProveedores.setToolTipText("Fecha Emision");
this.jLabelfecha_emisionFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelfecha_emisionFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelfecha_emisionFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelfecha_emisionFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelfecha_emisionFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelfecha_emisionFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_FECHAEMISION);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelfecha_emisionFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
//jFormattedTextFieldfecha_emisionFacturasProveedores= new JFormattedTextFieldMe();
jDateChooserfecha_emisionFacturasProveedores= new JDateChooser();
jDateChooserfecha_emisionFacturasProveedores.setEnabled(false);
jDateChooserfecha_emisionFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
jDateChooserfecha_emisionFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
jDateChooserfecha_emisionFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
FuncionesSwing.setBoldDate(jDateChooserfecha_emisionFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
jDateChooserfecha_emisionFacturasProveedores.setDate(new Date());
jDateChooserfecha_emisionFacturasProveedores.setDateFormatString("yyyy-MM-dd");;
//jFormattedTextFieldfecha_emisionFacturasProveedores.setText(Funciones.getStringMySqlCurrentDate());
this.jButtonfecha_emisionFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonfecha_emisionFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonfecha_emisionFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonfecha_emisionFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonfecha_emisionFacturasProveedoresBusqueda.setText("U");
this.jButtonfecha_emisionFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonfecha_emisionFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonfecha_emisionFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jDateChooserfecha_emisionFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jDateChooserfecha_emisionFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"fecha_emisionFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonfecha_emisionFacturasProveedoresBusqueda.setVisible(false); }
this.jLabeltotalFacturasProveedores = new JLabelMe();
this.jLabeltotalFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_TOTAL+" : *");
this.jLabeltotalFacturasProveedores.setToolTipText("Total");
this.jLabeltotalFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabeltotalFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabeltotalFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabeltotalFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPaneltotalFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPaneltotalFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_TOTAL);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPaneltotalFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
jTextFieldtotalFacturasProveedores= new JTextFieldMe();
jTextFieldtotalFacturasProveedores.setEnabled(false);
jTextFieldtotalFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFieldtotalFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
jTextFieldtotalFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_VALOR + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_VALOR,0),Constantes.ISWING_ALTO_CONTROL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL,0)));
FuncionesSwing.setBoldTextField(jTextFieldtotalFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
jTextFieldtotalFacturasProveedores.setText("0.0");
this.jButtontotalFacturasProveedoresBusqueda= new JButtonMe();
this.jButtontotalFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtontotalFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtontotalFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtontotalFacturasProveedoresBusqueda.setText("U");
this.jButtontotalFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtontotalFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtontotalFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jTextFieldtotalFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jTextFieldtotalFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"totalFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtontotalFacturasProveedoresBusqueda.setVisible(false); }
this.jLabelnumero_pre_impresoFacturasProveedores = new JLabelMe();
this.jLabelnumero_pre_impresoFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_NUMEROPREIMPRESO+" : *");
this.jLabelnumero_pre_impresoFacturasProveedores.setToolTipText("Numero Pre Impreso");
this.jLabelnumero_pre_impresoFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
this.jLabelnumero_pre_impresoFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
this.jLabelnumero_pre_impresoFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL2 + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL2,0)));
FuncionesSwing.setBoldLabel(jLabelnumero_pre_impresoFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelnumero_pre_impresoFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelnumero_pre_impresoFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_NUMEROPREIMPRESO);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelnumero_pre_impresoFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
jTextFieldnumero_pre_impresoFacturasProveedores= new JTextFieldMe();
jTextFieldnumero_pre_impresoFacturasProveedores.setEnabled(false);
jTextFieldnumero_pre_impresoFacturasProveedores.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)));
jTextFieldnumero_pre_impresoFacturasProveedores.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)));
jTextFieldnumero_pre_impresoFacturasProveedores.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(jTextFieldnumero_pre_impresoFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda.setText("U");
this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jTextFieldnumero_pre_impresoFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jTextFieldnumero_pre_impresoFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"numero_pre_impresoFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonnumero_pre_impresoFacturasProveedoresBusqueda.setVisible(false); }
this.jLabelfechaFacturasProveedores = new JLabelMe();
this.jLabelfechaFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_FECHA+" : *");
this.jLabelfechaFacturasProveedores.setToolTipText("Fecha");
this.jLabelfechaFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelfechaFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelfechaFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelfechaFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelfechaFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelfechaFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_FECHA);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelfechaFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
//jFormattedTextFieldfechaFacturasProveedores= new JFormattedTextFieldMe();
jDateChooserfechaFacturasProveedores= new JDateChooser();
jDateChooserfechaFacturasProveedores.setEnabled(false);
jDateChooserfechaFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
jDateChooserfechaFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
jDateChooserfechaFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_FECHA,0),Constantes.ISWING_ALTO_CONTROL_FECHA + FuncionesSwing.getValorProporcion(Constantes.ISWING_ALTO_CONTROL_FECHA,0)));
FuncionesSwing.setBoldDate(jDateChooserfechaFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
jDateChooserfechaFacturasProveedores.setDate(new Date());
jDateChooserfechaFacturasProveedores.setDateFormatString("yyyy-MM-dd");;
//jFormattedTextFieldfechaFacturasProveedores.setText(Funciones.getStringMySqlCurrentDate());
this.jButtonfechaFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonfechaFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonfechaFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonfechaFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonfechaFacturasProveedoresBusqueda.setText("U");
this.jButtonfechaFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonfechaFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonfechaFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jDateChooserfechaFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jDateChooserfechaFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"fechaFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonfechaFacturasProveedoresBusqueda.setVisible(false); }
}
public void inicializarElementosCamposForeigKeysFacturasProveedores() {
String sKeyStrokeName="";
KeyStroke keyStrokeControl=null;
this.jLabelid_empresaFacturasProveedores = new JLabelMe();
this.jLabelid_empresaFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_IDEMPRESA+" : *");
this.jLabelid_empresaFacturasProveedores.setToolTipText("Empresa");
this.jLabelid_empresaFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelid_empresaFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelid_empresaFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelid_empresaFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelid_empresaFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelid_empresaFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_IDEMPRESA);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelid_empresaFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
jComboBoxid_empresaFacturasProveedores= new JComboBoxMe();
jComboBoxid_empresaFacturasProveedores.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)));
jComboBoxid_empresaFacturasProveedores.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)));
jComboBoxid_empresaFacturasProveedores.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.setBoldComboBox(jComboBoxid_empresaFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
jComboBoxid_empresaFacturasProveedores.setEnabled(false);
this.jButtonid_empresaFacturasProveedores= new JButtonMe();
this.jButtonid_empresaFacturasProveedores.setMinimumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_empresaFacturasProveedores.setMaximumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_empresaFacturasProveedores.setPreferredSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_empresaFacturasProveedores.setText("Buscar");
this.jButtonid_empresaFacturasProveedores.setToolTipText("Buscar ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA")+")");
this.jButtonid_empresaFacturasProveedores.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaFacturasProveedores,"buscar_form","Buscar");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSQUEDA");
jComboBoxid_empresaFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_empresaFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaFacturasProveedores"));
this.jButtonid_empresaFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonid_empresaFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_empresaFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_empresaFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonid_empresaFacturasProveedoresBusqueda.setText("U");
this.jButtonid_empresaFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonid_empresaFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jComboBoxid_empresaFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_empresaFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonid_empresaFacturasProveedoresBusqueda.setVisible(false); }
this.jButtonid_empresaFacturasProveedoresUpdate= new JButtonMe();
this.jButtonid_empresaFacturasProveedoresUpdate.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_empresaFacturasProveedoresUpdate.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_empresaFacturasProveedoresUpdate.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonid_empresaFacturasProveedoresUpdate.setText("U");
this.jButtonid_empresaFacturasProveedoresUpdate.setToolTipText("ACTUALIZAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR")+")");
this.jButtonid_empresaFacturasProveedoresUpdate.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_empresaFacturasProveedoresUpdate,"actualizardatos","ACTUALIZAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_ACTUALIZAR");
jComboBoxid_empresaFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_empresaFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_empresaFacturasProveedoresUpdate"));
this.jLabelid_clienteFacturasProveedores = new JLabelMe();
this.jLabelid_clienteFacturasProveedores.setText(""+FacturasProveedoresConstantesFunciones.LABEL_IDCLIENTE+" : *");
this.jLabelid_clienteFacturasProveedores.setToolTipText("Cliente");
this.jLabelid_clienteFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelid_clienteFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
this.jLabelid_clienteFacturasProveedores.setPreferredSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes.ISWING_ANCHO_CONTROL_LABEL,-4),Constantes2.ISWING_ALTO_CONTROL_LABEL + FuncionesSwing.getValorProporcion(Constantes2.ISWING_ALTO_CONTROL_LABEL,0)));
FuncionesSwing.setBoldLabel(jLabelid_clienteFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jPanelid_clienteFacturasProveedores=new JPanelMe("fondo_formulario",true);//new JPanel();
this.jPanelid_clienteFacturasProveedores.setToolTipText(FacturasProveedoresConstantesFunciones.LABEL_IDCLIENTE);
this.gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jPanelid_clienteFacturasProveedores.setLayout(this.gridaBagLayoutFacturasProveedores);
jComboBoxid_clienteFacturasProveedores= new JComboBoxMe();
jComboBoxid_clienteFacturasProveedores.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)));
jComboBoxid_clienteFacturasProveedores.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)));
jComboBoxid_clienteFacturasProveedores.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.setBoldComboBox(jComboBoxid_clienteFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonid_clienteFacturasProveedores= new JButtonMe();
this.jButtonid_clienteFacturasProveedores.setMinimumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_clienteFacturasProveedores.setMaximumSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_clienteFacturasProveedores.setPreferredSize(new Dimension(50,Constantes.ISWING_ALTO_CONTROL));
this.jButtonid_clienteFacturasProveedores.setText("Buscar");
this.jButtonid_clienteFacturasProveedores.setToolTipText("Buscar ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA")+")");
this.jButtonid_clienteFacturasProveedores.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_clienteFacturasProveedores,"buscar_form","Buscar");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSQUEDA");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSQUEDA");
jComboBoxid_clienteFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_clienteFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_clienteFacturasProveedores"));
this.jButtonid_clienteFacturasProveedoresBusqueda= new JButtonMe();
this.jButtonid_clienteFacturasProveedoresBusqueda.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_clienteFacturasProveedoresBusqueda.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_clienteFacturasProveedoresBusqueda.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonid_clienteFacturasProveedoresBusqueda.setText("U");
this.jButtonid_clienteFacturasProveedoresBusqueda.setToolTipText("BUSCAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR")+")");
this.jButtonid_clienteFacturasProveedoresBusqueda.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_clienteFacturasProveedoresBusqueda,"buscardatos","BUSCAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_BUSCAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_BUSCAR");
jComboBoxid_clienteFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_clienteFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_clienteFacturasProveedoresBusqueda"));
if(this.facturasproveedoresSessionBean.getEsGuardarRelacionado() || paginaTipo.equals(PaginaTipo.SECUNDARIO)) {
this.jButtonid_clienteFacturasProveedoresBusqueda.setVisible(false); }
this.jButtonid_clienteFacturasProveedoresUpdate= new JButtonMe();
this.jButtonid_clienteFacturasProveedoresUpdate.setMinimumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_clienteFacturasProveedoresUpdate.setMaximumSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
this.jButtonid_clienteFacturasProveedoresUpdate.setPreferredSize(new Dimension(Constantes2.ISWING_ANCHO_CONTROL_BOTONICONO,Constantes2.ISWING_ALTO_CONTROL_BOTONICONO));
//this.jButtonid_clienteFacturasProveedoresUpdate.setText("U");
this.jButtonid_clienteFacturasProveedoresUpdate.setToolTipText("ACTUALIZAR DATOS ("+FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR")+")");
this.jButtonid_clienteFacturasProveedoresUpdate.setFocusable(false);
FuncionesSwing.addImagenButtonGeneral(this.jButtonid_clienteFacturasProveedoresUpdate,"actualizardatos","ACTUALIZAR DATOS");
sKeyStrokeName = FuncionesSwing.getKeyNameControl("CONTROL_ACTUALIZAR");
keyStrokeControl=FuncionesSwing.getKeyStrokeControl( "CONTROL_ACTUALIZAR");
jComboBoxid_clienteFacturasProveedores.getInputMap().put(keyStrokeControl, sKeyStrokeName);
jComboBoxid_clienteFacturasProveedores.getActionMap().put(sKeyStrokeName, new ButtonAbstractAction(this,"id_clienteFacturasProveedoresUpdate"));
}
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.jInternalFrameDetalleFacturasProveedores = new FacturasProveedoresBeanSwingJInternalFrameAdditional(paginaTipo);//JInternalFrameBase("Facturas Proveedores DATOS");
this.cargarMenus();
this.gridaBagLayoutFacturasProveedores= new GridBagLayout();
String sToolTipFacturasProveedores="";
sToolTipFacturasProveedores=FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO;
if(Constantes.ISDEVELOPING) {
sToolTipFacturasProveedores+="(Cartera.FacturasProveedores)";
}
if(!this.facturasproveedoresSessionBean.getEsGuardarRelacionado()) {
sToolTipFacturasProveedores+="_"+this.opcionActual.getId();
}
this.jButtonNuevoFacturasProveedores = new JButtonMe();
this.jButtonModificarFacturasProveedores = new JButtonMe();
this.jButtonActualizarFacturasProveedores = new JButtonMe();
this.jButtonEliminarFacturasProveedores = new JButtonMe();
this.jButtonCancelarFacturasProveedores = new JButtonMe();
this.jButtonGuardarCambiosFacturasProveedores = new JButtonMe();
this.jButtonGuardarCambiosTablaFacturasProveedores = new JButtonMe();
this.jButtonCerrarFacturasProveedores = new JButtonMe();
this.jScrollPanelDatosFacturasProveedores = new JScrollPane();
this.jScrollPanelDatosEdicionFacturasProveedores = new JScrollPane();
this.jScrollPanelDatosGeneralFacturasProveedores = new JScrollPane();
this.jPanelCamposFacturasProveedores = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelCamposOcultosFacturasProveedores = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelAccionesFacturasProveedores = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
this.jPanelAccionesFormularioFacturasProveedores = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);
//if(!this.conCargarMinimo) {
;
;
//}
this.sPath=" <---> Acceso: Facturas Proveedores";
if(!this.facturasproveedoresSessionBean.getEsGuardarRelacionado()) {
this.jScrollPanelDatosFacturasProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Facturas Proveedoreses" + this.sPath));
} else {
this.jScrollPanelDatosFacturasProveedores.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
this.jScrollPanelDatosEdicionFacturasProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jScrollPanelDatosGeneralFacturasProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Edicion Datos"));
this.jPanelCamposFacturasProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));
this.jPanelCamposFacturasProveedores.setName("jPanelCamposFacturasProveedores");
this.jPanelCamposOcultosFacturasProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos Ocultos"));
this.jPanelCamposOcultosFacturasProveedores.setName("jPanelCamposOcultosFacturasProveedores");
this.jPanelAccionesFacturasProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));
this.jPanelAccionesFacturasProveedores.setToolTipText("Acciones");
this.jPanelAccionesFacturasProveedores.setName("Acciones");
this.jPanelAccionesFormularioFacturasProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones Extra/Post"));
this.jPanelAccionesFormularioFacturasProveedores.setToolTipText("Acciones");
this.jPanelAccionesFormularioFacturasProveedores.setName("Acciones");
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosEdicionFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosGeneralFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldScrollPanel(this.jScrollPanelDatosFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelCamposFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelCamposOcultosFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldPanel(this.jPanelAccionesFormularioFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
//if(!this.conCargarMinimo) {
;
;
//}
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
this.jButtonNuevoFacturasProveedores.setText("Nuevo");
this.jButtonModificarFacturasProveedores.setText("Editar");
this.jButtonActualizarFacturasProveedores.setText("Actualizar");
this.jButtonEliminarFacturasProveedores.setText("Eliminar");
this.jButtonCancelarFacturasProveedores.setText("Cancelar");
this.jButtonGuardarCambiosFacturasProveedores.setText("Guardar");
this.jButtonGuardarCambiosTablaFacturasProveedores.setText("Guardar");
this.jButtonCerrarFacturasProveedores.setText("Salir");
FuncionesSwing.addImagenButtonGeneral(this.jButtonNuevoFacturasProveedores,"nuevo_button","Nuevo",this.facturasproveedoresSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonModificarFacturasProveedores,"modificar_button","Editar",this.facturasproveedoresSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonActualizarFacturasProveedores,"actualizar_button","Actualizar",this.facturasproveedoresSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonEliminarFacturasProveedores,"eliminar_button","Eliminar",this.facturasproveedoresSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCancelarFacturasProveedores,"cancelar_button","Cancelar",this.facturasproveedoresSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosFacturasProveedores,"guardarcambios_button","Guardar",this.facturasproveedoresSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonGuardarCambiosTablaFacturasProveedores,"guardarcambiostabla_button","Guardar",this.facturasproveedoresSessionBean.getEsGuardarRelacionado());
FuncionesSwing.addImagenButtonGeneral(this.jButtonCerrarFacturasProveedores,"cerrar_button","Salir",this.facturasproveedoresSessionBean.getEsGuardarRelacionado());
FuncionesSwing.setBoldButton(this.jButtonNuevoFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonModificarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonGuardarCambiosTablaFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonCerrarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);
FuncionesSwing.setBoldButton(this.jButtonActualizarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButton(this.jButtonEliminarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
FuncionesSwing.setBoldButton(this.jButtonCancelarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
this.jButtonNuevoFacturasProveedores.setToolTipText("Nuevo"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("NUEVO"));
this.jButtonModificarFacturasProveedores.setToolTipText("Editar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO+"");// + FuncionesSwing.getKeyMensaje("MODIFICAR"))
this.jButtonActualizarFacturasProveedores.setToolTipText("Actualizar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ACTUALIZAR"));
this.jButtonEliminarFacturasProveedores.setToolTipText("Eliminar)"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("ELIMINAR"));
this.jButtonCancelarFacturasProveedores.setToolTipText("Cancelar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("CANCELAR"));
this.jButtonGuardarCambiosFacturasProveedores.setToolTipText("Guardar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonGuardarCambiosTablaFacturasProveedores.setToolTipText("Guardar"+" "+FacturasProveedoresConstantesFunciones.SCLASSWEBTITULO + FuncionesSwing.getKeyMensaje("GUARDAR_CAMBIOS"));
this.jButtonCerrarFacturasProveedores.setToolTipText("Salir"+" "+FacturasProveedoresConstantesFunciones.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 = "NuevoFacturasProveedores";
inputMap = this.jButtonNuevoFacturasProveedores.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("NUEVO") , FuncionesSwing.getMaskKey("NUEVO")), sMapKey);
this.jButtonNuevoFacturasProveedores.getActionMap().put(sMapKey, new ButtonAbstractAction(this,"NuevoFacturasProveedores"));
//ACTUALIZAR
sMapKey = "ActualizarFacturasProveedores";
inputMap = this.jButtonActualizarFacturasProveedores.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ACTUALIZAR") , FuncionesSwing.getMaskKey("ACTUALIZAR")), sMapKey);
this.jButtonActualizarFacturasProveedores.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"ActualizarFacturasProveedores"));
//ELIMINAR
sMapKey = "EliminarFacturasProveedores";
inputMap = this.jButtonEliminarFacturasProveedores.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("ELIMINAR") , FuncionesSwing.getMaskKey("ELIMINAR")), sMapKey);
this.jButtonEliminarFacturasProveedores.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"EliminarFacturasProveedores"));
//CANCELAR
sMapKey = "CancelarFacturasProveedores";
inputMap = this.jButtonCancelarFacturasProveedores.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CANCELAR") , FuncionesSwing.getMaskKey("CANCELAR")), sMapKey);
this.jButtonCancelarFacturasProveedores.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CancelarFacturasProveedores"));
//CERRAR
sMapKey = "CerrarFacturasProveedores";
inputMap = this.jButtonCerrarFacturasProveedores.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("CERRAR") , FuncionesSwing.getMaskKey("CERRAR")), sMapKey);
this.jButtonCerrarFacturasProveedores.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"CerrarFacturasProveedores"));
//GUARDAR CAMBIOS
sMapKey = "GuardarCambiosTablaFacturasProveedores";
inputMap = this.jButtonGuardarCambiosTablaFacturasProveedores.getInputMap(FuncionesSwing.getTipoFocusedKeyEvent("NORMAL"));
inputMap.put(KeyStroke.getKeyStroke(FuncionesSwing.getKeyEvent("GUARDAR_CAMBIOS") , FuncionesSwing.getMaskKey("GUARDAR_CAMBIOS")), sMapKey);
this.jButtonGuardarCambiosTablaFacturasProveedores.getActionMap().put(sMapKey,new ButtonAbstractAction(this,"GuardarCambiosTablaFacturasProveedores"));
//HOT KEYS
this.jCheckBoxPostAccionNuevoFacturasProveedores = new JCheckBoxMe();
this.jCheckBoxPostAccionNuevoFacturasProveedores.setText("Nuevo");
this.jCheckBoxPostAccionNuevoFacturasProveedores.setToolTipText("Nuevo FacturasProveedores");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionNuevoFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
this.jCheckBoxPostAccionSinCerrarFacturasProveedores = new JCheckBoxMe();
this.jCheckBoxPostAccionSinCerrarFacturasProveedores.setText("Sin Cerrar");
this.jCheckBoxPostAccionSinCerrarFacturasProveedores.setToolTipText("Sin Cerrar Ventana FacturasProveedores");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionSinCerrarFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
this.jCheckBoxPostAccionSinMensajeFacturasProveedores = new JCheckBoxMe();
this.jCheckBoxPostAccionSinMensajeFacturasProveedores.setText("Sin Mensaje");
this.jCheckBoxPostAccionSinMensajeFacturasProveedores.setToolTipText("Sin Mensaje Confirmacion");
FuncionesSwing.setBoldCheckBox(this.jCheckBoxPostAccionSinMensajeFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
this.jComboBoxTiposAccionesFacturasProveedores = new JComboBoxMe();
//this.jComboBoxTiposAccionesFacturasProveedores.setText("Accion");
this.jComboBoxTiposAccionesFacturasProveedores.setToolTipText("Tipos de Acciones");
this.jComboBoxTiposAccionesFormularioFacturasProveedores = new JComboBoxMe();
//this.jComboBoxTiposAccionesFormularioFacturasProveedores.setText("Accion");
this.jComboBoxTiposAccionesFormularioFacturasProveedores.setToolTipText("Tipos de Acciones");
this.jLabelAccionesFacturasProveedores = new JLabelMe();
this.jLabelAccionesFacturasProveedores.setText("Acciones");
this.jLabelAccionesFacturasProveedores.setMinimumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesFacturasProveedores.setMaximumSize(new Dimension(Constantes.ISWING_ANCHO_CONTROL,Constantes.ISWING_ALTO_CONTROL));
this.jLabelAccionesFacturasProveedores.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.inicializarElementosCamposFacturasProveedores();
//ELEMENTOS FK
this.inicializarElementosCamposForeigKeysFacturasProveedores();
//ELEMENTOS TABLAS PARAMETOS
if(!this.conCargarMinimo) {
}
//ELEMENTOS TABLAS PARAMETOS_FIN
//ELEMENTOS TABLAS PARAMETOS_FIN
this.jTabbedPaneRelacionesFacturasProveedores=new JTabbedPane();
this.jTabbedPaneRelacionesFacturasProveedores.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Relacionados"));
//ESTA EN BEAN
FuncionesSwing.setBoldTabbedPane(this.jTabbedPaneRelacionesFacturasProveedores,STIPO_TAMANIO_GENERAL,false,false,this);
int iPosXAccionPaginacion=0;
this.jComboBoxTiposAccionesFacturasProveedores.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesFacturasProveedores.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesFacturasProveedores.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesFacturasProveedores, STIPO_TAMANIO_GENERAL,false,true,this);;
this.jComboBoxTiposAccionesFormularioFacturasProveedores.setMinimumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesFormularioFacturasProveedores.setMaximumSize(new Dimension(145,20));
this.jComboBoxTiposAccionesFormularioFacturasProveedores.setPreferredSize(new Dimension(145,20));
FuncionesSwing.setBoldComboBox(this.jComboBoxTiposAccionesFormularioFacturasProveedores, STIPO_TAMANIO_GENERAL,false,false,this);
GridBagLayout gridaBagLayoutCamposFacturasProveedores = new GridBagLayout();
GridBagLayout gridaBagLayoutCamposOcultosFacturasProveedores = new GridBagLayout();
this.jPanelCamposFacturasProveedores.setLayout(gridaBagLayoutCamposFacturasProveedores);
this.jPanelCamposOcultosFacturasProveedores.setLayout(gridaBagLayoutCamposOcultosFacturasProveedores);
;
;
//SUBPANELES SIMPLES
//SUBPANELES POR CAMPO
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelidFacturasProveedores.add(jLabelIdFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelidFacturasProveedores.add(jLabelidFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelid_empresaFacturasProveedores.add(jLabelid_empresaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelid_empresaFacturasProveedores.add(jButtonid_empresaFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 3;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelid_empresaFacturasProveedores.add(jButtonid_empresaFacturasProveedoresUpdate, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelid_empresaFacturasProveedores.add(jComboBoxid_empresaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelid_clienteFacturasProveedores.add(jLabelid_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelid_clienteFacturasProveedores.add(jButtonid_clienteFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 3;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelid_clienteFacturasProveedores.add(jButtonid_clienteFacturasProveedoresUpdate, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelid_clienteFacturasProveedores.add(jComboBoxid_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelfecha_emision_inicioFacturasProveedores.add(jLabelfecha_emision_inicioFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelfecha_emision_inicioFacturasProveedores.add(jButtonfecha_emision_inicioFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelfecha_emision_inicioFacturasProveedores.add(jDateChooserfecha_emision_inicioFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelfecha_emision_finFacturasProveedores.add(jLabelfecha_emision_finFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelfecha_emision_finFacturasProveedores.add(jButtonfecha_emision_finFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelfecha_emision_finFacturasProveedores.add(jDateChooserfecha_emision_finFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelcodigo_clienteFacturasProveedores.add(jLabelcodigo_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelcodigo_clienteFacturasProveedores.add(jButtoncodigo_clienteFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelcodigo_clienteFacturasProveedores.add(jTextFieldcodigo_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelnombre_clienteFacturasProveedores.add(jLabelnombre_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelnombre_clienteFacturasProveedores.add(jButtonnombre_clienteFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelnombre_clienteFacturasProveedores.add(jscrollPanenombre_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelnumero_facturaFacturasProveedores.add(jLabelnumero_facturaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelnumero_facturaFacturasProveedores.add(jButtonnumero_facturaFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelnumero_facturaFacturasProveedores.add(jTextFieldnumero_facturaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelfecha_emisionFacturasProveedores.add(jLabelfecha_emisionFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelfecha_emisionFacturasProveedores.add(jButtonfecha_emisionFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelfecha_emisionFacturasProveedores.add(jDateChooserfecha_emisionFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPaneltotalFacturasProveedores.add(jLabeltotalFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPaneltotalFacturasProveedores.add(jButtontotalFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPaneltotalFacturasProveedores.add(jTextFieldtotalFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelnumero_pre_impresoFacturasProveedores.add(jLabelnumero_pre_impresoFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelnumero_pre_impresoFacturasProveedores.add(jButtonnumero_pre_impresoFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelnumero_pre_impresoFacturasProveedores.add(jTextFieldnumero_pre_impresoFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelfechaFacturasProveedores.add(jLabelfechaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(this.conMostrarAccionesCampo) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
//this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 2;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(0, 0, 0, 0);
this.jPanelfechaFacturasProveedores.add(jButtonfechaFacturasProveedoresBusqueda, this.gridBagConstraintsFacturasProveedores);
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.HORIZONTAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = 1;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelfechaFacturasProveedores.add(jDateChooserfechaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
//SUBPANELES SIMPLES
//SUBPANELES EN PANEL
//SUBPANELES EN PANEL CAMPOS NORMAL
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelidFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelid_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelfecha_emision_inicioFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelfecha_emision_finFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelcodigo_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelnombre_clienteFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelnumero_facturaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelfecha_emisionFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPaneltotalFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelnumero_pre_impresoFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposFacturasProveedores.add(this.jPanelfechaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposFacturasProveedores % 1==0) {
iXPanelCamposFacturasProveedores=0;
iYPanelCamposFacturasProveedores++;
}
//SUBPANELES EN PANEL CAMPOS OCULTOS
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iYPanelCamposOcultosFacturasProveedores;
this.gridBagConstraintsFacturasProveedores.gridx = iXPanelCamposOcultosFacturasProveedores++;
this.gridBagConstraintsFacturasProveedores.ipadx = 0;
//COLSPAN_NUEVAFILA
this.gridBagConstraintsFacturasProveedores.insets = new Insets(Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING_LEFT, Constantes2.I_CELLSPACING, Constantes2.I_CELLSPACING);
this.jPanelCamposOcultosFacturasProveedores.add(this.jPanelid_empresaFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
if(iXPanelCamposOcultosFacturasProveedores % 1==0) {
iXPanelCamposOcultosFacturasProveedores=0;
iYPanelCamposOcultosFacturasProveedores++;
}
//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 gridaBagLayoutAccionesFacturasProveedores= new GridBagLayout();
this.jPanelAccionesFacturasProveedores.setLayout(gridaBagLayoutAccionesFacturasProveedores);
GridBagLayout gridaBagLayoutAccionesFormularioFacturasProveedores= new GridBagLayout();
this.jPanelAccionesFormularioFacturasProveedores.setLayout(gridaBagLayoutAccionesFormularioFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridYParametrosAccionesFormulario;
this.gridBagConstraintsFacturasProveedores.gridx = iGridXParametrosAccionesFormulario++;
this.jPanelAccionesFormularioFacturasProveedores.add(this.jComboBoxTiposAccionesFormularioFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
int iPosXAccion=0;
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = iPosXAccion++;
this.jPanelAccionesFacturasProveedores.add(this.jButtonModificarFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.VERTICAL;
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx =iPosXAccion++;
this.jPanelAccionesFacturasProveedores.add(this.jButtonEliminarFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = iPosXAccion++;
this.jPanelAccionesFacturasProveedores.add(this.jButtonActualizarFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx = iPosXAccion++;
this.jPanelAccionesFacturasProveedores.add(this.jButtonGuardarCambiosFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = 0;
this.gridBagConstraintsFacturasProveedores.gridx =iPosXAccion++;
this.jPanelAccionesFacturasProveedores.add(this.jButtonCancelarFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
//this.setJProgressBarToJPanel();
GridBagLayout gridaBagLayoutFacturasProveedores = new GridBagLayout();
this.jContentPane.setLayout(gridaBagLayoutFacturasProveedores);
if(this.parametroGeneralUsuario.getcon_botones_tool_bar() && !this.facturasproveedoresSessionBean.getEsGuardarRelacionado()) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyPrincipal++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
//this.gridBagConstraintsFacturasProveedores.fill =GridBagConstraints.VERTICAL;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.CENTER;//.CENTER;NORTH
this.gridBagConstraintsFacturasProveedores.ipadx = 100;
}
//PROCESANDO EN OTRA PANTALLA
int iGridxBusquedasParametros=0;
//PARAMETROS TABLAS PARAMETROS
if(!this.conCargarMinimo) {
//NO BUSQUEDA
}
//PARAMETROS TABLAS PARAMETROS_FIN
//PARAMETROS REPORTES
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy =iGridyPrincipal++;
this.gridBagConstraintsFacturasProveedores.gridx =0;
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.BOTH;
//this.gridBagConstraintsFacturasProveedores.ipady =150;
this.jContentPane.add(this.jScrollPanelDatosFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
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(FacturasProveedoresJInternalFrame.CON_DATOS_FRAME) {
//this.jInternalFrameDetalleFacturasProveedores = new FacturasProveedoresBeanSwingJInternalFrameAdditional();//JInternalFrameBase("Facturas Proveedores 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] - Facturas Proveedores DATOS");
this.setTitle(Funciones.GetTituloSistema(this.parametroGeneralSg,this.moduloActual,this.usuarioActual,"Facturas Proveedores 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);
FacturasProveedoresModel facturasproveedoresModel=new FacturasProveedoresModel(this);
//SI USARA CLASE INTERNA
//FacturasProveedoresModel.FacturasProveedoresFocusTraversalPolicy facturasproveedoresFocusTraversalPolicy = facturasproveedoresModel.new FacturasProveedoresFocusTraversalPolicy(this);
//facturasproveedoresFocusTraversalPolicy.setfacturasproveedoresJInternalFrame(this);
this.setFocusTraversalPolicy(facturasproveedoresModel);
this.jContentPaneDetalleFacturasProveedores = new JPanelMe(FuncionesSwing.getFondoImagen(parametroGeneralUsuario.getid_tipo_fondo()),true);//new JPanel();
int iGridyRelaciones=0;
GridBagLayout gridaBagLayoutDetalleFacturasProveedores = new GridBagLayout();
this.jContentPaneDetalleFacturasProveedores.setLayout(gridaBagLayoutDetalleFacturasProveedores);
GridBagLayout gridaBagLayoutBusquedasParametrosFacturasProveedores = new GridBagLayout();
if(this.parametroGeneralUsuario.getcon_botones_tool_bar()) {
//AGREGA TOOLBAR DETALLE A PANTALLA
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyRelaciones++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPaneDetalleFacturasProveedores.add(jTtoolBarDetalleFacturasProveedores, gridBagConstraintsFacturasProveedores);
}
this.jScrollPanelDatosEdicionFacturasProveedores= new JScrollPane(jContentPaneDetalleFacturasProveedores,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosEdicionFacturasProveedores.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionFacturasProveedores.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionFacturasProveedores.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralFacturasProveedores= new JScrollPane(jContentPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosGeneralFacturasProveedores.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralFacturasProveedores.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosGeneralFacturasProveedores.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyRelaciones++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPaneDetalleFacturasProveedores.add(jPanelCamposFacturasProveedores, gridBagConstraintsFacturasProveedores);
//if(!this.conCargarMinimo) {
;
//}
this.conMaximoRelaciones=true;
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
//&& facturasproveedoresSessionBean.getConGuardarRelaciones()
) {
//paraCargarPorParte es false por defecto(y ejecuta funcion normal cargando detalle en tab panel), si se utiliza funcionalidad es true y carga tab panel auxiliar temporal
if(this.facturasproveedoresSessionBean.getConGuardarRelaciones()) {
this.gridBagConstraintsFacturasProveedores= new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyRelaciones++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPaneDetalleFacturasProveedores.add(this.jTabbedPaneRelacionesFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
}
//RELACIONES OTROS AGRUPADOS
;
} else {
//this.jButtonNuevoRelacionesFacturasProveedores.setVisible(false);
}
}
}
Boolean tieneColumnasOcultas=false;
tieneColumnasOcultas=true;
if(!Constantes.ISDEVELOPING) {
this.jPanelCamposOcultosFacturasProveedores.setVisible(false);
} else {
if(tieneColumnasOcultas) {
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.fill=GridBagConstraints.NONE;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.gridBagConstraintsFacturasProveedores.gridy = iGridyRelaciones++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPaneDetalleFacturasProveedores.add(jPanelCamposOcultosFacturasProveedores, gridBagConstraintsFacturasProveedores);
this.jPanelCamposOcultosFacturasProveedores.setVisible(true);
}
}
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyRelaciones++;//1;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.CENTER;//WEST;
this.jContentPaneDetalleFacturasProveedores.add(this.jPanelAccionesFormularioFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyRelaciones;//1;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPaneDetalleFacturasProveedores.add(this.jPanelAccionesFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
//this.setContentPane(jScrollPanelDatosEdicionFacturasProveedores);
//} 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.jScrollPanelDatosEdicionFacturasProveedores= new JScrollPane(this.jPanelCamposFacturasProveedores,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.jScrollPanelDatosEdicionFacturasProveedores.setMinimumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionFacturasProveedores.setMaximumSize(new Dimension(iWidthScroll,iHeightScroll));
this.jScrollPanelDatosEdicionFacturasProveedores.setPreferredSize(new Dimension(iWidthScroll,iHeightScroll));
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyPrincipal++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.gridBagConstraintsFacturasProveedores.fill = GridBagConstraints.BOTH;
this.gridBagConstraintsFacturasProveedores.ipady = this.getSize().height-yOffset*3;
this.gridBagConstraintsFacturasProveedores.anchor = GridBagConstraints.WEST;
this.jContentPane.add(this.jScrollPanelDatosEdicionFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
//ACCIONES FORMULARIO
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy =iGridyPrincipal++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPane.add(this.jPanelAccionesFormularioFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy =iGridyPrincipal++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPane.add(this.jPanelAccionesFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
*/
//}
//DISENO_DETALLE-(Descomentar)
/*
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyPrincipal++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPane.add(this.jPanelCamposFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy = iGridyPrincipal++;
this.gridBagConstraintsFacturasProveedores.gridx = 0;
this.jContentPane.add(this.jPanelCamposOcultosFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
this.gridBagConstraintsFacturasProveedores = new GridBagConstraints();
this.gridBagConstraintsFacturasProveedores.gridy =iGridyPrincipal++;
this.gridBagConstraintsFacturasProveedores.gridx =0;
this.jContentPane.add(this.jPanelAccionesFacturasProveedores, this.gridBagConstraintsFacturasProveedores);
*/
//pack();
//return this.jScrollPanelDatosGeneralFacturasProveedores;//jContentPane;
return jScrollPanelDatosEdicionFacturasProveedores;
}
/*
case "CONTROL_BUSQUEDA":
sKeyName="F3";
case "CONTROL_BUSCAR":
sKeyName="F4";
case "CONTROL_ARBOL":
sKeyName="F5";
case "CONTROL_ACTUALIZAR":
sKeyName="F6";
sKeyName="N";
*/
}
| 59.687964 | 388 | 0.838237 |
c6c93f52a476f688d66b05e859a91467425b4762 | 13,682 | package com.seventh_root.atherna.command;
import com.seventh_root.atherna.Atherna;
import com.seventh_root.atherna.character.AthernaCharacter;
import com.seventh_root.atherna.classes.AthernaClass;
import com.seventh_root.atherna.player.AthernaPlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import static java.lang.Integer.parseInt;
import static org.bukkit.ChatColor.*;
public class ClassCommand implements CommandExecutor {
private Atherna plugin;
public ClassCommand(Atherna plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("set")) {
classSet(sender, args);
} else if (args[0].equalsIgnoreCase("info")) {
if (classInfo(sender, label, args)) return true;
} else if (args[0].equalsIgnoreCase("list")) {
classList(sender);
} else if (args[0].equalsIgnoreCase("setlevel")) {
if (classSetLevel(sender, label, args)) return true;
} else if (args[0].equalsIgnoreCase("addexp")) {
if (classAddExp(sender, label, args)) return true;
} else {
sender.sendMessage(RED + "Usage: /" + label + " [set|info|list" +
(sender.hasPermission("atherna.command.class.setlevel") ? "|setlevel" : "") +
(sender.hasPermission("atherna.command.class.addexp") ? "|addexp" : "") +
"]"
);
}
} else {
sender.sendMessage(RED + "Usage: /" + label + " [set|info|list" +
(sender.hasPermission("atherna.command.class.setlevel") ? "|setlevel" : "") +
(sender.hasPermission("atherna.command.class.addexp") ? "|addexp" : "") +
"]"
);
}
return true;
}
private boolean classAddExp(CommandSender sender, String label, String[] args) {
if (sender.hasPermission("atherna.command.class.addexp")) {
Player bukkitPlayer = null;
int experience;
if (args.length > 2) {
String playerName = args[1];
bukkitPlayer = plugin.getServer().getPlayer(playerName);
experience = parseInt(args[2]);
} else if (args.length > 1) {
experience = parseInt(args[1]);
} else {
return true;
}
if (bukkitPlayer == null) {
if (sender instanceof Player) {
bukkitPlayer = (Player) sender;
} else {
sender.sendMessage(RED + "You are not a player, please specify a valid player name");
return true;
}
}
AthernaPlayer player = plugin.getPlayerManager().getByBukkitPlayer(bukkitPlayer);
if (player != null) {
AthernaCharacter character = player.getActiveCharacter();
if (character != null) {
AthernaClass athernaClass = character.getAthernaClass();
if (athernaClass != null) {
int initialExperience = plugin.getClassManager().getTotalExperience(character, athernaClass);
plugin.getClassManager().setTotalExperience(character, athernaClass,
plugin.getClassManager().getTotalExperience(character, athernaClass) + experience);
int finalExperience = plugin.getClassManager().getTotalExperience(character, athernaClass);
int experienceDiff = finalExperience - initialExperience;
sender.sendMessage(GREEN + "Gave " + character.getName() + " " + experienceDiff + " experience");
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have a class. Set one with /" + label + " set [class]");
} else {
sender.sendMessage(RED + "That player does not currently have a class");
}
}
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have a character");
} else {
sender.sendMessage(RED + "That player does not currently have a character");
}
}
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have an Atherna player associated");
} else {
sender.sendMessage(RED + "That player currently does not have an Atherna player associated");
}
}
} else {
sender.sendMessage(RED + "You do not have permission to perform that command");
}
return false;
}
private boolean classSetLevel(CommandSender sender, String label, String[] args) {
if (sender.hasPermission("atherna.command.class.setlevel")) {
Player bukkitPlayer = null;
int level;
if (args.length > 2) {
String playerName = args[1];
bukkitPlayer = plugin.getServer().getPlayer(playerName);
level = parseInt(args[2]);
} else if (args.length > 1) {
level = parseInt(args[1]);
} else {
return true;
}
if (bukkitPlayer == null) {
if (sender instanceof Player) {
bukkitPlayer = (Player) sender;
} else {
sender.sendMessage(RED + "You are not a player, please specify a valid player name");
return true;
}
}
AthernaPlayer player = plugin.getPlayerManager().getByBukkitPlayer(bukkitPlayer);
if (player != null) {
AthernaCharacter character = player.getActiveCharacter();
if (character != null) {
AthernaClass athernaClass = character.getAthernaClass();
if (athernaClass != null) {
plugin.getClassManager().setLevel(character, athernaClass, level);
sender.sendMessage(GREEN + "Set " + character.getName() + "'s level to " +
plugin.getClassManager().getLevel(character, athernaClass));
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have a class. Set one with /" + label + " set [class]");
} else {
sender.sendMessage(RED + "That player does not currently have a class");
}
}
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have a character");
} else {
sender.sendMessage(RED + "That player does not currently have a character");
}
}
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have an Atherna player associated");
} else {
sender.sendMessage(RED + "That player currently does not have an Atherna player associated");
}
}
} else {
sender.sendMessage(RED + "You do not have permission to perform that command");
}
return false;
}
private void classList(CommandSender sender) {
sender.sendMessage(GOLD + "Class list:");
plugin.getClassManager().getAthernaClasses().forEach(athernaClass -> sender.sendMessage(GRAY + " - " + athernaClass.getName()));
}
private boolean classInfo(CommandSender sender, String label, String[] args) {
Player bukkitPlayer;
if (args.length > 1) {
String playerName = args[0];
bukkitPlayer = plugin.getServer().getPlayer(playerName);
} else {
if (sender instanceof Player) {
bukkitPlayer = (Player) sender;
} else {
sender.sendMessage(RED + "You are not a player, please specify a valid player name");
return true;
}
}
AthernaPlayer player = plugin.getPlayerManager().getByBukkitPlayer(bukkitPlayer);
if (player != null) {
AthernaCharacter character = player.getActiveCharacter();
if (character != null) {
AthernaClass currentClass = character.getAthernaClass();
if (currentClass != null) {
sender.sendMessage(GRAY + "Current class: " + GOLD + currentClass.getName() + GRAY + " - " +
GOLD + "Lv" + plugin.getClassManager().getLevel(character, currentClass) +
(plugin.getClassManager().getLevel(character, currentClass) < currentClass.getMaxLevel() ? (
GRAY + " [ " +
GOLD + plugin.getClassManager().getExperienceTowardsNextLevel(character, currentClass) +
GRAY + " / " +
GOLD + plugin.getClassManager().getExperienceForLevel(plugin.getClassManager().getLevel(character, currentClass) + 1) +
GRAY + " exp ]"
) : (GRAY + " [ " + GOLD + "MAX LEVEL" + GRAY + " ]"))
);
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have a class. Set one with /" + label + " set [class]");
} else {
sender.sendMessage(RED + "That player does not currently have a class");
}
}
sender.sendMessage(GRAY + "All classes levelled on this character: ");
plugin.getClassManager().getAthernaClasses().stream().filter(
athernaClass -> plugin.getClassManager().getTotalExperience(character, athernaClass) > 0)
.forEach(athernaClass -> {
sender.sendMessage(GRAY + athernaClass.getName() + ": " +
GOLD + "Lv" + plugin.getClassManager().getLevel(character, athernaClass) +
(plugin.getClassManager().getLevel(character, athernaClass) < athernaClass.getMaxLevel() ? (
GRAY + " [ " +
GOLD + plugin.getClassManager().getExperienceTowardsNextLevel(character, athernaClass) +
GRAY + " / " +
GOLD + plugin.getClassManager().getExperienceForLevel(plugin.getClassManager().getLevel(character, athernaClass) + 1) +
GRAY + " exp ]"
) : (GRAY + " [ " + GOLD + "MAX LEVEL" + GRAY + " ]"))
);
});
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have a character");
} else {
sender.sendMessage(RED + "That player does not currently have a character");
}
}
} else {
if (bukkitPlayer == sender) {
sender.sendMessage(RED + "You do not currently have an Atherna player associated");
} else {
sender.sendMessage(RED + "That player currently does not have an Atherna player associated");
}
}
return false;
}
private void classSet(CommandSender sender, String[] args) {
if (sender instanceof Player) {
Player bukkitPlayer = (Player) sender;
AthernaPlayer player = plugin.getPlayerManager().getByBukkitPlayer(bukkitPlayer);
if (player != null) {
AthernaCharacter character = player.getActiveCharacter();
if (character != null) {
if (args.length > 1) {
AthernaClass athernaClass = plugin.getClassManager().getByName(args[1]);
if (athernaClass != null) {
character.setAthernaClass(athernaClass);
sender.sendMessage(GREEN + "Class set to " + athernaClass.getName());
} else {
sender.sendMessage(RED + "That class does not exist");
}
} else {
sender.sendMessage(RED + "You must specify a class");
}
} else {
sender.sendMessage(RED + "You do not currently have a character");
}
} else {
sender.sendMessage(RED + "You do not currently have a player");
}
} else {
sender.sendMessage(RED + "You are not a player");
}
}
}
| 50.117216 | 159 | 0.507967 |
c223fc27cc4f6a829359b18cdb4157a16c32c230 | 4,732 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.squareup.leakcanary.internal;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import com.squareup.leakcanary.*;
public final class HeapAnalyzerService extends IntentService
{
public HeapAnalyzerService()
{
super(((Class) (com/squareup/leakcanary/internal/HeapAnalyzerService)).getSimpleName());
// 0 0:aload_0
// 1 1:ldc1 #2 <Class HeapAnalyzerService>
// 2 3:invokevirtual #19 <Method String Class.getSimpleName()>
// 3 6:invokespecial #22 <Method void IntentService(String)>
// 4 9:return
}
public static void runAnalysis(Context context, HeapDump heapdump, Class class1)
{
Intent intent = new Intent(context, com/squareup/leakcanary/internal/HeapAnalyzerService);
// 0 0:new #27 <Class Intent>
// 1 3:dup
// 2 4:aload_0
// 3 5:ldc1 #2 <Class HeapAnalyzerService>
// 4 7:invokespecial #30 <Method void Intent(Context, Class)>
// 5 10:astore_3
intent.putExtra("listener_class_extra", class1.getName());
// 6 11:aload_3
// 7 12:ldc1 #11 <String "listener_class_extra">
// 8 14:aload_2
// 9 15:invokevirtual #33 <Method String Class.getName()>
// 10 18:invokevirtual #37 <Method Intent Intent.putExtra(String, String)>
// 11 21:pop
intent.putExtra("heapdump_extra", ((java.io.Serializable) (heapdump)));
// 12 22:aload_3
// 13 23:ldc1 #8 <String "heapdump_extra">
// 14 25:aload_1
// 15 26:invokevirtual #40 <Method Intent Intent.putExtra(String, java.io.Serializable)>
// 16 29:pop
context.startService(intent);
// 17 30:aload_0
// 18 31:aload_3
// 19 32:invokevirtual #46 <Method android.content.ComponentName Context.startService(Intent)>
// 20 35:pop
// 21 36:return
}
protected void onHandleIntent(Intent intent)
{
if(intent == null)
//* 0 0:aload_1
//* 1 1:ifnonnull 14
{
CanaryLog.d("HeapAnalyzerService received a null intent, ignoring.", new Object[0]);
// 2 4:ldc1 #52 <String "HeapAnalyzerService received a null intent, ignoring.">
// 3 6:iconst_0
// 4 7:anewarray Object[]
// 5 10:invokestatic #60 <Method void CanaryLog.d(String, Object[])>
return;
// 6 13:return
} else
{
String s = intent.getStringExtra("listener_class_extra");
// 7 14:aload_1
// 8 15:ldc1 #11 <String "listener_class_extra">
// 9 17:invokevirtual #64 <Method String Intent.getStringExtra(String)>
// 10 20:astore_2
intent = ((Intent) ((HeapDump)intent.getSerializableExtra("heapdump_extra")));
// 11 21:aload_1
// 12 22:ldc1 #8 <String "heapdump_extra">
// 13 24:invokevirtual #68 <Method java.io.Serializable Intent.getSerializableExtra(String)>
// 14 27:checkcast #70 <Class HeapDump>
// 15 30:astore_1
AbstractAnalysisResultService.sendResultToListener(((Context) (this)), s, ((HeapDump) (intent)), (new HeapAnalyzer(((HeapDump) (intent)).excludedRefs)).checkForLeak(((HeapDump) (intent)).heapDumpFile, ((HeapDump) (intent)).referenceKey));
// 16 31:aload_0
// 17 32:aload_2
// 18 33:aload_1
// 19 34:new #72 <Class HeapAnalyzer>
// 20 37:dup
// 21 38:aload_1
// 22 39:getfield #76 <Field com.squareup.leakcanary.ExcludedRefs HeapDump.excludedRefs>
// 23 42:invokespecial #79 <Method void HeapAnalyzer(com.squareup.leakcanary.ExcludedRefs)>
// 24 45:aload_1
// 25 46:getfield #83 <Field java.io.File HeapDump.heapDumpFile>
// 26 49:aload_1
// 27 50:getfield #86 <Field String HeapDump.referenceKey>
// 28 53:invokevirtual #90 <Method com.squareup.leakcanary.AnalysisResult HeapAnalyzer.checkForLeak(java.io.File, String)>
// 29 56:invokestatic #96 <Method void AbstractAnalysisResultService.sendResultToListener(Context, String, HeapDump, com.squareup.leakcanary.AnalysisResult)>
return;
// 30 59:return
}
}
private static final String HEAPDUMP_EXTRA = "heapdump_extra";
private static final String LISTENER_CLASS_EXTRA = "listener_class_extra";
}
| 45.5 | 241 | 0.613905 |
9d33c776c42c184499ec4d3e9dfa804c956d961d | 5,052 | package com.paypal.udc.service.impl;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import com.paypal.udc.config.UDCInterceptorConfig;
import com.paypal.udc.dao.ClusterRepository;
import com.paypal.udc.entity.Cluster;
import com.paypal.udc.interceptor.UDCInterceptor;
import com.paypal.udc.util.UserUtil;
import com.paypal.udc.util.enumeration.ActiveEnumeration;
import com.paypal.udc.validator.cluster.ClusterDescValidator;
import com.paypal.udc.validator.cluster.ClusterLivyEndpointValidator;
import com.paypal.udc.validator.cluster.ClusterLivyPortValidator;
import com.paypal.udc.validator.cluster.ClusterNameValidator;
@RunWith(SpringRunner.class)
public class ClusterServiceTest {
@MockBean
private UDCInterceptor udcInterceptor;
@MockBean
private UDCInterceptorConfig udcInterceptorConfig;
@MockBean
private UserUtil userUtil;
@Mock
private ClusterRepository clusterRepository;
@Mock
private ClusterDescValidator s2;
@Mock
private ClusterLivyEndpointValidator s4;
@Mock
private ClusterLivyPortValidator s3;
@Mock
private ClusterNameValidator s1;
@InjectMocks
private ClusterService clusterService;
private long clusterId;
private String clusterName;
private Cluster cluster;
private List<Cluster> clusterList;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.clusterId = 1L;
this.clusterName = "Cluster1";
this.cluster = new Cluster(this.clusterId, this.clusterName, "Description", "a.b.c.d", 8989, "Y", "CrUser",
"CrTime",
"UpdUser", "UpdTime");
this.clusterList = Arrays.asList(this.cluster);
}
@Test
public void verifyValidGetAllClusters() throws Exception {
when(this.clusterRepository.findAll()).thenReturn(this.clusterList);
final List<Cluster> result = this.clusterService.getAllClusters();
assertEquals(this.clusterList.size(), result.size());
verify(this.clusterRepository).findAll();
}
@Test
public void verifyValidGetClusterById() throws Exception {
when(this.clusterRepository.findOne(this.clusterId)).thenReturn(this.cluster);
final Cluster result = this.clusterService.getClusterById(this.clusterId);
assertEquals(this.cluster, result);
verify(this.clusterRepository).findOne(this.clusterId);
}
@Test
public void verifyValidGetClusterByName() throws Exception {
when(this.clusterRepository.findByClusterName(this.clusterName)).thenReturn(this.cluster);
final Cluster result = this.clusterService.getClusterByName(this.clusterName);
assertEquals(this.cluster, result);
verify(this.clusterRepository).findByClusterName(this.clusterName);
}
@Test
public void verifyValidAddCluster() throws Exception {
when(this.clusterRepository.save(this.cluster)).thenReturn(this.cluster);
final Cluster result = this.clusterService.addCluster(this.cluster);
assertEquals(this.cluster, result);
verify(this.clusterRepository).save(this.cluster);
}
@Test
public void verifyValidUpdateCluster() throws Exception {
when(this.clusterRepository.findOne(this.clusterId)).thenReturn(this.cluster);
when(this.clusterRepository.save(this.cluster)).thenReturn(this.cluster);
final Cluster result = this.clusterService.updateCluster(this.cluster);
assertEquals(this.cluster, result);
verify(this.clusterRepository).save(this.cluster);
}
@Test
public void verifyValidDeActivateCluster() throws Exception {
when(this.clusterRepository.findOne(this.clusterId)).thenReturn(this.cluster);
when(this.clusterRepository.save(this.cluster)).thenReturn(this.cluster);
final Cluster result = this.clusterService.deActivateCluster(this.clusterId);
assertEquals(this.cluster, result);
assertEquals(ActiveEnumeration.NO.getFlag(), result.getIsActiveYN());
verify(this.clusterRepository).save(this.cluster);
}
@Test
public void verifyValidReActivateCluster() throws Exception {
when(this.clusterRepository.findOne(this.clusterId)).thenReturn(this.cluster);
when(this.clusterRepository.save(this.cluster)).thenReturn(this.cluster);
final Cluster result = this.clusterService.reActivateCluster(this.clusterId);
assertEquals(this.cluster, result);
assertEquals(ActiveEnumeration.YES.getFlag(), result.getIsActiveYN());
verify(this.clusterRepository).save(this.cluster);
}
}
| 33.68 | 115 | 0.735748 |
eb845f61d2e52c96ef39c7a5e180270ad9a79717 | 340 | package site.higgs.limiter.interceptor;
import java.lang.reflect.Method;
import java.util.Collection;
/**
* 定义limiter的来源
*/
public interface LimiterOperationSource {
/**
*
* @param method
* @param clazz
* @return
*/
Collection<LimiterOperation> getLimiterOperations(Method method, Class<?> clazz);
}
| 17 | 86 | 0.673529 |
b609ad374a7a724be888d4ec601235255b020e1c | 96 | package com.github.binarywang.wxpay.bean.result;
public class WxPaySendRedpackResultTest {
}
| 13.714286 | 48 | 0.8125 |
26d320c08871baa79aeabb0c48148d0916ca4534 | 13,099 | package bouyomi;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import bouyomi.Counter.CountData;
import bouyomi.Counter.CountData.Count;
import bouyomi.Util.Admin;
import bouyomi.Util.Pass;
import bouyomi.Util.SaveProxyData;
/**棒読みちゃん専用のプロキシです*/
public class BouyomiProxy{
public static HashMap<String,String> Config=new HashMap<String,String>();
private static String command;//コンソールに入力されたテキスト
public static int proxy_port;//棒読みちゃんのポート(サーバはlocalhost固定)
public static long lastComment=System.currentTimeMillis();
public static ModuleLoader module;
public static Admin admin;
public static SaveProxyData study_log;
public static String log_guild=null,log_channel=null;
//main関数、スタート地点
public static void main(String[] args) throws IOException{
long time=System.currentTimeMillis();
Boot.load("config.conf");
InputStreamReader isr=new InputStreamReader(System.in);
final BufferedReader br=new BufferedReader(isr);//コンソールから1行ずつ取得する為のオブジェクト
if(args.length>0&&!args[0].equals("-"))command=args[0];
else {
System.out.println("プロキシサーバのポート(半角数字)");
command=br.readLine();//1行取得する
}
//0文字だったらデフォルト、それ以外だったら数値化
proxy_port=command.isEmpty()?50003:Integer.parseInt(command);
System.out.println("プロキシサーバのポート"+proxy_port);
if(args.length>1) {
if(args[1].equals("-"))command="";
else command=args[1];
}else {
System.out.println("デフォルトの投稿先BOTのID");
command=br.readLine();//1行取得する
}
//0文字だったら無し、それ以外だったらそれ
if(!command.isEmpty()) {
for(DiscordBOT b:DiscordBOT.bots) {
if(b.jda.getSelfUser().getId().equals(command)) {
DiscordBOT.DefaultHost=b;
break;
}
}
}
System.out.println("デフォルトの投稿先BOTのID"+(DiscordBOT.DefaultHost==null?"無し":DiscordBOT.DefaultHost.jda.getSelfUser().getName()));
if(args.length>2) {
if(args[2].equals("-"))command="";
else command=args[2];
}
//0文字だったら無し、それ以外だったらそれ
File modulePath=null;
if(!command.isEmpty()) {
module=new ModuleLoader();
modulePath=new File(command);
}
ServerSocket ss=new ServerSocket(proxy_port);//サーバ開始
new Thread("CommandReader"){
public void run(){
while(true){
try{
command=br.readLine();//1行取得する
if(command==null) System.exit(1);//読み込み失敗した場合終了
if(command.indexOf("clear")>=0) {
System.out.println("入力クリア="+command);
}else if(command.equals("setCounter")) {
System.out.println("ユーザIDを入力");
command=br.readLine();//1行取得する
CountData cd=Counter.usercount.get(command);
for(String id:Counter.usercount.keySet()) {
CountData c=Counter.usercount.get(id);
if(c!=null&&c.name.equals(command))cd=c;
}
if(cd==null) {
System.out.println("新規登録");
System.out.println("ID="+command);
String id=command;
System.out.println("ユーザ名を入力");
command=br.readLine();//1行取得する
if(command.isEmpty())continue;
cd=new CountData(command);
Counter.usercount.put(id,cd);
}
System.out.println("ユーザ名="+cd.name);
System.out.println("カウント単語を入力");
String w=br.readLine();
Count c=cd.count.get(w);
if(c==null)continue;
try{
System.out.println("現在の数値"+c.count);
c.count=Long.parseLong(command=br.readLine());
System.out.println(w+"のカウントを"+c.count+"に変更");
}catch(NumberFormatException e) {
}
}else if("saveConfig".equals(command)) {
try{
save(Config,"config.txt");
}catch(IOException e){
e.printStackTrace();
}
}else if("addPass".equals(command)) {
Pass.addPass();
}else if("exit".equals(command)){
ss.close();//サーバ終了
System.exit(0);//プログラム終了
}else talk("localhost:"+proxy_port,command);
}catch(IOException e){//コンソールから取得できない時終了
System.exit(1);
}
}
}
}.start();
IAutoSave.thread();
DailyUpdate.init();
try{
load(Config,"config.txt");
}catch(IOException e){
e.printStackTrace();
}
IAutoSave.Register(new IAutoSave() {
private int hash=Config.hashCode();
@Override
public void autoSave() throws IOException{
int hc=Config.hashCode();
if(hash==hc)return;
hash=hc;
shutdownHook();
}
@Override
public void shutdownHook() {
try{
save(Config,"config.txt");
}catch(IOException e){
e.printStackTrace();
}
}
});
Counter.init();
admin=new Admin();
Pass.read();
study_log=new SaveProxyData("教育者.txt");
if(module!=null) {
module.load(modulePath);
if(!module.isActive())module=null;
}
System.out.println("モジュール"+(module==null||!module.isActive()?"無し":module.path));
DailyUpdate.updater.start();
//スレッドプールを用意(最低1スレッド維持、空きスレッド60秒維持)
ExecutorService pool=new ThreadPoolExecutor(1, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
System.out.println("起動時間合計"+(System.currentTimeMillis()-time)+"ms");
System.out.println("exitで終了");
int threads=0;
while(true){//無限ループ
threads++;
try{
if(threads>3)System.err.println("警告:実行中のメッセージスレッドが"+threads+"件です");
Socket s=ss.accept();//サーバ受付
BouyomiConection r=new BouyomiTCPConection(s);//接続単位でインスタンス生成
pool.execute(r);//スレッドプールで実行する
}catch(IOException e){//例外は無視
try{
Thread.sleep(100);
}catch(InterruptedException e1){
e1.printStackTrace();
}
}
threads--;
}
}
public static void load(List<String> list,String path) throws IOException {
list.clear();
FileInputStream fos=new FileInputStream(path);
InputStreamReader isr=new InputStreamReader(fos,StandardCharsets.UTF_8);
BufferedReader br=new BufferedReader(isr);
try {
while(true) {
String line=br.readLine();
if(line==null)break;
list.add(line);
}
}catch(FileNotFoundException fnf){
}finally {
br.close();
}
}
public static void load(Map<String,String> map,String path) throws IOException {
load(map,path,true);
}
public static void load(Map<String,String> map,String path,boolean log) throws IOException {
map.clear();
FileInputStream fos=new FileInputStream(path);
InputStreamReader isr=new InputStreamReader(fos,StandardCharsets.UTF_8);
BufferedReader br=new BufferedReader(isr);
if(log)System.out.println("========="+path+"==============");
try {
while(true) {
String line=br.readLine();
if(line==null)break;
int tab=line.indexOf('\t');
if(tab<0||tab+1>line.length()) {
map.put(line,"");//タブがない時ORフォーマットがおかしいときは行をキーにして値を0文字に
continue;
}
String key=line.substring(0,tab);
String val=line.substring(tab+1);
if(log)System.out.println("k="+key+" v="+val);
map.put(key,val);
}
}catch(FileNotFoundException fnf){
}finally {
br.close();
}
}
public static void save(List<String> list,String path) throws IOException {
FileOutputStream fos=new FileOutputStream(path);
final OutputStreamWriter osw=new OutputStreamWriter(fos,StandardCharsets.UTF_8);
try {
for(String s:list) {
osw.write(s);
osw.append('\n');
}
}finally {
osw.flush();
osw.close();
}
}
public static void save(Map<String,String> map,String path) throws IOException {
save(map,path,true);
}
public static void save(Map<String,String> map,String path,boolean log) throws IOException {
FileOutputStream fos=new FileOutputStream(path);
final OutputStreamWriter osw=new OutputStreamWriter(fos,StandardCharsets.UTF_8);
if(log)System.out.println("========="+path+"==============");
try {
map.forEach(new BiConsumer<String,String>(){
@Override
public void accept(String key,String val){
try{
osw.write(key);
osw.write("\t");
osw.write(val);
osw.write("\n");
if(log)System.out.println("k="+key+" v="+val);
}catch(IOException e){
e.printStackTrace();
}
}
});
}finally {
osw.flush();
osw.close();
}
}
public static int ConectionTest(String host) {
Socket soc=null;
try{
//System.out.println("棒読みちゃんに接続");
int tab=host.indexOf(':');
if(tab<0||tab+1>host.length()) {
soc=new Socket("localhost",Integer.parseInt(host));
}else {
String key=host.substring(0,tab);
String val=host.substring(tab+1);
soc=new Socket(key,Integer.parseInt(val));
}
soc.setSoTimeout(1000);
OutputStream os=soc.getOutputStream();
//System.out.println("棒読みちゃんに接続完了"+host);
short volume=-1;//音量 棒読みちゃん設定
short speed=-1;//速度 棒読みちゃん設定
short tone=-1;//音程 棒読みちゃん設定
short voice=0;//声質 棒読みちゃん設定
byte messageData[]=null;
try{
messageData="。".getBytes("UTF-8");
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
int length=messageData.length;
byte data[]=new byte[15+length];
data[0]=(byte) 1; // コマンド 1桁目
data[1]=(byte) 0; // コマンド 2桁目
data[2]=(byte) ((speed>>>0)&0xFF); // 速度 1桁目
data[3]=(byte) ((speed>>>8)&0xFF); // 速度 2桁目
data[4]=(byte) ((tone>>>0)&0xFF); // 音程 1桁目
data[5]=(byte) ((tone>>>8)&0xFF); // 音程 2桁目
data[6]=(byte) ((volume>>>0)&0xFF); // 音量 1桁目
data[7]=(byte) ((volume>>>8)&0xFF); // 音量 2桁目
data[8]=(byte) ((voice>>>0)&0xFF); // 声質 1桁目
data[9]=(byte) ((voice>>>8)&0xFF); // 声質 2桁目
data[10]=(byte) 0; // エンコード(0: UTF-8)
data[11]=(byte) ((length>>>0)&0xFF); // 長さ 1桁目
data[12]=(byte) ((length>>>8)&0xFF); // 長さ 2桁目
data[13]=(byte) ((length>>>16)&0xFF); // 長さ 3桁目
data[14]=(byte) ((length>>>24)&0xFF); // 長さ 4桁目
System.arraycopy(messageData,0,data,15,length);
send(host,data);
os.write(data);
return 0;
}catch(ConnectException e) {
return 1;
}catch(UnknownHostException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally {
try{
if(soc!=null)soc.close();
}catch(IOException e){
e.printStackTrace();
}
}
return 2;
}
private static int send_errors;
/**棒読みちゃんに送信する
* @param host */
public synchronized static void send(String host, byte[] data){
//System.out.println("棒読みちゃんに接続開始"+host);
Socket soc=null;
try{
//System.out.println("棒読みちゃんに接続");
int tab=host.indexOf(':');
if(tab<0||tab+1>host.length()) {
soc=new Socket("localhost",Integer.parseInt(host));
}else {
String key=host.substring(0,tab);
String val=host.substring(tab+1);
soc=new Socket(key,Integer.parseInt(val));
}
soc.setSoTimeout(1000);
OutputStream os=soc.getOutputStream();
//System.out.println("棒読みちゃんに接続完了"+host);
os.write(data);
send_errors=0;
}catch(ConnectException e) {
send_errors++;
if(send_errors==5)System.err.println("棒読みちゃんに接続できません-"+host);
}catch(UnknownHostException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally {
try{
if(soc!=null)soc.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
/**文字列を送信
* @param command2 */
public static void talk(String host,String message){
//System.out.println("タスク実行="+message);
short volume=-1;//音量 棒読みちゃん設定
short speed=-1;//速度 棒読みちゃん設定
short tone=-1;//音程 棒読みちゃん設定
short voice=0;//声質 棒読みちゃん設定
byte messageData[]=null;
try{
messageData=message.getBytes("UTF-8");
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
int length=messageData.length;
byte data[]=new byte[15+length];
data[0]=(byte) 1; // コマンド 1桁目
data[1]=(byte) 0; // コマンド 2桁目
data[2]=(byte) ((speed>>>0)&0xFF); // 速度 1桁目
data[3]=(byte) ((speed>>>8)&0xFF); // 速度 2桁目
data[4]=(byte) ((tone>>>0)&0xFF); // 音程 1桁目
data[5]=(byte) ((tone>>>8)&0xFF); // 音程 2桁目
data[6]=(byte) ((volume>>>0)&0xFF); // 音量 1桁目
data[7]=(byte) ((volume>>>8)&0xFF); // 音量 2桁目
data[8]=(byte) ((voice>>>0)&0xFF); // 声質 1桁目
data[9]=(byte) ((voice>>>8)&0xFF); // 声質 2桁目
data[10]=(byte) 0; // エンコード(0: UTF-8)
data[11]=(byte) ((length>>>0)&0xFF); // 長さ 1桁目
data[12]=(byte) ((length>>>8)&0xFF); // 長さ 2桁目
data[13]=(byte) ((length>>>16)&0xFF); // 長さ 3桁目
data[14]=(byte) ((length>>>24)&0xFF); // 長さ 4桁目
System.arraycopy(messageData,0,data,15,length);
send(host,data);
}
}
| 31.188095 | 128 | 0.636232 |
0a3980ccf5387368824f7aca87552bb6139df390 | 49,700 | /*
* Copyright (c) 2011 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.truth;
import static com.google.common.truth.TestCorrespondences.STRING_PARSES_TO_INTEGER_CORRESPONDENCE;
import static com.google.common.truth.TestCorrespondences.WITHIN_10_OF;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.fail;
import com.google.common.collect.ForwardingMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for {@link Map} subjects.
*
* @author Christian Gruber
* @author Kurt Alfred Kluever
*/
@RunWith(JUnit4.class)
public class MapSubjectTest extends BaseSubjectTestCase {
@Test
public void containsExactlyWithNullKey() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, "value");
assertThat(actual).containsExactly(null, "value");
assertThat(actual).containsExactly(null, "value").inOrder();
assertThat(actual).containsExactlyEntriesIn(actual);
assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
}
@Test
public void containsExactlyWithNullValue() {
Map<String, String> actual = Maps.newHashMap();
actual.put("key", null);
assertThat(actual).containsExactly("key", null);
assertThat(actual).containsExactly("key", null).inOrder();
assertThat(actual).containsExactlyEntriesIn(actual);
assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
}
@Test
public void containsExactlyEmpty() {
ImmutableMap<String, Integer> actual = ImmutableMap.of();
assertThat(actual).containsExactly();
assertThat(actual).containsExactly().inOrder();
assertThat(actual).containsExactlyEntriesIn(actual);
assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
}
@Test
public void containsExactlyEmpty_fails() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1);
expectFailureWhenTestingThat(actual).containsExactly();
assertFailureKeys("expected to be empty", "but was");
}
@Test
public void containsExactlyEntriesInEmpty_fails() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1);
expectFailureWhenTestingThat(actual).containsExactlyEntriesIn(ImmutableMap.of());
assertFailureKeys("expected to be empty", "but was");
}
@Test
public void containsExactlyOneEntry() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1);
assertThat(actual).containsExactly("jan", 1);
assertThat(actual).containsExactly("jan", 1).inOrder();
assertThat(actual).containsExactlyEntriesIn(actual);
assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
}
@Test
public void containsExactlyMultipleEntries() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
assertThat(actual).containsExactly("march", 3, "jan", 1, "feb", 2);
assertThat(actual).containsExactly("jan", 1, "feb", 2, "march", 3).inOrder();
assertThat(actual).containsExactlyEntriesIn(actual);
assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
}
@Test
public void containsExactlyDuplicateKeys() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
try {
assertThat(actual).containsExactly("jan", 1, "jan", 2, "jan", 3);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.isEqualTo("Duplicate keys ([jan x 3]) cannot be passed to containsExactly().");
}
}
@Test
public void containsExactlyMultipleDuplicateKeys() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
try {
assertThat(actual).containsExactly("jan", 1, "jan", 1, "feb", 2, "feb", 2);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.isEqualTo("Duplicate keys ([jan x 2, feb x 2]) cannot be passed to containsExactly().");
}
}
@Test
public void containsExactlyExtraKey() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).containsExactly("feb", 2, "jan", 1);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> contains exactly <{feb=2, jan=1}>. "
+ "It has the following entries with unexpected keys: {march=3}");
}
@Test
public void containsExactlyExtraKeyInOrder() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).containsExactly("feb", 2, "jan", 1).inOrder();
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> contains exactly <{feb=2, jan=1}>. "
+ "It has the following entries with unexpected keys: {march=3}");
}
@Test
public void namedMapContainsExactlyExtraKey() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).named("foo").containsExactly("feb", 2, "jan", 1);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that foo (<{jan=1, feb=2, march=3}>) contains exactly <{feb=2, jan=1}>. "
+ "It has the following entries with unexpected keys: {march=3}");
}
@Test
public void containsExactlyMissingKey() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2);
expectFailureWhenTestingThat(actual).containsExactly("jan", 1, "march", 3, "feb", 2);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2}> contains exactly <{jan=1, march=3, feb=2}>. "
+ "It is missing keys for the following entries: {march=3}");
}
@Test
public void containsExactlyWrongValue() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).containsExactly("jan", 1, "march", 33, "feb", 2);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> contains exactly <{jan=1, march=33, feb=2}>. "
+ "It has the following entries with matching keys but different values: "
+ "{march=(expected 33 but got 3)}");
}
@Test
public void containsExactlyExtraKeyAndMissingKey() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "march", 3);
expectFailureWhenTestingThat(actual).containsExactly("jan", 1, "feb", 2);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, march=3}> contains exactly <{jan=1, feb=2}>. "
+ "It is missing keys for the following entries: {feb=2} "
+ "and has the following entries with unexpected keys: {march=3}");
}
@Test
public void containsExactlyExtraKeyAndWrongValue() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).containsExactly("jan", 1, "march", 33);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> contains exactly <{jan=1, march=33}>. "
+ "It has the following entries with unexpected keys: {feb=2} "
+ "and has the following entries with matching keys but different values: "
+ "{march=(expected 33 but got 3)}");
}
@Test
public void containsExactlyMissingKeyAndWrongValue() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "march", 3);
expectFailureWhenTestingThat(actual).containsExactly("jan", 1, "march", 33, "feb", 2);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, march=3}> contains exactly <{jan=1, march=33, feb=2}>. "
+ "It is missing keys for the following entries: {feb=2} "
+ "and has the following entries with matching keys but different values: "
+ "{march=(expected 33 but got 3)}");
}
@Test
public void containsExactlyExtraKeyAndMissingKeyAndWrongValue() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "march", 3);
expectFailureWhenTestingThat(actual).containsExactly("march", 33, "feb", 2);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, march=3}> contains exactly <{march=33, feb=2}>. "
+ "It is missing keys for the following entries: {feb=2} "
+ "and has the following entries with unexpected keys: {jan=1} "
+ "and has the following entries with matching keys but different values: "
+ "{march=(expected 33 but got 3)}");
}
@Test
public void containsExactlyNotInOrder() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
assertThat(actual).containsExactlyEntriesIn(actual);
assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
assertThat(actual).containsExactly("jan", 1, "march", 3, "feb", 2);
expectFailureWhenTestingThat(actual).containsExactly("jan", 1, "march", 3, "feb", 2).inOrder();
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> contains exactly these entries in order "
+ "<{jan=1, march=3, feb=2}>");
}
@Test
@SuppressWarnings("ShouldHaveEvenArgs")
public void containsExactlyBadNumberOfArgs() {
ImmutableMap<String, Integer> actual =
ImmutableMap.of("jan", 1, "feb", 2, "march", 3, "april", 4, "may", 5);
assertThat(actual).containsExactlyEntriesIn(actual);
assertThat(actual).containsExactlyEntriesIn(actual).inOrder();
try {
assertThat(actual)
.containsExactly("jan", 1, "feb", 2, "march", 3, "april", 4, "may", 5, "june", 6, "july");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertThat(expected)
.hasMessageThat()
.isEqualTo(
"There must be an equal number of key/value pairs "
+ "(i.e., the number of key/value parameters (13) must be even).");
}
}
@Test
public void containsExactlyWrongValue_sameToStringForValues() {
expectFailureWhenTestingThat(ImmutableMap.of("jan", 1L, "feb", 2L))
.containsExactly("jan", 1, "feb", 2);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2}> contains exactly <{jan=1, feb=2}>. "
+ "It has the following entries with matching keys but different values: "
+ "{jan=(expected 1 (java.lang.Integer) but got 1 (java.lang.Long)), "
+ "feb=(expected 2 (java.lang.Integer) but got 2 (java.lang.Long))}");
}
@Test
public void containsExactlyWrongValue_sameToStringForKeys() {
expectFailureWhenTestingThat(ImmutableMap.of(1L, "jan", 1, "feb"))
.containsExactly(1, "jan", 1L, "feb");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{1=jan, 1=feb}> contains exactly <{1=jan, 1=feb}>. "
+ "It has the following entries with matching keys but different values: "
+ "{1 (java.lang.Integer)=(expected jan but got feb), "
+ "1 (java.lang.Long)=(expected feb but got jan)}");
}
@Test
public void containsExactlyExtraKeyAndMissingKey_failsWithSameToStringForKeys() {
expectFailureWhenTestingThat(ImmutableMap.of(1L, "jan", 2, "feb"))
.containsExactly(1, "jan", 2, "feb");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{1=jan, 2=feb}> contains exactly <{1=jan, 2=feb}>. "
+ "It is missing keys for the following entries: {1 (java.lang.Integer)=jan} "
+ "and has the following entries with unexpected keys: {1 (java.lang.Long)=jan}");
}
@Test
public void isEqualToPass() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
assertThat(actual).isEqualTo(expectedMap);
}
@Test
public void isEqualToFailureExtraMissingAndDiffering() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "april", 4, "march", 5);
expectFailureWhenTestingThat(actual).isEqualTo(expectedMap);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, april=4, march=5}>. "
+ "It is missing keys for the following entries: {april=4} and "
+ "has the following entries with unexpected keys: {feb=2} and "
+ "has the following entries with matching keys but different values: "
+ "{march=(expected 5 but got 3)}");
}
@Test
public void isEqualToFailureDiffering() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 4);
expectFailureWhenTestingThat(actual).isEqualTo(expectedMap);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, feb=2, march=4}>. "
+ "It has the following entries with matching keys but different values: "
+ "{march=(expected 4 but got 3)}");
}
@Test
public void namedMapIsEqualToFailureDiffering() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 4);
expectFailureWhenTestingThat(actual).named("foo").isEqualTo(expectedMap);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that foo (<{jan=1, feb=2, march=3}>) is equal to <{jan=1, feb=2, march=4}>."
+ " It has the following entries with matching keys but different values: "
+ "{march=(expected 4 but got 3)}");
}
@Test
public void isEqualToFailureExtra() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2);
expectFailureWhenTestingThat(actual).isEqualTo(expectedMap);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, feb=2}>. "
+ "It has the following entries with unexpected keys: {march=3}");
}
@Test
public void isEqualToFailureMissing() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).isEqualTo(expectedMap);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2}> is equal to <{jan=1, feb=2, march=3}>. "
+ "It is missing keys for the following entries: {march=3}");
}
@Test
public void isEqualToFailureExtraAndMissing() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "mar", 3);
expectFailureWhenTestingThat(actual).isEqualTo(expectedMap);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, feb=2, mar=3}>. "
+ "It is missing keys for the following entries: {mar=3} "
+ "and has the following entries with unexpected keys: {march=3}");
}
@Test
public void isEqualToFailureDiffering_sameToString() {
ImmutableMap<String, Number> actual =
ImmutableMap.<String, Number>of("jan", 1, "feb", 2, "march", 3L);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).isEqualTo(expectedMap);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1, feb=2, march=3}> is equal to <{jan=1, feb=2, march=3}>. "
+ "It has the following entries with matching keys but different values: "
+ "{march=(expected 3 (java.lang.Integer) but got 3 (java.lang.Long))}");
}
@Test
public void isEqualToNonMap() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).isEqualTo("something else");
assertFailureKeys("expected", "but was");
}
/**
* A broken implementation of {@link Map} whose {@link #equals} method does not implement the
* contract. Users sometimes write tests using broken implementations, and we should test that
* {@code isEqualTo} is consistent with their implementation.
*/
private static class BrokenMap<K, V> extends ForwardingMap<K, V> {
static <K, V> Map<K, V> wrapWithAlwaysTrueEquals(Map<K, V> delegate) {
return new BrokenMap<>(delegate, true);
}
static <K, V> Map<K, V> wrapWithAlwaysFalseEquals(Map<K, V> delegate) {
return new BrokenMap<>(delegate, false);
}
private final Map<K, V> delegate;
private final boolean equalsStub;
private BrokenMap(Map<K, V> delegate, boolean equalsStub) {
this.delegate = delegate;
this.equalsStub = equalsStub;
}
@Override
public Map<K, V> delegate() {
return delegate;
}
@Override
public boolean equals(Object other) {
return equalsStub;
}
}
@Test
public void isEqualTo_brokenMapEqualsImplementation_trueWhenItShouldBeFalse() {
// These maps are not equal according to the contract of Map.equals, but have a broken equals()
// implementation that always returns true. So the isEqualTo assertion should pass.
Map<String, Integer> map1 = BrokenMap.wrapWithAlwaysTrueEquals(ImmutableMap.of("jan", 1));
Map<String, Integer> map2 = BrokenMap.wrapWithAlwaysTrueEquals(ImmutableMap.of("feb", 2));
assertThat(map1).isEqualTo(map2);
}
@Test
public void isEqualTo_brokenMapEqualsImplementation_falseWhenItShouldBeTrue() {
// These maps are equal according to the contract of Map.equals, but have a broken equals()
// implementation that always returns false. So the isEqualTo assertion should fail.
Map<String, Integer> map1 = BrokenMap.wrapWithAlwaysFalseEquals(ImmutableMap.of("jan", 1));
Map<String, Integer> map1clone = BrokenMap.wrapWithAlwaysFalseEquals(ImmutableMap.of("jan", 1));
expectFailureWhenTestingThat(map1).isEqualTo(map1clone);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{jan=1}> is equal to <{jan=1}>. It is equal according to the contract "
+ "of Map.equals(Object), but this implementation returned false");
}
@Test
public void isNotEqualTo() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
ImmutableMap<String, Integer> unexpected = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).isNotEqualTo(unexpected);
}
@Test
public void isEmpty() {
ImmutableMap<String, String> actual = ImmutableMap.of();
assertThat(actual).isEmpty();
}
@Test
public void isEmptyWithFailure() {
ImmutableMap<Integer, Integer> actual = ImmutableMap.of(1, 5);
expectFailureWhenTestingThat(actual).isEmpty();
assertFailureKeys("expected to be empty", "but was");
}
@Test
public void isNotEmpty() {
ImmutableMap<Integer, Integer> actual = ImmutableMap.of(1, 5);
assertThat(actual).isNotEmpty();
}
@Test
public void isNotEmptyWithFailure() {
ImmutableMap<Integer, Integer> actual = ImmutableMap.of();
expectFailureWhenTestingThat(actual).isNotEmpty();
assertFailureKeys("expected not to be empty");
}
@Test
public void hasSize() {
assertThat(ImmutableMap.of(1, 2, 3, 4)).hasSize(2);
}
@Test
public void hasSizeZero() {
assertThat(ImmutableMap.of()).hasSize(0);
}
@Test
public void hasSizeNegative() {
try {
assertThat(ImmutableMap.of(1, 2)).hasSize(-1);
fail();
} catch (IllegalArgumentException expected) {
}
}
@Test
public void containsKey() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
assertThat(actual).containsKey("kurt");
}
@Test
public void containsKeyFailure() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
expectFailureWhenTestingThat(actual).containsKey("greg");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{kurt=kluever}> contains key <greg>");
}
@Test
public void containsKeyNullFailure() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
expectFailureWhenTestingThat(actual).containsKey(null);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{kurt=kluever}> contains key <null>");
}
@Test
public void containsKey_failsWithSameToString() {
expectFailureWhenTestingThat(ImmutableMap.of(1L, "value1", 2L, "value2", "1", "value3"))
.containsKey(1);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{1=value1, 2=value2, 1=value3}> contains key <1 (java.lang.Integer)>. "
+ "However, it does contain keys <[1 (java.lang.Long), 1 (java.lang.String)]>.");
}
@Test
public void containsKey_failsWithNullStringAndNull() {
Map<String, String> actual = Maps.newHashMap();
actual.put("null", "value1");
expectFailureWhenTestingThat(actual).containsKey(null);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{null=value1}> contains key <null (null type)>. However, "
+ "it does contain keys <[null] (java.lang.String)>.");
}
@Test
public void containsNullKey() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, "null");
assertThat(actual).containsKey(null);
}
@Test
public void doesNotContainKey() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
assertThat(actual).doesNotContainKey("greg");
assertThat(actual).doesNotContainKey(null);
}
@Test
public void doesNotContainKeyFailure() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
expectFailureWhenTestingThat(actual).doesNotContainKey("kurt");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{kurt=kluever}> does not contain key <kurt>");
}
@Test
public void doesNotContainNullKey() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, "null");
expectFailureWhenTestingThat(actual).doesNotContainKey(null);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{null=null}> does not contain key <null>");
}
@Test
public void containsEntry() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
assertThat(actual).containsEntry("kurt", "kluever");
}
@Test
public void containsEntryFailure() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
expectFailureWhenTestingThat(actual).containsEntry("greg", "kick");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{kurt=kluever}> contains entry <greg=kick>");
}
@Test
public void containsEntry_failsWithSameToStringOfKey() {
expectFailureWhenTestingThat(ImmutableMap.of(1L, "value1", 2L, "value2"))
.containsEntry(1, "value1");
assertWithMessage("Full message: %s", expectFailure.getFailure().getMessage())
.that(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{1=value1, 2=value2}> contains entry "
+ "<1=value1 (Map.Entry<java.lang.Integer, java.lang.String>)>. "
+ "However, it does contain keys <[1] (java.lang.Long)>.");
}
@Test
public void containsEntry_failsWithSameToStringOfValue() {
expectFailureWhenTestingThat(ImmutableMap.of(1, "null")).containsEntry(1, null);
assertWithMessage("Full message: %s", expectFailure.getFailure().getMessage())
.that(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{1=null}> contains entry <1=null "
+ "(Map.Entry<java.lang.Integer, null type>)>. However, it does contain values "
+ "<[null] (java.lang.String)>.");
}
@Test
public void containsNullKeyAndValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
expectFailureWhenTestingThat(actual).containsEntry(null, null);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{kurt=kluever}> contains entry <null=null>");
}
@Test
public void containsNullEntry() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, null);
assertThat(actual).containsEntry(null, null);
}
@Test
public void containsNullEntryValue() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, null);
expectFailureWhenTestingThat(actual).containsEntry("kurt", null);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{null=null}> contains entry <kurt=null>. "
+ "However, the following keys are mapped to <null>: [null]");
}
private static final String KEY_IS_PRESENT_WITH_DIFFERENT_VALUE =
"key is present but with a different value";
@Test
public void containsNullEntryKey() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, null);
expectFailureWhenTestingThat(actual).containsEntry(null, "kluever");
assertFailureValue("value of", "map.get(null)");
assertFailureValue("expected", "kluever");
assertFailureValue("but was", "null");
assertFailureValue("map was", "{null=null}");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.contains(KEY_IS_PRESENT_WITH_DIFFERENT_VALUE);
}
@Test
public void doesNotContainEntry() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
assertThat(actual).doesNotContainEntry("greg", "kick");
assertThat(actual).doesNotContainEntry(null, null);
assertThat(actual).doesNotContainEntry("kurt", null);
assertThat(actual).doesNotContainEntry(null, "kluever");
}
@Test
public void doesNotContainEntryFailure() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
expectFailureWhenTestingThat(actual).doesNotContainEntry("kurt", "kluever");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{kurt=kluever}> does not contain entry <kurt=kluever>");
}
@Test
public void doesNotContainNullEntry() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, null);
assertThat(actual).doesNotContainEntry("kurt", null);
assertThat(actual).doesNotContainEntry(null, "kluever");
}
@Test
public void doesNotContainNullEntryFailure() {
Map<String, String> actual = Maps.newHashMap();
actual.put(null, null);
expectFailureWhenTestingThat(actual).doesNotContainEntry(null, null);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{null=null}> does not contain entry <null=null>");
}
@Test
public void failMapContainsKey() {
ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
expectFailureWhenTestingThat(actual).containsKey("b");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{a=A}> contains key <b>");
}
@Test
public void failMapContainsKeyWithNull() {
ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
expectFailureWhenTestingThat(actual).containsKey(null);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{a=A}> contains key <null>");
}
@Test
public void failMapLacksKey() {
ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
expectFailureWhenTestingThat(actual).doesNotContainKey("a");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo("Not true that <{a=A}> does not contain key <a>");
}
@Test
public void containsKeyWithValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
assertThat(actual).containsEntry("a", "A");
}
@Test
public void containsKeyWithNullValueNullExpected() {
Map<String, String> actual = Maps.newHashMap();
actual.put("a", null);
assertThat(actual).containsEntry("a", null);
}
@Test
public void failMapContainsKeyWithValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
expectFailureWhenTestingThat(actual).containsEntry("a", "a");
assertFailureValue("value of", "map.get(a)");
assertFailureValue("expected", "a");
assertFailureValue("but was", "A");
assertFailureValue("map was", "{a=A}");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.doesNotContain(KEY_IS_PRESENT_WITH_DIFFERENT_VALUE);
}
@Test
public void failMapContainsKeyWithNullValuePresentExpected() {
Map<String, String> actual = Maps.newHashMap();
actual.put("a", null);
expectFailureWhenTestingThat(actual).containsEntry("a", "A");
assertFailureValue("value of", "map.get(a)");
assertFailureValue("expected", "A");
assertFailureValue("but was", "null");
assertFailureValue("map was", "{a=null}");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.contains(KEY_IS_PRESENT_WITH_DIFFERENT_VALUE);
}
@Test
public void failMapContainsKeyWithPresentValueNullExpected() {
ImmutableMap<String, String> actual = ImmutableMap.of("a", "A");
expectFailureWhenTestingThat(actual).containsEntry("a", null);
assertFailureValue("value of", "map.get(a)");
assertFailureValue("expected", "null");
assertFailureValue("but was", "A");
assertFailureValue("map was", "{a=A}");
assertThat(expectFailure.getFailure())
.hasMessageThat()
.contains(KEY_IS_PRESENT_WITH_DIFFERENT_VALUE);
}
@Test
public void comparingValuesUsing_containsEntry_success() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsEntry("def", 456);
}
@Test
public void comparingValuesUsing_containsEntry_failsExpectedKeyHasWrongValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "+123", "def", "+456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsEntry("def", 123);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=+123, def=+456}> contains an entry with "
+ "key <def> and a value that parses to <123>. "
+ "However, it has a mapping from that key to <+456>");
}
@Test
public void comparingValuesUsing_containsEntry_failsWrongKeyHasExpectedValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "+123", "def", "+456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsEntry("xyz", 456);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=+123, def=+456}> contains an entry with "
+ "key <xyz> and a value that parses to <456>. "
+ "However, the following keys are mapped to such values: <[def]>");
}
@Test
public void comparingValuesUsing_containsEntry_failsMissingExpectedKeyAndValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "+123", "def", "+456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsEntry("xyz", 321);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=+123, def=+456}> contains an entry with "
+ "key <xyz> and a value that parses to <321>");
}
@Test
public void comparingValuesUsing_containsEntry_diffExpectedKeyHasWrongValue() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("abc", 35, "def", 71);
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(WITHIN_10_OF)
.containsEntry("def", 60);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=35, def=71}> contains an entry with key <def> and a value that is "
+ "within 10 of <60>. However, it has a mapping from that key to <71> (diff: 11)");
}
@Test
public void comparingValuesUsing_doesNotContainEntry_successExcludedKeyHasWrongValues() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "+123", "def", "+456");
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.doesNotContainEntry("def", 123);
}
@Test
public void comparingValuesUsing_doesNotContainEntry_successWrongKeyHasExcludedValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "+123", "def", "+456");
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.doesNotContainEntry("xyz", 456);
}
@Test
public void comparingValuesUsing_doesNotContainEntry_failsMissingExcludedKeyAndValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.doesNotContainEntry("xyz", 321);
}
@Test
public void comparingValuesUsing_doesNotContainEntry_failure() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "+123", "def", "+456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.doesNotContainEntry("def", 456);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=+123, def=+456}> does not contain an entry with "
+ "key <def> and a value that parses to <456>. It maps that key to <+456>");
}
@Test
public void comparingValuesUsing_containsExactly_success() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactly("def", 456, "abc", 123);
}
@Test
public void comparingValuesUsing_containsExactly_inOrder_success() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactly("abc", 123, "def", 456)
.inOrder();
}
@Test
public void comparingValuesUsing_containsExactly_failsExtraEntry() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactly("def", 456);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains exactly one entry that has a key that is "
+ "equal to and a value that parses to the key and value of each entry of "
+ "<{def=456}>. It has the following entries with unexpected keys: {abc=123}");
}
@Test
public void comparingValuesUsing_containsExactly_failsMissingEntry() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactly("def", 456, "xyz", 999, "abc", 123);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains exactly one entry that has a key that is "
+ "equal to and a value that parses to the key and value of each entry of "
+ "<{def=456, xyz=999, abc=123}>. It is missing keys for the following entries: "
+ "{xyz=999}");
}
@Test
public void comparingValuesUsing_containsExactly_failsWrongKey() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactly("def", 456, "cab", 123);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains exactly one entry that has a key that is "
+ "equal to and a value that parses to the key and value of each entry of "
+ "<{def=456, cab=123}>. It is missing keys for the following entries: {cab=123} "
+ "and has the following entries with unexpected keys: {abc=123}");
}
@Test
public void comparingValuesUsing_containsExactly_failsWrongValue() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactly("def", 456, "abc", 321);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains exactly one entry that has a key that is "
+ "equal to and a value that parses to the key and value of each entry of "
+ "<{def=456, abc=321}>. It has the following entries with matching keys but "
+ "different values: {abc=(expected 321 but got 123)}");
}
@Test
public void comparingValuesUsing_containsExactly_inOrder_failsOutOfOrder() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactly("def", 456, "abc", 123)
.inOrder();
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains, in order, exactly one entry that has"
+ " a key that is equal to and a value that parses to the key and value of each"
+ " entry of <{def=456, abc=123}>");
}
@Test
public void comparingValuesUsing_containsExactly_wrongValueTypeInActual() {
ImmutableMap<String, Object> actual = ImmutableMap.<String, Object>of("abc", "123", "def", 456);
MapSubject.UsingCorrespondence<String, Integer> intermediate =
assertThat(actual).comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE);
try {
intermediate.containsExactly("def", 456, "abc", 123);
fail("Should have thrown.");
} catch (ClassCastException expected) {
}
}
@Test
public void comparingValuesUsing_containsExactly_wrongValueTypeInExpected() {
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
MapSubject.UsingCorrespondence<String, Integer> intermediate =
assertThat(actual).comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE);
try {
intermediate.containsExactly("def", 456, "abc", 123L);
fail("Should have thrown.");
} catch (ClassCastException expected) {
}
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_success() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("def", 456, "abc", 123);
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected);
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_inOrder_success() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("abc", 123, "def", 456);
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected)
.inOrder();
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_failsExtraEntry() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("def", 456);
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains exactly one entry that has a key that is "
+ "equal to and a value that parses to the key and value of each entry of "
+ "<{def=456}>. It has the following entries with unexpected keys: {abc=123}");
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_failsMissingEntry() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("def", 456, "xyz", 999, "abc", 123);
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains exactly one entry that has a key that is "
+ "equal to and a value that parses to the key and value of each entry of "
+ "<{def=456, xyz=999, abc=123}>. It is missing keys for the following entries: "
+ "{xyz=999}");
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_failsWrongKey() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("def", 456, "cab", 123);
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains exactly one entry that has a key that is "
+ "equal to and a value that parses to the key and value of each entry of "
+ "<{def=456, cab=123}>. It is missing keys for the following entries: {cab=123} "
+ "and has the following entries with unexpected keys: {abc=123}");
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_failsWrongValue() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("def", 456, "abc", 321);
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains exactly one entry that has a key that is "
+ "equal to and a value that parses to the key and value of each entry of "
+ "<{def=456, abc=321}>. It has the following entries with matching keys but "
+ "different values: {abc=(expected 321 but got 123)}");
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_diffMissingAndExtraAndWrongValue() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("abc", 30, "def", 60, "ghi", 90);
ImmutableMap<String, Integer> actual = ImmutableMap.of("abc", 35, "fed", 60, "ghi", 101);
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(WITHIN_10_OF)
.containsExactlyEntriesIn(expected);
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=35, fed=60, ghi=101}> contains exactly one entry that has a key "
+ "that is equal to and a value that is within 10 of the key and value of each "
+ "entry of <{abc=30, def=60, ghi=90}>. It is missing keys for the following "
+ "entries: {def=60} and has the following entries with unexpected keys: {fed=60} "
+ "and has the following entries with matching keys but different values: "
+ "{ghi=(expected 90 but got 101, diff: 11)}");
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_inOrder_failsOutOfOrder() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("def", 456, "abc", 123);
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123", "def", "456");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected)
.inOrder();
assertThat(expectFailure.getFailure())
.hasMessageThat()
.isEqualTo(
"Not true that <{abc=123, def=456}> contains, in order, exactly one entry that has"
+ " a key that is equal to and a value that parses to the key and value of each"
+ " entry of <{def=456, abc=123}>");
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_empty() {
ImmutableMap<String, Integer> expected = ImmutableMap.of();
ImmutableMap<String, String> actual = ImmutableMap.of();
assertThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected);
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_failsEmpty() {
ImmutableMap<String, Integer> expected = ImmutableMap.of();
ImmutableMap<String, String> actual = ImmutableMap.of("abc", "123");
expectFailureWhenTestingThat(actual)
.comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE)
.containsExactlyEntriesIn(expected);
assertFailureKeys("expected to be empty", "but was");
}
@Test
public void comparingValuesUsing_containsExactlyEntriesIn_wrongValueTypeInActual() {
ImmutableMap<String, Integer> expected = ImmutableMap.of("def", 456, "abc", 123);
ImmutableMap<String, Object> actual = ImmutableMap.<String, Object>of("abc", "123", "def", 456);
MapSubject.UsingCorrespondence<String, Integer> intermediate =
assertThat(actual).comparingValuesUsing(STRING_PARSES_TO_INTEGER_CORRESPONDENCE);
try {
intermediate.containsExactlyEntriesIn(expected);
fail("Should have thrown.");
} catch (ClassCastException e) {
// expected
}
}
private MapSubject expectFailureWhenTestingThat(Map<?, ?> actual) {
return expectFailure.whenTesting().that(actual);
}
}
| 41.694631 | 100 | 0.668994 |
53043f625fbb7fa7d63c611665ae2508bac74d68 | 1,314 | package net.folivo.springframework.security.abac.config;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import net.folivo.springframework.security.abac.method.aopalliance.AbacMethodSecurityPointcut;
import net.folivo.springframework.security.abac.method.aopalliance.AbacMethodSecurityPointcutAdvisor;
@Configuration
public class AbacAopAdvisorConfiguration {
// TODO catch?
// TODO interface as return type?
// TODO how to ensure, that this is right inteceptor?
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
protected AbstractPointcutAdvisor abacMethodSecurityPointcutAdvisor() throws Exception {
// TODO is order of this(config) relevant? originally it is added
return new AbacMethodSecurityPointcutAdvisor(abacMethodSecurityPointcut(), "abacMethodSecurityInterceptor");
}
// TODO interface as return type?
// @Bean
// @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
protected StaticMethodMatcherPointcut abacMethodSecurityPointcut() {
return new AbacMethodSecurityPointcut();
}
}
| 41.0625 | 110 | 0.837139 |
6e7704a24466e378fe6935ad8b67e1815efdfef7 | 1,027 | package fileio.writer;
import exception.FileWriteException;
import model.Wallet;
import storage.IContainer;
public class BankWalletWriter {
protected BankWalletWriter() {
}
/**
* The function returns the file content of bank wallet container
*
* @param bankWallets = bank wallet container
* @return String of content
* @throws FileWriteException
*/
protected String writeBankWalletsJson(IContainer<Wallet> bankWallets) throws FileWriteException {
String result = "{";
for (Wallet bankWallet : bankWallets) {
result += convertBankWalletToJsonString(bankWallet);
}
if (result.endsWith(",")) { // if ends with , ignore it
result = result.substring(0, result.length() - 1);
}
result += "}";
result = JsonWriteHelper.validateJsonObject(result);
return result;
}
private String convertBankWalletToJsonString(Wallet cryptoWallet) {
return "\"" + cryptoWallet.getId() + "\":"
+ WalletEntityWriter.writeWalletEntitiesToJsonArray("banknotes", cryptoWallet.getEntities()) + ",";
}
}
| 27.026316 | 103 | 0.725414 |
c5427accfa9997dd0cae88b8a795a9907881e95e | 389 | package com.kiparo.injection;
import com.kiparo.presentation.screeens.home.HomeActivity;
import com.kiparo.presentation.screeens.home.HomeModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
@Module
public abstract class ActivitiesModule {
@ContributesAndroidInjector(modules = { HomeModule.class })
abstract HomeActivity contributeHomeActivity();
}
| 25.933333 | 63 | 0.820051 |
c45b04d4c579a4995158cbbc7aa6d0d90800f02b | 229 | package gameLogic.Items;
import gameLogic.Tiles.Tile2D;
/**
*
* @author griffiryan
*
* GreenKey is a specialization of the Key class.
*/
public class GreenKey extends Key {
public GreenKey(Tile2D tile) {
super(tile);
}
}
| 12.722222 | 48 | 0.71179 |
ebd8328f7196b1afa04bdd34bc697bd5e9f270f7 | 2,792 | package cn.wizzer.app.msg.modules.models;
import cn.wizzer.app.sys.modules.models.Sys_user;
import cn.wizzer.framework.base.dao.entity.annotation.Ref;
import cn.wizzer.framework.base.model.BaseModel;
import org.nutz.dao.entity.annotation.*;
import java.io.Serializable;
@Comment("任务处理意见表")
@Table("msg_option")
public class Msg_option extends BaseModel implements Serializable {
@Column
@Name
@Comment("ID")
@ColDefine(type = ColType.VARCHAR, width = 32)
@Prev(els = {@EL("uuid()")})
private String id;
@Column
@Comment("单据id")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String billid;
@Column
@Comment("任务id")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String assignid;
@Column
@Comment("操作类型") //0 同意(然后结束流程);1 不同意(打回或者终止由业务auditHandler方法决定); 2 转交(其他人处理); 3 跳转下一步人(同意,并且指定了下一步处理人)
@ColDefine(type = ColType.INT)
private String type;
@Column
@Comment("处理意见")
@ColDefine(type = ColType.VARCHAR, width = 255)
private String content;
@Column
@Comment("操作时间")
@ColDefine(type = ColType.VARCHAR, width = 32)
private String optime;
@Column
@Comment("下一个处理人id")
@ColDefine(type = ColType.VARCHAR, width = 32)
@Ref(Sys_user.class)
private String nextHandlerId;
@One(field = "nextHandlerId")
private Sys_user nextHandler;
@One(field = "opBy")
private Sys_user opByUser;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBillid() {
return billid;
}
public void setBillid(String billid) {
this.billid = billid;
}
public String getAssignid() {
return assignid;
}
public void setAssignid(String assignid) {
this.assignid = assignid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getOptime() {
return optime;
}
public void setOptime(String optime) {
this.optime = optime;
}
public String getNextHandlerId() {
return nextHandlerId;
}
public void setNextHandlerId(String nextHandlerId) {
this.nextHandlerId = nextHandlerId;
}
public Sys_user getNextHandler() {
return nextHandler;
}
public void setNextHandler(Sys_user nextHandler) {
this.nextHandler = nextHandler;
}
public Sys_user getOpByUser() {
return opByUser;
}
public void setOpByUser(Sys_user opByUser) {
this.opByUser = opByUser;
}
}
| 21.643411 | 108 | 0.633954 |
55a127f93ffd8215cb1100bfb0272698923b4638 | 1,966 | package hongwei.leetcode.playground.other.baidu1;
public class BigNumber {
public Node initListA() {
Node node = new Node(1);
node.next = new Node(3);
node.next.next = new Node(6);
node.next.next.next = new Node(6);
return node;
}
public Node initListB() {
Node node = new Node(4);
node.next = new Node(7);
return node;
}
public Node addBigNumber(Node lista, Node listb) {
Node rla = reverse(lista);
Node rlb = reverse(listb);
int advanced = 0;
Node rlc = null, cc = null;
while (rla != null || rlb != null) {
int na = rla != null ? rla.data : 0;
int nb = rlb != null ? rlb.data : 0;
int n = na + nb + advanced;
int left = n % 10;
advanced = n / 10;
if (cc == null) {
cc = new Node(left);
rlc = cc;
} else {
cc.next = new Node(left);
cc = cc.next;
}
rla = rla != null ? rla.next : null;
rlb = rlb != null ? rlb.next : null;
}
return reverse(rlc);
}
public Node reverse(Node head) {
Node prev = null;
Node cur = head;
while (cur != null) {
Node t = cur.next;
cur.next = prev;
prev = cur;
cur = t;
}
return prev;
}
private class Node {
public int data;
public Node next;
public Node(int d) {
data = d;
}
}
public static void main(String[] args) {
BigNumber bigNumber = new BigNumber();
Node a = bigNumber.initListA();
Node b = bigNumber.initListB();
Node c = bigNumber.addBigNumber(a, b);
// Node c = bigNumber.reverse(b);
while (c != null) {
System.out.println(c.data + "->");
c = c.next;
}
}
}
| 25.868421 | 54 | 0.459817 |
39da89e15a8df5caab01ae7b882733173e05d0da | 356 | package com.jsh.erp.service.materialCategory;
import com.jsh.erp.service.ResourceInfo;
import java.lang.annotation.*;
/**
* @author jishenghua qq752718920 2018-10-7 15:26:27
*/
@ResourceInfo(value = "materialCategory", type = 75)
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MaterialCategoryResource {
}
| 22.25 | 53 | 0.775281 |
e2b583febbedb404485b2b613bcbdda775a9f443 | 2,599 | package com.ssagroup.ebi_app.services;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by User on 8/9/16.
*/
public class DownloadImageService extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
Bitmap bitmap;
Activity activity;
public DownloadImageService() {
}
public DownloadImageService(Activity activity) {
this.activity = activity;
}
public DownloadImageService(Bitmap bitmap) {
this.bitmap = bitmap;
}
public DownloadImageService(Bitmap bitmap, ImageView bmImage) {
this.bitmap = bitmap;
this.bmImage = bmImage;
}
@Override
protected Bitmap doInBackground(String... urls) {
String urlDisplay = urls[0];
Bitmap b = null;
try {
URL url = new URL(urlDisplay);
URLConnection conn = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
httpURLConnection.setAllowUserInteraction(true);
httpURLConnection.setInstanceFollowRedirects(true);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
InputStream in = null;
int response = httpURLConnection.getResponseCode();
in = httpURLConnection.getInputStream();
switch (response) {
case HttpURLConnection.HTTP_OK: // 200
in = httpURLConnection.getInputStream();
break;
case HttpURLConnection.HTTP_MOVED_PERM: // 301
String location = httpURLConnection.getHeaderField("Location");
URL urlNew = new URL(location);
URLConnection connNew = urlNew.openConnection();
HttpURLConnection httpURLConnectionNew = (HttpURLConnection) connNew;
in = httpURLConnectionNew.getInputStream();
break;
default:
break;
}
b = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return b;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
bitmap = result;
}
}
| 28.877778 | 89 | 0.614852 |
1e43cf7e4990b6c25e79ef1a77f2face72a4ba57 | 8,009 | package io.smallrye.reactive.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.awaitility.Awaitility.await;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.spi.DeploymentException;
import org.eclipse.microprofile.reactive.messaging.Message;
import org.eclipse.microprofile.reactive.streams.operators.SubscriberBuilder;
import org.junit.Test;
import io.reactivex.Flowable;
import io.smallrye.reactive.messaging.beans.BeanConsumingMessagesAndReturningACompletionStageOfSomething;
import io.smallrye.reactive.messaging.beans.BeanConsumingMessagesAndReturningACompletionStageOfVoid;
import io.smallrye.reactive.messaging.beans.BeanConsumingMessagesAndReturningSomething;
import io.smallrye.reactive.messaging.beans.BeanConsumingMessagesAndReturningVoid;
import io.smallrye.reactive.messaging.beans.BeanConsumingPayloadsAndReturningACompletionStageOfSomething;
import io.smallrye.reactive.messaging.beans.BeanConsumingPayloadsAndReturningACompletionStageOfVoid;
import io.smallrye.reactive.messaging.beans.BeanConsumingPayloadsAndReturningSomething;
import io.smallrye.reactive.messaging.beans.BeanConsumingPayloadsAndReturningVoid;
import io.smallrye.reactive.messaging.beans.BeanReturningASubscriberOfMessages;
import io.smallrye.reactive.messaging.beans.BeanReturningASubscriberOfMessagesButDiscarding;
import io.smallrye.reactive.messaging.beans.BeanReturningASubscriberOfPayloads;
public class SubscriberShapeTest extends WeldTestBaseWithoutTails {
@Override
public List<Class<?>> getBeans() {
return Collections.singletonList(SourceOnly.class);
}
@Test
public void testBeanProducingASubscriberOfMessages() {
initializer.addBeanClasses(BeanReturningASubscriberOfMessages.class);
initialize();
BeanReturningASubscriberOfMessages collector = container.select(BeanReturningASubscriberOfMessages.class).get();
assertThat(collector.payloads()).isEqualTo(EXPECTED);
}
@Test
public void testBeanProducingASubscriberOfPayloads() {
initializer.addBeanClasses(BeanReturningASubscriberOfPayloads.class);
initialize();
BeanReturningASubscriberOfPayloads collector = container.select(BeanReturningASubscriberOfPayloads.class).get();
assertThat(collector.payloads()).isEqualTo(EXPECTED);
}
@Test
public void testThatWeCanProduceSubscriberOfMessage() {
initializer.addBeanClasses(BeanReturningASubscriberOfMessagesButDiscarding.class);
initialize();
assertThatSubscriberWasPublished(container);
}
@Test
public void testThatWeCanConsumeMessagesFromAMethodReturningVoid() {
// This case is not supported as it forces blocking acknowledgment.
// See the MediatorConfiguration class for details.
initializer.addBeanClasses(BeanConsumingMessagesAndReturningVoid.class);
try {
initialize();
fail("Expected failure - method validation should have failed");
} catch (DeploymentException e) {
// Check we have the right cause
assertThat(e).hasMessageContaining("Invalid method").hasMessageContaining("acknowledgment");
}
}
@Test
public void testThatWeCanConsumePayloadsFromAMethodReturningVoid() {
initializer.addBeanClasses(BeanConsumingPayloadsAndReturningVoid.class);
initialize();
BeanConsumingPayloadsAndReturningVoid collector = container.getBeanManager()
.createInstance().select(BeanConsumingPayloadsAndReturningVoid.class).get();
assertThat(collector.payloads()).isEqualTo(EXPECTED);
}
@Test
public void testThatWeCanConsumeMessagesFromAMethodReturningSomething() {
// This case is not supported as it forces blocking acknowledgment.
// See the MediatorConfiguration class for details.
initializer.addBeanClasses(BeanConsumingMessagesAndReturningSomething.class);
try {
initialize();
fail("Expected failure - method validation should have failed");
} catch (DeploymentException e) {
// Check we have the right cause
assertThat(e).hasMessageContaining("Invalid method").hasMessageContaining("acknowledgment");
}
}
@Test
public void testThatWeCanConsumePayloadsFromAMethodReturningSomething() {
initializer.addBeanClasses(BeanConsumingPayloadsAndReturningSomething.class);
initialize();
BeanConsumingPayloadsAndReturningSomething collector = container.getBeanManager()
.createInstance().select(BeanConsumingPayloadsAndReturningSomething.class).get();
assertThat(collector.payloads()).isEqualTo(EXPECTED);
}
@Test
public void testThatWeCanConsumeMessagesFromAMethodReturningACompletionStage() {
initializer.addBeanClasses(BeanConsumingMessagesAndReturningACompletionStageOfVoid.class);
initialize();
BeanConsumingMessagesAndReturningACompletionStageOfVoid collector = container.getBeanManager()
.createInstance().select(BeanConsumingMessagesAndReturningACompletionStageOfVoid.class).get();
await().until(() -> collector.payloads().size() == EXPECTED.size());
assertThat(collector.payloads()).isEqualTo(EXPECTED);
collector.close();
}
@Test
public void testThatWeCanConsumePayloadsFromAMethodReturningACompletionStage() {
initializer.addBeanClasses(BeanConsumingPayloadsAndReturningACompletionStageOfVoid.class);
initialize();
BeanConsumingPayloadsAndReturningACompletionStageOfVoid collector = container.getBeanManager()
.createInstance().select(BeanConsumingPayloadsAndReturningACompletionStageOfVoid.class).get();
await().until(() -> collector.payloads().size() == EXPECTED.size());
assertThat(collector.payloads()).isEqualTo(EXPECTED);
collector.close();
}
@Test
public void testThatWeCanConsumeMessagesFromAMethodReturningACompletionStageOfSomething() {
initializer.addBeanClasses(BeanConsumingMessagesAndReturningACompletionStageOfSomething.class);
initialize();
BeanConsumingMessagesAndReturningACompletionStageOfSomething collector = container.getBeanManager()
.createInstance().select(BeanConsumingMessagesAndReturningACompletionStageOfSomething.class).get();
await().until(() -> collector.payloads().size() == EXPECTED.size());
assertThat(collector.payloads()).isEqualTo(EXPECTED);
collector.close();
}
@Test
public void testThatWeCanConsumePayloadsFromAMethodReturningACompletionStageOfSomething() {
initializer.addBeanClasses(BeanConsumingPayloadsAndReturningACompletionStageOfSomething.class);
initialize();
BeanConsumingPayloadsAndReturningACompletionStageOfSomething collector = container.getBeanManager()
.createInstance().select(BeanConsumingPayloadsAndReturningACompletionStageOfSomething.class).get();
await().until(() -> collector.payloads().size() == EXPECTED.size());
assertThat(collector.payloads()).isEqualTo(EXPECTED);
collector.close();
}
@SuppressWarnings("unchecked")
private void assertThatSubscriberWasPublished(SeContainer container) {
assertThat(registry(container).getOutgoingNames()).contains("subscriber");
List<SubscriberBuilder<? extends Message, Void>> subscriber = registry(container).getSubscribers("subscriber");
assertThat(subscriber).isNotEmpty();
List<String> list = new ArrayList<>();
Flowable.just("a", "b", "c").map(Message::of)
.doOnNext(m -> list.add(m.getPayload()))
.subscribe(((SubscriberBuilder) subscriber.get(0)).build());
assertThat(list).containsExactly("a", "b", "c");
}
}
| 48.539394 | 120 | 0.752903 |
b5a6c030e64b5b5baeafbfc381ab1d865a7e8e5e | 1,836 | package com.ck.orangeblogdao.po;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ck.orangeblogdao.pojo.BasePo;
import java.util.Date;
@TableName(value="m_fnd_dictionary")
public class FndDictionaryPo extends BasePo {
/* */
private String dicCode;
/* */
private String dicValue;
/* */
private String dicDesc;
/**
* 字典类型
*/
private String dicType;
/* */
private String status;
/* */
private String sCid;
/* */
private Date sCt;
/* */
private String sUid;
/* */
private Date sUt;
public String getDicType() {
return dicType;
}
public void setDicType(String dicType) {
this.dicType = dicType;
}
public String getDicCode(){
return this.dicCode;
}
public void setDicCode(String dicCode){
this.dicCode = dicCode;
}
public String getDicValue(){
return this.dicValue;
}
public void setDicValue(String dicValue){
this.dicValue = dicValue;
}
public String getDicDesc(){
return this.dicDesc;
}
public void setDicDesc(String dicDesc){
this.dicDesc = dicDesc;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSCid(){
return this.sCid;
}
public void setSCid(String sCid){
this.sCid = sCid;
}
public Date getSCt(){
return this.sCt;
}
public void setSCt(Date sCt){
this.sCt = sCt;
}
public String getSUid(){
return this.sUid;
}
public void setSUid(String sUid){
this.sUid = sUid;
}
public Date getSUt(){
return this.sUt;
}
public void setSUt(Date sUt){
this.sUt = sUt;
}
}
| 16.247788 | 53 | 0.583333 |
f4162dd63d8680d1719b8e7b5dd616aad0f855db | 1,286 | /**
* Copyright (c) 2011-2030, author jinchao ([email protected]).
* <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>
* https://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.
*/
package cn.itchao.edu.framework.web;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author jinchao
*/
public class BaseController {
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
@ModelAttribute
public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
this.session = request.getSession();
}
}
| 28.577778 | 88 | 0.741058 |
f4f39e3c760c01f07ef2a2b6c875cb75ed1130b6 | 2,275 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.dmn.engine.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.camunda.bpm.dmn.engine.DmnDecision;
import org.camunda.bpm.dmn.engine.DmnDecisionLogic;
public class DmnDecisionImpl implements DmnDecision {
protected String key;
protected String name;
protected DmnDecisionLogic decisionLogic;
protected Collection<DmnDecision> requiredDecision = new ArrayList<DmnDecision>();
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setDecisionLogic(DmnDecisionLogic decisionLogic) {
this.decisionLogic = decisionLogic;
}
public DmnDecisionLogic getDecisionLogic() {
return decisionLogic;
}
public void setRequiredDecision(List<DmnDecision> requiredDecision) {
this.requiredDecision = requiredDecision;
}
@Override
public Collection<DmnDecision> getRequiredDecisions() {
return requiredDecision;
}
@Override
public boolean isDecisionTable() {
return decisionLogic != null && decisionLogic instanceof DmnDecisionTableImpl;
}
@Override
public String toString() {
return "DmnDecisionTableImpl{" +
" key= "+ key +
", name= "+ name +
", requiredDecision=" + requiredDecision +
", decisionLogic=" + decisionLogic +
'}';
}
}
| 27.409639 | 84 | 0.731868 |
bb44865dd4589ffaa6880992beb7bd4d0c4df5ab | 604 | package net.collaud.fablab.manager.data.virtual;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import net.collaud.fablab.manager.data.UserEO;
/**
*
* @author Gaetan Collaud <[email protected]>
*/
@Getter
@EqualsAndHashCode(of = {"id"})
public class HistoryEntryUser {
private final Long id;
private final String lastname;
private final String firstname;
public HistoryEntryUser(UserEO user){
this.id = user.getId();
this.lastname = user.getLastname();
this.firstname = user.getFirstname();
}
@Override
public String toString() {
return firstname+" "+lastname;
}
}
| 20.133333 | 51 | 0.738411 |
6b2f3666a5ba778bfed200a8420f4a0b80c3e5e3 | 2,557 | package io.subutai.core.environment.api.dto;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonProperty;
import io.subutai.common.host.ContainerHostState;
import io.subutai.common.peer.ContainerSize;
/**
* Trimmed container for REST
*/
public class ContainerDto
{
@JsonProperty( "id" )
private String id;
@JsonProperty( "environmentId" )
private String environmentId;
@JsonProperty( "hostname" )
private String hostname;
@JsonProperty( "ip" )
private String ip;
@JsonProperty( "templateName" )
private String templateName;
@JsonProperty( "templateId" )
private String templateId;
@JsonProperty( "type" )
private ContainerSize type;
@JsonProperty( "arch" )
private String arch;
@JsonProperty( "tags" )
private Set<String> tags;
@JsonProperty( "peerId" )
private String peerId;
@JsonProperty( "hostId" )
private String hostId;
@JsonProperty( "local" )
private boolean local;
@JsonProperty( "state" )
private ContainerHostState state;
// Where environment of container created: subutai, hub
@JsonProperty( "dataSource" )
private String dataSource;
public ContainerDto( @JsonProperty( "id" ) final String id,
@JsonProperty( "environmentId" ) final String environmentId,
@JsonProperty( "hostname" ) final String hostname, @JsonProperty( "ip" ) final String ip,
@JsonProperty( "templateName" ) final String templateName,
@JsonProperty( "type" ) final ContainerSize type, @JsonProperty( "arch" ) final String arch,
@JsonProperty( "tags" ) final Set<String> tags, @JsonProperty( "peerId" ) final String peerId,
@JsonProperty( "hostId" ) final String hostId, @JsonProperty( "local" ) boolean local,
@JsonProperty( "dataSource" ) String dataSource,
@JsonProperty( "state" ) ContainerHostState state,
@JsonProperty( "templateId" ) String templateId )
{
this.id = id;
this.environmentId = environmentId;
this.hostname = hostname;
this.ip = ip;
this.templateName = templateName;
this.type = type;
this.arch = arch;
this.tags = tags;
this.peerId = peerId;
this.hostId = hostId;
this.local = local;
this.templateId = templateId;
this.dataSource = dataSource;
this.state = state;
}
}
| 33.644737 | 119 | 0.620649 |
7864ad6f1e894f584a993dc85e1a3bcb1efed260 | 285 | public class Customer {
int id;
String firsName;
String lastName;
public Customer(){
}
public Customer(int id, String firsName,String lastName){
this.id = id;
this.firsName = firsName;
this.lastName = lastName;
}
}
| 17.8125 | 62 | 0.564912 |
2c5d91dc44c12fa25fa9d8fbe94ba37d72ed8c67 | 2,229 | package br.apolo.data.model;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import br.apolo.common.util.InputLength;
import br.apolo.data.entitylistener.AuditLogListener;
import br.apolo.security.UserPermission;
@Entity
@EntityListeners(value = AuditLogListener.class)
@Table(name = "user_group")
@AttributeOverride(name = "id", column = @Column(name = "user_group_id"))
public class UserGroup extends AuditableBaseEntity {
private static final long serialVersionUID = -7985007135932159381L;
@Column(name = "name", length = InputLength.MEDIUM, nullable = false)
@NotNull
@Size(min = 1, max = InputLength.MEDIUM)
private String name;
@ElementCollection(targetClass = UserPermission.class, fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
@CollectionTable(name = "group_permission",
joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "user_group_id", insertable = true, updatable = true, nullable = false),
uniqueConstraints = @UniqueConstraint(columnNames = {"group_id", "permission_name" }, name = "uq_group_permission")
)
@Column(name = "permission_name")
@NotNull
private Set<UserPermission> permissions;
@ManyToMany(mappedBy = "groups", cascade = CascadeType.MERGE)
private Set<User> users;
public String getName() {
return name;
}
public void setName(String value) {
name = value;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users1) {
this.users = users1;
}
public Set<UserPermission> getPermissions() {
return permissions;
}
public void setPermissions(Set<UserPermission> perms) {
this.permissions = perms;
}
}
| 28.948052 | 144 | 0.778825 |
1cad479250510b0f50e352d778479db12b2a2499 | 9,215 | package me.josephzhu.javaconcurrenttest.lock;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.StampedLock;
import java.util.stream.IntStream;
@Slf4j
public class LockBenchmark {
final static int LOOP_COUNT = 1000000;
@Test
public void test() throws Exception {
List<TestCase> testCases = new ArrayList<>();
Arrays.asList(SyncTask.class,
ReentrantLockTask.class,
FairReentrantLockTask.class,
ReentrantReadWriteLockTask.class,
FairReentrantReadWriteLockTask.class,
StampedLockTask.class
).forEach(syncTaskClass -> {
testCases.add(new TestCase(syncTaskClass, 1, 0));
testCases.add(new TestCase(syncTaskClass, 10, 0));
testCases.add(new TestCase(syncTaskClass, 0, 1));
testCases.add(new TestCase(syncTaskClass, 0, 10));
testCases.add(new TestCase(syncTaskClass, 1, 1));
testCases.add(new TestCase(syncTaskClass, 10, 10));
testCases.add(new TestCase(syncTaskClass, 50, 50));
testCases.add(new TestCase(syncTaskClass, 100, 100));
testCases.add(new TestCase(syncTaskClass, 500, 500));
testCases.add(new TestCase(syncTaskClass, 1000, 1000));
testCases.add(new TestCase(syncTaskClass, 1, 10));
testCases.add(new TestCase(syncTaskClass, 10, 100));
testCases.add(new TestCase(syncTaskClass, 10, 200));
testCases.add(new TestCase(syncTaskClass, 10, 500));
testCases.add(new TestCase(syncTaskClass, 10, 1000));
testCases.add(new TestCase(syncTaskClass, 10, 1));
testCases.add(new TestCase(syncTaskClass, 100, 10));
testCases.add(new TestCase(syncTaskClass, 200, 10));
testCases.add(new TestCase(syncTaskClass, 500, 10));
testCases.add(new TestCase(syncTaskClass, 1000, 10));
});
testCases.forEach(testCase -> {
System.gc();
try {
benchmark(testCase);
} catch (Exception e) {
e.printStackTrace();
}
});
StringBuilder stringBuilder = new StringBuilder();
int index = 0;
for (TestCase testCase : testCases) {
if (index % 20 == 0)
stringBuilder.append("\r\n");
stringBuilder.append(testCase.duration);
stringBuilder.append(",");
index++;
}
System.out.println(stringBuilder.toString());
}
private void benchmark(TestCase testCase) throws Exception {
LockTask.counter = 0;
log.info("Start benchmark:{}", testCase);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch finish = new CountDownLatch(testCase.readerThreadCount + testCase.writerThreadCount);
if (testCase.readerThreadCount > 0) {
LockTask readerTask = (LockTask) testCase.lockTaskClass.getDeclaredConstructor(Boolean.class).newInstance(false);
readerTask.start = start;
readerTask.finish = finish;
readerTask.loopCount = LOOP_COUNT / testCase.readerThreadCount;
IntStream.rangeClosed(1, testCase.readerThreadCount)
.mapToObj(__ -> new Thread(readerTask))
.forEach(Thread::start);
}
if (testCase.writerThreadCount > 0) {
LockTask writerTask = (LockTask) testCase.lockTaskClass.getDeclaredConstructor(Boolean.class).newInstance(true);
writerTask.start = start;
writerTask.finish = finish;
writerTask.loopCount = LOOP_COUNT / testCase.writerThreadCount;
IntStream.rangeClosed(1, testCase.writerThreadCount)
.mapToObj(__ -> new Thread(writerTask))
.forEach(Thread::start);
}
start.countDown();
long begin = System.currentTimeMillis();
finish.await();
if (testCase.writerThreadCount > 0)
Assert.assertEquals(LOOP_COUNT, LockTask.counter);
testCase.duration = System.currentTimeMillis() - begin;
log.info("Finish benchmark:{}", testCase);
}
}
@Slf4j
abstract class LockTask implements Runnable {
protected static volatile long counter;
protected boolean write;
int loopCount;
CountDownLatch start;
CountDownLatch finish;
public LockTask(Boolean write) {
this.write = write;
}
@Override
public void run() {
try {
start.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < loopCount; i++) {
doTask();
}
finish.countDown();
}
abstract protected void doTask();
}
@Slf4j
class SyncTask extends LockTask {
private static Object locker = new Object();
public SyncTask(Boolean write) {
super(write);
}
@Override
protected void doTask() {
synchronized (locker) {
if (write) {
counter++;
} else {
long value = counter + 1;
//log.debug("{}, {}", this.getClass().getSimpleName(), value);
}
}
}
}
@Slf4j
class ReentrantLockTask extends LockTask {
private static ReentrantLock locker = new ReentrantLock();
public ReentrantLockTask(Boolean write) {
super(write);
}
@Override
protected void doTask() {
locker.lock();
try {
if (write) {
counter++;
} else {
long value = counter + 1;
//log.debug("{}, {}", this.getClass().getSimpleName(), value);
}
} finally {
locker.unlock();
}
}
}
@Slf4j
class FairReentrantLockTask extends LockTask {
private static ReentrantLock locker = new ReentrantLock(true);
public FairReentrantLockTask(Boolean write) {
super(write);
}
@Override
protected void doTask() {
locker.lock();
try {
if (write) {
counter++;
} else {
long value = counter + 1;
//log.debug("{}, {}", this.getClass().getSimpleName(), value);
}
} finally {
locker.unlock();
}
}
}
@Slf4j
class ReentrantReadWriteLockTask extends LockTask {
private static ReentrantReadWriteLock locker = new ReentrantReadWriteLock();
public ReentrantReadWriteLockTask(Boolean write) {
super(write);
}
@Override
protected void doTask() {
locker.writeLock().lock();
if (write) {
try {
counter++;
} finally {
locker.writeLock().unlock();
}
} else {
locker.readLock().lock();
try {
long value = counter + 1;
//log.debug("{}, {}", this.getClass().getSimpleName(), value);
} finally {
locker.readLock().unlock();
}
}
}
}
@Slf4j
class FairReentrantReadWriteLockTask extends LockTask {
private static ReentrantReadWriteLock locker = new ReentrantReadWriteLock(true);
public FairReentrantReadWriteLockTask(Boolean write) {
super(write);
}
@Override
protected void doTask() {
if (write) {
locker.writeLock().lock();
try {
counter++;
} finally {
locker.writeLock().unlock();
}
} else {
locker.readLock().lock();
try {
long value = counter + 1;
//log.debug("{}, {}", this.getClass().getSimpleName(), value);
} finally {
locker.readLock().unlock();
}
}
}
}
@Slf4j
class StampedLockTask extends LockTask {
private static StampedLock locker = new StampedLock();
public StampedLockTask(Boolean write) {
super(write);
}
@Override
protected void doTask() {
if (write) {
long stamp = locker.writeLock();
counter++;
locker.unlockWrite(stamp);
} else {
long stamp = locker.tryOptimisticRead();
long value = counter + 1;
if (!locker.validate(stamp)) {
stamp = locker.readLock();
try {
value = counter + 1;
} finally {
locker.unlockRead(stamp);
}
}
//log.debug("{}, {}", this.getClass().getSimpleName(), value);
}
}
}
@ToString
@RequiredArgsConstructor
class TestCase {
final Class lockTaskClass;
final int writerThreadCount;
final int readerThreadCount;
long duration;
}
| 29.161392 | 125 | 0.568747 |
9d97516a4b872fb539962b29c6ba82e3a5ea0d3c | 2,212 | package org.apache.hadoop.chukwa.datacollection.adaptor.filetailer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.TestCase;
import org.apache.hadoop.chukwa.Chunk;
import org.apache.hadoop.chukwa.datacollection.agent.ChukwaAgent;
import org.apache.hadoop.chukwa.datacollection.connector.ChunkCatcherConnector;
public class TestCharFileTailingAdaptorUTF8 extends TestCase {
ChunkCatcherConnector chunks;
public TestCharFileTailingAdaptorUTF8() {
chunks = new ChunkCatcherConnector();
chunks.start();
}
public void testCrSepAdaptor() throws IOException, InterruptedException,
ChukwaAgent.AlreadyRunningException {
ChukwaAgent agent = new ChukwaAgent();
File testFile = makeTestFile("chukwaTest", 80);
long adaptorId = agent
.processCommand("add org.apache.hadoop.chukwa.datacollection.adaptor.filetailer.CharFileTailingAdaptorUTF8"
+ " lines " + testFile + " 0");
assertTrue(adaptorId != -1);
System.out.println("getting a chunk...");
Chunk c = chunks.waitForAChunk();
System.out.println("got chunk");
assertTrue(c.getSeqID() == testFile.length());
assertTrue(c.getRecordOffsets().length == 80);
int recStart = 0;
for (int rec = 0; rec < c.getRecordOffsets().length; ++rec) {
String record = new String(c.getData(), recStart,
c.getRecordOffsets()[rec] - recStart + 1);
System.out.println("record " + rec + " was: " + record);
assertTrue(record.equals(rec + " abcdefghijklmnopqrstuvwxyz\n"));
recStart = c.getRecordOffsets()[rec] + 1;
}
assertTrue(c.getDataType().equals("lines"));
agent.stopAdaptor(adaptorId, false);
agent.shutdown();
}
private File makeTestFile(String name, int size) throws IOException {
File tmpOutput = new File(System.getProperty("test.build.data", "/tmp"),
name);
FileOutputStream fos = new FileOutputStream(tmpOutput);
PrintWriter pw = new PrintWriter(fos);
for (int i = 0; i < size; ++i) {
pw.print(i + " ");
pw.println("abcdefghijklmnopqrstuvwxyz");
}
pw.flush();
pw.close();
return tmpOutput;
}
}
| 34.5625 | 115 | 0.695298 |
0e6a9ba8f28401d8f32ee01d66016125b6c5720c | 4,622 | /*
* Copyright 2014 - 2017 Cognizant Technology Solutions
*
* 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.cognizant.cognizantits.ide.main.dashboard.server;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
*
*/
public class Tools {
private static final Logger LOG = Logger.getLogger(Tools.class.getName());
private static final String FORMAR = "dd-MM-yyyy";
private static final long MILLS_IN_DAY = 1000L * 60 * 60 * 24;
public static synchronized void writeFile(File f, String s) {
try (PrintWriter out = new PrintWriter(f)) {
out.write((s));
} catch (Exception ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
public static synchronized String readFile(File path) throws Exception {
return scanFile(path);
}
public static synchronized String scanFile(File path) throws Exception {
String data = "";
try (Scanner s = new Scanner(path).useDelimiter("\\A")) {
if (s.hasNext()) {
data = s.next();
}
}
return data;
}
public static synchronized long getMillisNow(String dateInString) {
try {
Date date = getFormatter().parse(dateInString), now = new Date();
return date.getTime() - now.getTime();
} catch (java.text.ParseException ex) {
LOG.log(Level.SEVERE, null, ex);
}
return -1;
}
public static String today() {
return getFormatter().format(new Date());
}
public static String after(int days) {
return getFormatter().format(getDateafter(days));
}
private static Date getDateafter(int days) {
return new Date(new Date().getTime() + toMillis(days));
}
private static long toMillis(int days) {
return MILLS_IN_DAY * (long) days;
}
/**
* @return the formatter
*/
public static SimpleDateFormat getFormatter() {
return new SimpleDateFormat(FORMAR);
}
public static Date toDate(String edate) {
try {
return getFormatter().parse(edate);
} catch (ParseException ex) {
return new Date();
}
}
public static void writeFile(File f, Set<String> set) {
try (PrintWriter out = new PrintWriter(f)) {
for (String s : set) {
out.write(s);
out.println();
}
} catch (Exception ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
}
public static boolean verifyLocalPort(String server, int port) {
try {
new ServerSocket(port).close();
return false;
} catch (IOException e) {
throw new RuntimeException("Couldn't create " + server + ". Port " + port + " already in use");
}
}
public static Date getScheduledTime() {
Calendar startTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 0);
startTime.set(Calendar.MINUTE, 0);
startTime.set(Calendar.SECOND, 0);
startTime.set(Calendar.MILLISECOND, 0);
if (startTime.before(now) || startTime.equals(now)) {
startTime.add(Calendar.DATE, 1);
}
return startTime.getTime();
}
public static int toInt(String v, int def) {
try {
return Integer.valueOf(v);
} catch (Exception ex) {
return def;
}
}
public static String IP() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (Exception ex) {
LOG.log(Level.WARNING, "unable to get ip address.. using 0.0.0.0", ex);
return "0.0.0.0";
}
}
}
| 28.530864 | 107 | 0.606664 |
6e1573103de402dbe14026d64976859169000481 | 3,500 | package com.englishnary.eridev.android.englishnary;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class NotesFecha extends ActionBarActivity {
//Definimos dos variables que hacen referencia a los EditText donde se cargan la fecha en uno y las notas de dicho día en el otro:
private EditText et_fecha,et_nota;
// En el método onCreate obtenemos las referencias de los dos EditText, normalmente lo hago en un
// método aparte para iniciar pero ahora solo són dos controles :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes_fecha);
et_fecha=(EditText)findViewById(R.id.et_fecha);
et_nota=(EditText)findViewById(R.id.et_nota);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/*El método grabar que se ejecuta cuando presionamos el botón grabar (no olvidar de inicializar la
propiedad onClick de cada botón con el nombre del método respectivo) tenemos primero que extraer la
fecha ingresada en el primer EditText y remplazar las barras de la fecha por guiones ya que no se
puede utilizar este caracter dentro de un nombre de archivo en Android:*/
public void grabar(View v) {
String nomarchivo=et_fecha.getText().toString();
nomarchivo=nomarchivo.replace('/','-');
try {
OutputStreamWriter archivo = new OutputStreamWriter(openFileOutput(
nomarchivo, Activity.MODE_PRIVATE));
archivo.write(et_nota.getText().toString());
archivo.flush();
archivo.close();
} catch (IOException e) {
}
Toast t = Toast.makeText(this, "La nota se ha guardado, introduce la fecha para recuperarla",
Toast.LENGTH_SHORT);
t.show();
et_fecha.setText("");
et_nota.setText("");
}
public void recuperar(View v) {
String nomarchivo=et_fecha.getText().toString();
nomarchivo=nomarchivo.replace('/','-');
boolean enco=false;
String[] archivos = fileList();
for (int f = 0; f < archivos.length; f++)
if (nomarchivo.equals(archivos[f]))
enco= true;
if (enco==true) {
try {
InputStreamReader archivo = new InputStreamReader(
openFileInput(nomarchivo));
BufferedReader br = new BufferedReader(archivo);
String linea = br.readLine();
String todo = "";
while (linea != null) {
todo = todo + linea + "\n";
linea = br.readLine();
}
br.close();
archivo.close();
et_nota.setText(todo);
} catch (IOException e) {
}
} else
{
Toast.makeText(this, "No hay notas grabadas para esa fecha", Toast.LENGTH_LONG).show();
et_nota.setText("");
}
}
} | 37.234043 | 134 | 0.626286 |
2bd9e94a2e07ccfebe7e457f30c93ab7864ca9b7 | 1,613 | package com.xml2j.tutorial.seq4.handlers;
/******************************************************************************
-----------------------------------------------------------------------------
XML2J XSD to Java code generator
-----------------------------------------------------------------------------
This code was generated using XML2J code generator.
Version: 2.5.0
Project home: XML2J https://github.com/lolkedijkstra/
Module: SEQ4
Generation date: Sun Apr 29 12:06:43 CEST 2018
Author: XML2J-GEN
******************************************************************************/
import org.xml.sax.XMLReader;
import com.xml2j.tutorial.seq4.ContainerType4;
import com.xml2j.tutorial.seq4.ContainerType4Handler;
import com.xml2j.xml.core.XMLMessageHandler;
import com.xml2j.xml.parser.ParserTask;
/**
* This class reads the XML document from an XML inputsource.
*
* This class is the entry point for the client application.
*/
public class SeqMessageHandler extends
XMLMessageHandler<ContainerType4> {
/** root element. */
static final String ELEMENT_NAME = "container";
/**
* Constructor.
*
* @see XMLMessageHandler XMLMessageHandler
* @param task
* The parser task
* @param reader
* The (SAX) XML Reader object
*/
public SeqMessageHandler(ParserTask task, XMLReader reader) {
super(reader
, new ContainerType4Handler(
task
, reader
, null // root has no parent
, ELEMENT_NAME
, ContainerType4.getAllocator()
, null // not applicable for root
, doProcess(ELEMENT_NAME, task))
);
}
}
| 26.016129 | 79 | 0.567266 |
bd1e453413fde5a266a1f323c25ee126bb14b149 | 1,542 | /*
* Copyright 2021 OPPO ESA Stack 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 io.esastack.commons.net.http;
import java.nio.charset.Charset;
import java.util.Map;
/**
* Builder interface for {@link MediaType}.
*/
public interface MediaTypeBuilder {
/**
* Sets {@link MediaType#subtype()}, default to {@code '*'}
*/
MediaTypeBuilder subtype(String subtype);
/**
* Sets {@link MediaType#charset()}
*/
default MediaTypeBuilder charset(Charset charset) {
return charset(charset.name());
}
/**
* Sets {@link MediaType#charset()}
*/
MediaTypeBuilder charset(String charset);
/**
* Add parameter into {@link MediaType#params()} ()}
*/
MediaTypeBuilder addParam(String key, String value);
/**
* Add parameters into {@link MediaType#params()}
*/
MediaTypeBuilder addParams(Map<String, String> parameters);
/**
* Builds a new instance of {@link MediaType} now.
*/
MediaType build();
}
| 26.135593 | 75 | 0.66537 |
d00d36aaee9df0063175c2f8e04b2c8804f1477d | 1,471 | package net.iexos.musicalarm;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.NumberPicker;
public final class DelayPickerFragment extends DialogFragment {
public DelayPickerFragment() {}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
Bundle bundle = getArguments();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final NumberPicker picker = new NumberPicker(getActivity());
picker.setMaxValue(60);
picker.setMinValue(1);
picker.setValue(bundle.getInt(AlarmViewActivity.PREF_DELAY));
builder.setTitle(R.string.set_delay);
builder.setView(picker);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AlarmViewActivity activity = (AlarmViewActivity) getActivity();
activity.onDelayChosen(picker.getValue());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
| 35.878049 | 90 | 0.668253 |
cc4e92a4ae27ed1dbcd2587449a5e8b187fbe8d3 | 15,387 | /*
* Copyright (C) 2018-2020. Huawei Technologies Co., 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 io.prestosql.tests;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import io.prestosql.Session;
import io.prestosql.execution.QueryManager;
import io.prestosql.execution.TaskInfo;
import io.prestosql.execution.TaskManager;
import io.prestosql.execution.TaskState;
import io.prestosql.metadata.NodeState;
import io.prestosql.server.BasicQueryInfo;
import io.prestosql.server.NodeStateChangeHandler;
import io.prestosql.server.testing.TestingPrestoServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static io.prestosql.execution.QueryState.FINISHED;
import static io.prestosql.memory.TestMemoryManager.createQueryRunner;
import static io.prestosql.server.NodeStateChangeHandler.isValidStateTransition;
import static io.prestosql.testing.TestingSession.testSessionBuilder;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
@Test(singleThreaded = true)
public class TestNodeStateChange
{
private static final long SHUTDOWN_TIMEOUT_MILLIS1 = 20_000;
private static final long SHUTDOWN_TIMEOUT_MILLIS2 = 240_000;
private static final Session TINY_SESSION = testSessionBuilder()
.setCatalog("tpch")
.setSchema("tiny")
.build();
private static final Map<String, String> defaultProperties = ImmutableMap.<String, String>builder()
.put("shutdown.grace-period", "5s")
.put("node-scheduler.include-coordinator", "false")
.build();
private static final Map<String, String> properties = ImmutableMap.<String, String>builder()
.put("node-scheduler.include-coordinator", "false")
.put("shutdown.grace-period", "10s")
.build();
private ListeningExecutorService executor;
@BeforeClass
public void setUp()
{
executor = MoreExecutors.listeningDecorator(newCachedThreadPool());
}
@AfterClass(alwaysRun = true)
public void shutdown()
{
executor.shutdownNow();
}
@Test
public void testIsValidStateTransition()
{
// oldState = ACTIVE
assertTrue(isValidStateTransition(NodeState.ACTIVE, NodeState.ACTIVE));
assertFalse(isValidStateTransition(NodeState.ACTIVE, NodeState.INACTIVE));
assertTrue(isValidStateTransition(NodeState.ACTIVE, NodeState.ISOLATING));
assertTrue(isValidStateTransition(NodeState.ACTIVE, NodeState.ISOLATED));
assertTrue(isValidStateTransition(NodeState.ACTIVE, NodeState.SHUTTING_DOWN));
// oldState = INACTIVE
assertFalse(isValidStateTransition(NodeState.INACTIVE, NodeState.ACTIVE));
assertFalse(isValidStateTransition(NodeState.INACTIVE, NodeState.INACTIVE));
assertFalse(isValidStateTransition(NodeState.INACTIVE, NodeState.ISOLATING));
assertFalse(isValidStateTransition(NodeState.INACTIVE, NodeState.ISOLATED));
assertTrue(isValidStateTransition(NodeState.INACTIVE, NodeState.SHUTTING_DOWN));
// oldState = ISOLATING
assertTrue(isValidStateTransition(NodeState.ISOLATING, NodeState.ACTIVE));
assertFalse(isValidStateTransition(NodeState.ISOLATING, NodeState.INACTIVE));
assertTrue(isValidStateTransition(NodeState.ISOLATING, NodeState.ISOLATING));
assertTrue(isValidStateTransition(NodeState.ISOLATING, NodeState.ISOLATED));
assertTrue(isValidStateTransition(NodeState.ISOLATING, NodeState.SHUTTING_DOWN));
// oldState = ISOLATED
assertTrue(isValidStateTransition(NodeState.ISOLATED, NodeState.ACTIVE));
assertFalse(isValidStateTransition(NodeState.ISOLATED, NodeState.INACTIVE));
assertTrue(isValidStateTransition(NodeState.ISOLATED, NodeState.ISOLATING));
assertTrue(isValidStateTransition(NodeState.ISOLATED, NodeState.ISOLATED));
assertTrue(isValidStateTransition(NodeState.ISOLATED, NodeState.SHUTTING_DOWN));
// oldState = SHUTTING_DOWN
assertFalse(isValidStateTransition(NodeState.SHUTTING_DOWN, NodeState.ACTIVE));
assertFalse(isValidStateTransition(NodeState.SHUTTING_DOWN, NodeState.INACTIVE));
assertFalse(isValidStateTransition(NodeState.SHUTTING_DOWN, NodeState.ISOLATING));
assertFalse(isValidStateTransition(NodeState.SHUTTING_DOWN, NodeState.ISOLATED));
assertTrue(isValidStateTransition(NodeState.SHUTTING_DOWN, NodeState.SHUTTING_DOWN));
}
@Test(timeOut = 30_000)
public void testBasicDoStateTransition()
throws Exception
{
try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, defaultProperties)) {
TestingPrestoServer worker = getWorker(queryRunner);
NodeStateChangeHandler nodeStateChangeHandler = worker.getNodeStateChangeHandler();
// current state is ACTIVE
assertEquals(nodeStateChangeHandler.getState(), NodeState.ACTIVE);
// graceful isolation, state will be changed to ISOLATED finally
nodeStateChangeHandler.doStateTransition(NodeState.ISOLATING);
while (nodeStateChangeHandler.getState().equals(NodeState.ISOLATING)) {
Thread.sleep(1000);
}
assertEquals(nodeStateChangeHandler.getState(), NodeState.ISOLATED);
// abort isolation, state change to ACTIVE
nodeStateChangeHandler.doStateTransition(NodeState.ACTIVE);
assertEquals(nodeStateChangeHandler.getState(), NodeState.ACTIVE);
// graceful isolation, state will be changed to ISOLATING
nodeStateChangeHandler.doStateTransition(NodeState.ISOLATING);
assertEquals(nodeStateChangeHandler.getState(), NodeState.ISOLATING);
// abort isolation, state change to ACTIVE
nodeStateChangeHandler.doStateTransition(NodeState.ACTIVE);
assertEquals(nodeStateChangeHandler.getState(), NodeState.ACTIVE);
// force isolation, state change to ISOLATED immediately
nodeStateChangeHandler.doStateTransition(NodeState.ISOLATED);
assertEquals(nodeStateChangeHandler.getState(), NodeState.ISOLATED);
// shutdown
nodeStateChangeHandler.doStateTransition(NodeState.SHUTTING_DOWN);
TestingPrestoServer.TestShutdownAction shutdownAction = (TestingPrestoServer.TestShutdownAction) worker.getShutdownAction();
shutdownAction.waitForShutdownComplete(SHUTDOWN_TIMEOUT_MILLIS1);
assertTrue(shutdownAction.isShutdown());
}
}
@Test(timeOut = 30_000)
public void testSuccessfulAbort()
throws Exception
{
try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, defaultProperties)) {
TestingPrestoServer worker = getWorker(queryRunner);
NodeStateChangeHandler nodeStateChangeHandler = worker.getNodeStateChangeHandler();
// current state is ACTIVE
assertEquals(nodeStateChangeHandler.getState(), NodeState.ACTIVE);
nodeStateChangeHandler.doStateTransition(NodeState.ISOLATING);
// Future task wait for 5 seconds to start
Thread.sleep(6000);
// abort isolation, state change to ACTIVE
nodeStateChangeHandler.doStateTransition(NodeState.ACTIVE);
assertEquals(nodeStateChangeHandler.getState(), NodeState.ACTIVE);
// If future task wasn't cancelled successfully, it'll finish and may change state
Thread.sleep(6000);
// Verify state wasn't changed to isolated
assertEquals(nodeStateChangeHandler.getState(), NodeState.ACTIVE);
}
}
@Test(timeOut = 30_000)
public void testWorkerIsolation()
throws Exception
{
try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, defaultProperties)) {
List<ListenableFuture<?>> queryFutures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk")));
}
TestingPrestoServer worker = queryRunner.getServers()
.stream()
.filter(server -> !server.isCoordinator())
.findFirst()
.get();
assertEquals(worker.getNodeStateChangeHandler().getState(), NodeState.ACTIVE);
TaskManager taskManager = worker.getTaskManager();
// wait until tasks show up on the worker
while (taskManager.getAllTaskInfo().isEmpty()) {
MILLISECONDS.sleep(500);
}
worker.getNodeStateChangeHandler().doStateTransition(NodeState.ISOLATING);
Futures.allAsList(queryFutures).get();
List<TaskInfo> taskInfos = worker.getTaskManager().getAllTaskInfo();
for (TaskInfo info : taskInfos) {
assertEquals(info.getTaskStatus().getState(), TaskState.FINISHED);
}
while (!worker.getNodeStateChangeHandler().getState().equals(NodeState.ISOLATED)) {
Thread.sleep(1000);
}
}
}
@Test(timeOut = 30_000)
public void testCoordinatorIsolation()
throws Exception
{
try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, defaultProperties)) {
List<ListenableFuture<?>> queryFutures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk")));
}
TestingPrestoServer coordinator = queryRunner.getServers()
.stream()
.filter(TestingPrestoServer::isCoordinator)
.findFirst()
.get();
QueryManager queryManager = coordinator.getQueryManager();
// wait until queries show up on the coordinator
while (queryManager.getQueries().isEmpty()) {
MILLISECONDS.sleep(500);
}
assertEquals(coordinator.getNodeStateChangeHandler().getState(), NodeState.ACTIVE);
coordinator.getNodeStateChangeHandler().doStateTransition(NodeState.ISOLATING);
Futures.allAsList(queryFutures).get();
List<BasicQueryInfo> queryInfos = queryRunner.getCoordinator().getQueryManager().getQueries();
for (BasicQueryInfo info : queryInfos) {
assertEquals(info.getState(), FINISHED);
}
while (!coordinator.getNodeStateChangeHandler().getState().equals(NodeState.ISOLATED)) {
Thread.sleep(1000);
}
}
}
@Test(timeOut = SHUTDOWN_TIMEOUT_MILLIS2)
public void testWorkerShutdown()
throws Exception
{
try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) {
List<ListenableFuture<?>> queryFutures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk")));
}
TestingPrestoServer worker = queryRunner.getServers()
.stream()
.filter(server -> !server.isCoordinator())
.findFirst()
.get();
TaskManager taskManager = worker.getTaskManager();
// wait until tasks show up on the worker
while (taskManager.getAllTaskInfo().isEmpty()) {
MILLISECONDS.sleep(500);
}
worker.getNodeStateChangeHandler().doStateTransition(NodeState.SHUTTING_DOWN);
Futures.allAsList(queryFutures).get();
List<BasicQueryInfo> queryInfos = queryRunner.getCoordinator().getQueryManager().getQueries();
for (BasicQueryInfo info : queryInfos) {
assertEquals(info.getState(), FINISHED);
}
TestingPrestoServer.TestShutdownAction shutdownAction = (TestingPrestoServer.TestShutdownAction) worker.getShutdownAction();
shutdownAction.waitForShutdownComplete(SHUTDOWN_TIMEOUT_MILLIS2);
assertTrue(shutdownAction.isShutdown());
}
}
@Test
public void testCoordinatorShutdown()
throws Exception
{
try (DistributedQueryRunner queryRunner = createQueryRunner(TINY_SESSION, properties)) {
List<ListenableFuture<?>> queryFutures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
queryFutures.add(executor.submit(() -> queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk")));
}
TestingPrestoServer coordinator = queryRunner.getServers()
.stream()
.filter(TestingPrestoServer::isCoordinator)
.findFirst()
.get();
QueryManager queryManager = coordinator.getQueryManager();
// wait until queries show up on the coordinator
while (queryManager.getQueries().isEmpty()) {
MILLISECONDS.sleep(500);
}
coordinator.getNodeStateChangeHandler().doStateTransition(NodeState.SHUTTING_DOWN);
Futures.allAsList(queryFutures).get();
List<BasicQueryInfo> queryInfos = queryRunner.getCoordinator().getQueryManager().getQueries();
for (BasicQueryInfo info : queryInfos) {
assertEquals(info.getState(), FINISHED);
}
TestingPrestoServer.TestShutdownAction shutdownAction = (TestingPrestoServer.TestShutdownAction) coordinator.getShutdownAction();
shutdownAction.waitForShutdownComplete(SHUTDOWN_TIMEOUT_MILLIS2);
assertTrue(shutdownAction.isShutdown());
}
}
private TestingPrestoServer getWorker(DistributedQueryRunner queryRunner)
{
return queryRunner.getServers()
.stream()
.filter(server -> !server.isCoordinator())
.findFirst()
.get();
}
}
| 43.466102 | 141 | 0.67505 |
1a62c795d6dc5af99aea9b8b3ca00d6ee6716841 | 12,914 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.course.certificate.manager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import org.apache.logging.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.olat.core.commons.services.pdf.PdfService;
import org.olat.core.gui.render.StringOutput;
import org.olat.core.id.Identity;
import org.olat.core.id.User;
import org.olat.core.id.UserConstants;
import org.olat.core.logging.Tracing;
import org.olat.core.util.Formatter;
import org.olat.core.util.StringHelper;
import org.olat.core.util.i18n.I18nManager;
import org.olat.course.assessment.AssessmentHelper;
import org.olat.course.certificate.CertificateTemplate;
import org.olat.course.certificate.CertificatesManager;
import org.olat.repository.RepositoryEntry;
import org.olat.user.UserManager;
import org.olat.user.propertyhandlers.UserPropertyHandler;
/**
* Worker which use the PDF service in OpenOLAT
* to produce the certificates based on HTML templates.
*
*
* Initial date: 8 févr. 2019<br>
* @author srosse, [email protected], http://www.frentix.com
*
*/
public class CertificatePdfServiceWorker {
private static final Logger log = Tracing
.createLoggerFor(CertificatePDFFormWorker.class);
private final Float score;
private final Boolean passed;
private final Identity identity;
private final RepositoryEntry entry;
private final String certificateURL;
private final Date dateCertification;
private final Date dateFirstCertification;
private final Date dateNextRecertification;
private final String custom1;
private final String custom2;
private final String custom3;
private final Locale locale;
private final PdfService pdfService;
private final UserManager userManager;
private final CertificatesManagerImpl certificatesManager;
public CertificatePdfServiceWorker(Identity identity, RepositoryEntry entry, Float score, Boolean passed,
Date dateCertification, Date dateFirstCertification, Date nextRecertificationDate, String custom1,
String custom2, String custom3, String certificateURL, Locale locale, UserManager userManager,
CertificatesManagerImpl certificatesManager, PdfService pdfService) {
this.entry = entry;
this.score = score;
this.custom1 = custom1;
this.custom2 = custom2;
this.custom3 = custom3;
this.locale = locale;
this.passed = passed;
this.identity = identity;
this.dateCertification = dateCertification;
this.dateFirstCertification = dateFirstCertification;
this.dateNextRecertification = nextRecertificationDate;
this.certificateURL = certificateURL;
this.pdfService = pdfService;
this.userManager = userManager;
this.certificatesManager = certificatesManager;
}
public File fill(CertificateTemplate template, File destinationDir, String filename) {
File certificateFile = new File(destinationDir, filename);
File templateFile = certificatesManager.getTemplateFile(template);
File htmlCertificateFile = copyAndEnrichTemplate(templateFile);
File qrCodeScriptFile = new File(htmlCertificateFile.getParent(), "qrcode.min.js");
if(!qrCodeScriptFile.exists()) {
try(InputStream inQRCodeLib = CertificatesManager.class.getResourceAsStream("qrcode.min.js")) {
Files.copy(inQRCodeLib, qrCodeScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch(Exception e) {
log.error("Can not read qrcode.min.js for QR Code PDF generation", e);
}
}
try(OutputStream out = new FileOutputStream(certificateFile)) {
pdfService.convert(htmlCertificateFile.getParentFile(), htmlCertificateFile.getName(), out);
} catch(Exception e) {
log.error("", e);
certificateFile = null;
}
try {
Files.deleteIfExists(htmlCertificateFile.toPath());
} catch (IOException e) {
log.error("", e);
}
return certificateFile;
}
private File copyAndEnrichTemplate(File templateFile) {
boolean result = false;
File htmlCertificate = new File(templateFile.getParent(), "c" + UUID.randomUUID() + ".html");
try(Reader in = Files.newBufferedReader(templateFile.toPath(), Charset.forName("UTF-8"));
StringOutput content = new StringOutput(32000);
Writer output = new FileWriter(htmlCertificate)) {
VelocityContext context = getContext();
result = certificatesManager.getVelocityEngine().evaluate(context, content, "mailTemplate", in);
content.flush();
if(hasQRCode(content)) {
injectQRCodeScript(content);
}
output.write(content.toString());
output.flush();
result = true;
} catch(Exception e) {
log.error("", e);
}
return result ? htmlCertificate : null;
}
private boolean hasQRCode(StringOutput content) {
return content.contains("o_qrcode");
}
private void injectQRCodeScript(StringOutput content) {
int injectionIndex = injectionPoint(content);
StringBuilder qr = new StringBuilder(512);
qr.append("<script src='qrcode.min.js'></script>\n")
.append("<script>\n")
.append("/* <![CDATA[ */ \n")
.append("document.addEventListener('load', new function() {\n")
.append(" var qrcodes = document.querySelectorAll('.o_qrcode');\n")
.append(" for (var i=0; i<qrcodes.length; i++) {\n")
.append(" var qrcode = qrcodes[i];\n")
.append(" var val = qrcode.textContent;\n")
.append(" while (qrcode.firstChild) {\n")
.append(" qrcode.removeChild(qrcode.firstChild);\n")
.append(" }\n")
.append(" new QRCode(qrcode, val);\n")
.append(" }\n")
.append("});\n")
.append("/* ]]> */\n")
.append("</script>");
content.insert(injectionIndex, qr.toString());
}
private int injectionPoint(StringOutput content) {
String[] anchors = new String[] { "</body", "</ body", "</BODY", "</ BODY", "</html", "</HTML" };
for(String anchor:anchors) {
int bodyIndex = content.indexOf(anchor);
if(bodyIndex > 0) {
return bodyIndex;
}
}
return content.length();// last hope
}
private VelocityContext getContext() {
VelocityContext context = new VelocityContext();
fillUserProperties(context);
fillRepositoryEntry(context);
fillCertificationInfos(context);
fillAssessmentInfos(context);
fillMetaInfos(context);
context.put("formatter", new DateFormatter());
return context;
}
private void fillUserProperties(VelocityContext context) {
User user = identity.getUser();
List<UserPropertyHandler> userPropertyHandlers = userManager.getAllUserPropertyHandlers();
for (UserPropertyHandler handler : userPropertyHandlers) {
String propertyName = handler.getName();
String value = handler.getUserProperty(user, null);
context.put(propertyName, value);
}
String fullName = userManager.getUserDisplayName(identity);
context.put("fullName", fullName);
String firstName = user.getProperty(UserConstants.FIRSTNAME, null);
String lastName = user.getProperty(UserConstants.LASTNAME, null);
StringBuilder firstNameLastName = new StringBuilder();
StringBuilder lastNameFirstName = new StringBuilder();
if(StringHelper.containsNonWhitespace(firstName)) {
firstNameLastName.append(firstName);
}
if(StringHelper.containsNonWhitespace(lastName)) {
if(firstNameLastName.length() > 0) firstNameLastName.append(" ");
firstNameLastName.append(lastName);
lastNameFirstName.append(lastName);
}
if(StringHelper.containsNonWhitespace(firstName)) {
if(lastNameFirstName.length() > 0) lastNameFirstName.append(" ");
lastNameFirstName.append(firstName);
}
context.put("firstNameLastName", firstNameLastName.toString());
context.put("lastNameFirstName", lastNameFirstName.toString());
}
private void fillRepositoryEntry(VelocityContext context) {
String title = entry.getDisplayname();
context.put("title", title);
String description = entry.getDescription();
context.put("description", description);
String requirements = entry.getRequirements();
context.put("requirements", requirements);
String objectives = entry.getObjectives();
context.put("objectives", objectives);
String credits = entry.getCredits();
context.put("credits", credits);
String externalRef = entry.getExternalRef();
context.put("externalReference", externalRef);
String authors = entry.getAuthors();
context.put("authors", authors);
String expenditureOfWorks = entry.getExpenditureOfWork();
context.put("expenditureOfWorks", expenditureOfWorks);
String mainLanguage = entry.getMainLanguage();
context.put("mainLanguage", mainLanguage);
String location = entry.getLocation();
context.put("location", location);
if (entry.getLifecycle() != null) {
Formatter format = Formatter.getInstance(locale);
Date from = entry.getLifecycle().getValidFrom();
String formattedFrom = format.formatDate(from);
context.put("from", formattedFrom);
String formattedFromLong = format.formatDateLong(from);
context.put("fromLong", formattedFromLong);
Date to = entry.getLifecycle().getValidTo();
String formattedTo = format.formatDate(to);
context.put("to", formattedTo);
String formattedToLong = format.formatDateLong(to);
context.put("toLong", formattedToLong);
}
}
private void fillCertificationInfos(VelocityContext context) {
Formatter format = Formatter.getInstance(locale);
context.put("dateFormatter", format);
if(dateCertification == null) {
context.put("dateCertification", "");
} else {
String formattedDateCertification = format.formatDate(dateCertification);
context.put("dateCertification", formattedDateCertification);
String formattedDateCertificationLong = format.formatDateLong(dateCertification);
context.put("dateCertificationLong", formattedDateCertificationLong);
context.put("dateCertificationRaw", dateCertification);
}
if(dateFirstCertification == null) {
context.put("dateFirstCertification", "");
} else {
String formattedDateFirstCertification = format.formatDate(dateFirstCertification);
context.put("dateFirstCertification", formattedDateFirstCertification);
String formattedDateFirstCertificationLong = format.formatDate(dateFirstCertification);
context.put("dateFirstCertificationLong", formattedDateFirstCertificationLong);
context.put("dateFirstCertificationRaw", dateFirstCertification);
}
if(dateNextRecertification == null) {
context.put("dateNextRecertification", "");
} else {
String formattedDateNextRecertification = format.formatDate(dateNextRecertification);
context.put("dateNextRecertification", formattedDateNextRecertification);
String formattedDateNextRecertificationLong = format.formatDateLong(dateNextRecertification);
context.put("dateNextRecertificationLong", formattedDateNextRecertificationLong);
context.put("dateNextRecertificationRaw", dateNextRecertification);
}
}
private void fillAssessmentInfos(VelocityContext context) {
String roundedScore = AssessmentHelper.getRoundedScore(score);
context.put("score", roundedScore);
String status = (passed != null && passed.booleanValue()) ? "Passed" : "Failed";
context.put("status", status);
}
private void fillMetaInfos(VelocityContext context) {
context.put("custom1", custom1);
context.put("custom2", custom2);
context.put("custom3", custom3);
context.put("certificateVerificationUrl", certificateURL);
}
public static class DateFormatter {
public String formatDate(Date date, String language) {
Locale locale = I18nManager.getInstance().getLocaleOrDefault(language);
Formatter formatter = Formatter.getInstance(locale);
return formatter.formatDate(date);
}
public String formatDateLong(Date date, String language) {
Locale locale = I18nManager.getInstance().getLocaleOrDefault(language);
Formatter formatter = Formatter.getInstance(locale);
return formatter.formatDateLong(date);
}
}
}
| 37.216138 | 106 | 0.749264 |
8456198c4b1c76c0f84d3a659822488e301a92c5 | 992 | package cn.vonce.common.bean;
import cn.vonce.common.enumerate.ResultCode;
/**
* 业务方法 执行返回结果(Service Result)
*
* @author Jovi
* @version 1.0
* @email [email protected]
* @date 2018年1月18日下午5:39:57
*/
public class SResult<T> {
/**
* 结果码
*/
private ResultCode resultCode = ResultCode.OTHERS;
/**
* 成功与否的消息
*/
private String msg;
/**
* 返回的数据对象
*/
private T data;
public ResultCode getResultCode() {
return resultCode;
}
public void setResultCode(ResultCode resultCode) {
this.resultCode = resultCode;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "SResult [resultCode=" + resultCode + ", mess=" + msg + ", data=" + data + "]";
}
}
| 16.533333 | 94 | 0.563508 |
d1cd53930f818b0e73f14a71475a8f8a4a00fb2c | 1,544 | package org.lan.iti.sdk.pay.model.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.lan.iti.sdk.pay.model.IResponse;
import java.util.Map;
/**
* @author I'm
* @since 2021/3/26
* description 支付业务统一响应参数
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OrderResponse implements IResponse {
/**
* 平台 app id
*/
private String appId;
/**
* 支付渠道
*/
private String channel;
/**
* 商户支付单号
*/
private String outOrderNo;
/**
* 平台支付单号
*/
private String orderNo;
/**
* 订单标题
*/
private String subject;
/**
* 订单创建时间
*/
private String createTime;
/**
* 支付时间
*/
private String paidTime;
/**
* 超时时间
*/
private String expiredTime;
/**
* 渠道支付单号
*/
private String transactionNo;
/**
* 支付状态
*/
private String status;
/**
* 订单额外字段
*/
private Map<String, Object> extra;
/**
* 渠道响应信息
*/
private Map<String, Object> response;
/**
* 退款金额
*/
private String refundAmount;
/**
* 退款状态
*/
private String refundStatus;
/**
* 退款描述(暂无退款;部分退款;全部退款)
*/
private String refundDescription;
/**
* 错误码
*/
private String errCode;
/**
* 错误信息
*/
private String errMsg;
/**
* 描述
*/
private String description;
/**
* wap url
*/
private String wapUrl;
}
| 13.310345 | 49 | 0.531088 |
08a4cfd01204e68ddf700b38b2da6f0408607756 | 1,059 | package com.sample.web.admin.controller.api.error;
import com.sample.domain.exception.APIException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import com.sample.web.base.controller.api.AbstractRestController;
@RestController
@RequestMapping(path = "/api/error", produces = MediaType.APPLICATION_JSON_VALUE)
public class ErrorController extends AbstractRestController {
@Override
public boolean authorityRequired() {
return false;
}
@Override
public String getFunctionName() {
return "API_ERROR";
}
@PutMapping(value = "/{status}")
public void put(@PathVariable Integer status) {
throw new APIException(String.valueOf(status));
}
@PostMapping(value = "/{status}")
public void post(@PathVariable Integer status) {
throw new APIException(String.valueOf(status));
}
@DeleteMapping(value = "/{status}")
public void delete(@PathVariable Integer status) {
throw new APIException(String.valueOf(status));
}
}
| 27.868421 | 81 | 0.711992 |
7ac0b1bd841ea2c8c5d2072fc68197344e141c77 | 38,553 | /*
* Copyright 2013 Gunnar Kappei.
*
* 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 de.zib.museum.museumdat.impl;
/**
* A document containing one recordInfoSet(@http://museum.zib.de/museumdat) element.
*
* This is a complex type.
*/
public class RecordInfoSetDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements de.zib.museum.museumdat.RecordInfoSetDocument
{
private static final long serialVersionUID = 1L;
public RecordInfoSetDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName RECORDINFOSET$0 =
new javax.xml.namespace.QName("http://museum.zib.de/museumdat", "recordInfoSet");
/**
* Gets the "recordInfoSet" element
*/
public de.zib.museum.museumdat.RecordInfoSetDocument.RecordInfoSet getRecordInfoSet()
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordInfoSetDocument.RecordInfoSet target = null;
target = (de.zib.museum.museumdat.RecordInfoSetDocument.RecordInfoSet)get_store().find_element_user(RECORDINFOSET$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "recordInfoSet" element
*/
public void setRecordInfoSet(de.zib.museum.museumdat.RecordInfoSetDocument.RecordInfoSet recordInfoSet)
{
generatedSetterHelperImpl(recordInfoSet, RECORDINFOSET$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "recordInfoSet" element
*/
public de.zib.museum.museumdat.RecordInfoSetDocument.RecordInfoSet addNewRecordInfoSet()
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordInfoSetDocument.RecordInfoSet target = null;
target = (de.zib.museum.museumdat.RecordInfoSetDocument.RecordInfoSet)get_store().add_element_user(RECORDINFOSET$0);
return target;
}
}
/**
* An XML recordInfoSet(@http://museum.zib.de/museumdat).
*
* This is a complex type.
*/
public static class RecordInfoSetImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements de.zib.museum.museumdat.RecordInfoSetDocument.RecordInfoSet
{
private static final long serialVersionUID = 1L;
public RecordInfoSetImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName RECORDINFOID$0 =
new javax.xml.namespace.QName("http://museum.zib.de/museumdat", "recordInfoID");
private static final javax.xml.namespace.QName RECORDINFOLINK$2 =
new javax.xml.namespace.QName("http://museum.zib.de/museumdat", "recordInfoLink");
private static final javax.xml.namespace.QName RECORDRELID$4 =
new javax.xml.namespace.QName("http://museum.zib.de/museumdat", "recordRelID");
private static final javax.xml.namespace.QName RECORDMETADATALOC$6 =
new javax.xml.namespace.QName("http://museum.zib.de/museumdat", "recordMetadataLoc");
private static final javax.xml.namespace.QName RECORDMETADATADATE$8 =
new javax.xml.namespace.QName("http://museum.zib.de/museumdat", "recordMetadataDate");
private static final javax.xml.namespace.QName TYPE$10 =
new javax.xml.namespace.QName("http://museum.zib.de/museumdat", "type");
/**
* Gets a List of "recordInfoID" elements
*/
public java.util.List<de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID> getRecordInfoIDList()
{
final class RecordInfoIDList extends java.util.AbstractList<de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID>
{
@Override
public de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID get(int i)
{ return RecordInfoSetImpl.this.getRecordInfoIDArray(i); }
@Override
public de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID set(int i, de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID o)
{
de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID old = RecordInfoSetImpl.this.getRecordInfoIDArray(i);
RecordInfoSetImpl.this.setRecordInfoIDArray(i, o);
return old;
}
@Override
public void add(int i, de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID o)
{ RecordInfoSetImpl.this.insertNewRecordInfoID(i).set(o); }
@Override
public de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID remove(int i)
{
de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID old = RecordInfoSetImpl.this.getRecordInfoIDArray(i);
RecordInfoSetImpl.this.removeRecordInfoID(i);
return old;
}
@Override
public int size()
{ return RecordInfoSetImpl.this.sizeOfRecordInfoIDArray(); }
}
synchronized (monitor())
{
check_orphaned();
return new RecordInfoIDList();
}
}
/**
* Gets array of all "recordInfoID" elements
* @deprecated
*/
@Deprecated
public de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID[] getRecordInfoIDArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List<de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID> targetList = new java.util.ArrayList<de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID>();
get_store().find_all_element_users(RECORDINFOID$0, targetList);
de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID[] result = new de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID[targetList.size()];
targetList.toArray(result);
return result;
}
}
/**
* Gets ith "recordInfoID" element
*/
public de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID getRecordInfoIDArray(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID target = null;
target = (de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID)get_store().find_element_user(RECORDINFOID$0, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return target;
}
}
/**
* Returns number of "recordInfoID" element
*/
public int sizeOfRecordInfoIDArray()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(RECORDINFOID$0);
}
}
/**
* Sets array of all "recordInfoID" element WARNING: This method is not atomicaly synchronized.
*/
public void setRecordInfoIDArray(de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID[] recordInfoIDArray)
{
check_orphaned();
arraySetterHelper(recordInfoIDArray, RECORDINFOID$0);
}
/**
* Sets ith "recordInfoID" element
*/
public void setRecordInfoIDArray(int i, de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID recordInfoID)
{
generatedSetterHelperImpl(recordInfoID, RECORDINFOID$0, i, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);
}
/**
* Inserts and returns a new empty value (as xml) as the ith "recordInfoID" element
*/
public de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID insertNewRecordInfoID(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID target = null;
target = (de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID)get_store().insert_element_user(RECORDINFOID$0, i);
return target;
}
}
/**
* Appends and returns a new empty value (as xml) as the last "recordInfoID" element
*/
public de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID addNewRecordInfoID()
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID target = null;
target = (de.zib.museum.museumdat.RecordInfoIDDocument.RecordInfoID)get_store().add_element_user(RECORDINFOID$0);
return target;
}
}
/**
* Removes the ith "recordInfoID" element
*/
public void removeRecordInfoID(int i)
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(RECORDINFOID$0, i);
}
}
/**
* Gets a List of "recordInfoLink" elements
*/
public java.util.List<de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink> getRecordInfoLinkList()
{
final class RecordInfoLinkList extends java.util.AbstractList<de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink>
{
@Override
public de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink get(int i)
{ return RecordInfoSetImpl.this.getRecordInfoLinkArray(i); }
@Override
public de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink set(int i, de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink o)
{
de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink old = RecordInfoSetImpl.this.getRecordInfoLinkArray(i);
RecordInfoSetImpl.this.setRecordInfoLinkArray(i, o);
return old;
}
@Override
public void add(int i, de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink o)
{ RecordInfoSetImpl.this.insertNewRecordInfoLink(i).set(o); }
@Override
public de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink remove(int i)
{
de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink old = RecordInfoSetImpl.this.getRecordInfoLinkArray(i);
RecordInfoSetImpl.this.removeRecordInfoLink(i);
return old;
}
@Override
public int size()
{ return RecordInfoSetImpl.this.sizeOfRecordInfoLinkArray(); }
}
synchronized (monitor())
{
check_orphaned();
return new RecordInfoLinkList();
}
}
/**
* Gets array of all "recordInfoLink" elements
* @deprecated
*/
@Deprecated
public de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink[] getRecordInfoLinkArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List<de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink> targetList = new java.util.ArrayList<de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink>();
get_store().find_all_element_users(RECORDINFOLINK$2, targetList);
de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink[] result = new de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink[targetList.size()];
targetList.toArray(result);
return result;
}
}
/**
* Gets ith "recordInfoLink" element
*/
public de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink getRecordInfoLinkArray(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink target = null;
target = (de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink)get_store().find_element_user(RECORDINFOLINK$2, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return target;
}
}
/**
* Returns number of "recordInfoLink" element
*/
public int sizeOfRecordInfoLinkArray()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(RECORDINFOLINK$2);
}
}
/**
* Sets array of all "recordInfoLink" element WARNING: This method is not atomicaly synchronized.
*/
public void setRecordInfoLinkArray(de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink[] recordInfoLinkArray)
{
check_orphaned();
arraySetterHelper(recordInfoLinkArray, RECORDINFOLINK$2);
}
/**
* Sets ith "recordInfoLink" element
*/
public void setRecordInfoLinkArray(int i, de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink recordInfoLink)
{
generatedSetterHelperImpl(recordInfoLink, RECORDINFOLINK$2, i, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);
}
/**
* Inserts and returns a new empty value (as xml) as the ith "recordInfoLink" element
*/
public de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink insertNewRecordInfoLink(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink target = null;
target = (de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink)get_store().insert_element_user(RECORDINFOLINK$2, i);
return target;
}
}
/**
* Appends and returns a new empty value (as xml) as the last "recordInfoLink" element
*/
public de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink addNewRecordInfoLink()
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink target = null;
target = (de.zib.museum.museumdat.RecordInfoLinkDocument.RecordInfoLink)get_store().add_element_user(RECORDINFOLINK$2);
return target;
}
}
/**
* Removes the ith "recordInfoLink" element
*/
public void removeRecordInfoLink(int i)
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(RECORDINFOLINK$2, i);
}
}
/**
* Gets a List of "recordRelID" elements
*/
public java.util.List<de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID> getRecordRelIDList()
{
final class RecordRelIDList extends java.util.AbstractList<de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID>
{
@Override
public de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID get(int i)
{ return RecordInfoSetImpl.this.getRecordRelIDArray(i); }
@Override
public de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID set(int i, de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID o)
{
de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID old = RecordInfoSetImpl.this.getRecordRelIDArray(i);
RecordInfoSetImpl.this.setRecordRelIDArray(i, o);
return old;
}
@Override
public void add(int i, de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID o)
{ RecordInfoSetImpl.this.insertNewRecordRelID(i).set(o); }
@Override
public de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID remove(int i)
{
de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID old = RecordInfoSetImpl.this.getRecordRelIDArray(i);
RecordInfoSetImpl.this.removeRecordRelID(i);
return old;
}
@Override
public int size()
{ return RecordInfoSetImpl.this.sizeOfRecordRelIDArray(); }
}
synchronized (monitor())
{
check_orphaned();
return new RecordRelIDList();
}
}
/**
* Gets array of all "recordRelID" elements
* @deprecated
*/
@Deprecated
public de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID[] getRecordRelIDArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List<de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID> targetList = new java.util.ArrayList<de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID>();
get_store().find_all_element_users(RECORDRELID$4, targetList);
de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID[] result = new de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID[targetList.size()];
targetList.toArray(result);
return result;
}
}
/**
* Gets ith "recordRelID" element
*/
public de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID getRecordRelIDArray(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID target = null;
target = (de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID)get_store().find_element_user(RECORDRELID$4, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return target;
}
}
/**
* Returns number of "recordRelID" element
*/
public int sizeOfRecordRelIDArray()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(RECORDRELID$4);
}
}
/**
* Sets array of all "recordRelID" element WARNING: This method is not atomicaly synchronized.
*/
public void setRecordRelIDArray(de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID[] recordRelIDArray)
{
check_orphaned();
arraySetterHelper(recordRelIDArray, RECORDRELID$4);
}
/**
* Sets ith "recordRelID" element
*/
public void setRecordRelIDArray(int i, de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID recordRelID)
{
generatedSetterHelperImpl(recordRelID, RECORDRELID$4, i, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);
}
/**
* Inserts and returns a new empty value (as xml) as the ith "recordRelID" element
*/
public de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID insertNewRecordRelID(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID target = null;
target = (de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID)get_store().insert_element_user(RECORDRELID$4, i);
return target;
}
}
/**
* Appends and returns a new empty value (as xml) as the last "recordRelID" element
*/
public de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID addNewRecordRelID()
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID target = null;
target = (de.zib.museum.museumdat.RecordRelIDDocument.RecordRelID)get_store().add_element_user(RECORDRELID$4);
return target;
}
}
/**
* Removes the ith "recordRelID" element
*/
public void removeRecordRelID(int i)
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(RECORDRELID$4, i);
}
}
/**
* Gets a List of "recordMetadataLoc" elements
*/
public java.util.List<de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc> getRecordMetadataLocList()
{
final class RecordMetadataLocList extends java.util.AbstractList<de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc>
{
@Override
public de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc get(int i)
{ return RecordInfoSetImpl.this.getRecordMetadataLocArray(i); }
@Override
public de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc set(int i, de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc o)
{
de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc old = RecordInfoSetImpl.this.getRecordMetadataLocArray(i);
RecordInfoSetImpl.this.setRecordMetadataLocArray(i, o);
return old;
}
@Override
public void add(int i, de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc o)
{ RecordInfoSetImpl.this.insertNewRecordMetadataLoc(i).set(o); }
@Override
public de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc remove(int i)
{
de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc old = RecordInfoSetImpl.this.getRecordMetadataLocArray(i);
RecordInfoSetImpl.this.removeRecordMetadataLoc(i);
return old;
}
@Override
public int size()
{ return RecordInfoSetImpl.this.sizeOfRecordMetadataLocArray(); }
}
synchronized (monitor())
{
check_orphaned();
return new RecordMetadataLocList();
}
}
/**
* Gets array of all "recordMetadataLoc" elements
* @deprecated
*/
@Deprecated
public de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc[] getRecordMetadataLocArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List<de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc> targetList = new java.util.ArrayList<de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc>();
get_store().find_all_element_users(RECORDMETADATALOC$6, targetList);
de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc[] result = new de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc[targetList.size()];
targetList.toArray(result);
return result;
}
}
/**
* Gets ith "recordMetadataLoc" element
*/
public de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc getRecordMetadataLocArray(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc target = null;
target = (de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc)get_store().find_element_user(RECORDMETADATALOC$6, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return target;
}
}
/**
* Returns number of "recordMetadataLoc" element
*/
public int sizeOfRecordMetadataLocArray()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(RECORDMETADATALOC$6);
}
}
/**
* Sets array of all "recordMetadataLoc" element WARNING: This method is not atomicaly synchronized.
*/
public void setRecordMetadataLocArray(de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc[] recordMetadataLocArray)
{
check_orphaned();
arraySetterHelper(recordMetadataLocArray, RECORDMETADATALOC$6);
}
/**
* Sets ith "recordMetadataLoc" element
*/
public void setRecordMetadataLocArray(int i, de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc recordMetadataLoc)
{
generatedSetterHelperImpl(recordMetadataLoc, RECORDMETADATALOC$6, i, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);
}
/**
* Inserts and returns a new empty value (as xml) as the ith "recordMetadataLoc" element
*/
public de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc insertNewRecordMetadataLoc(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc target = null;
target = (de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc)get_store().insert_element_user(RECORDMETADATALOC$6, i);
return target;
}
}
/**
* Appends and returns a new empty value (as xml) as the last "recordMetadataLoc" element
*/
public de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc addNewRecordMetadataLoc()
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc target = null;
target = (de.zib.museum.museumdat.RecordMetadataLocDocument.RecordMetadataLoc)get_store().add_element_user(RECORDMETADATALOC$6);
return target;
}
}
/**
* Removes the ith "recordMetadataLoc" element
*/
public void removeRecordMetadataLoc(int i)
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(RECORDMETADATALOC$6, i);
}
}
/**
* Gets a List of "recordMetadataDate" elements
*/
public java.util.List<de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate> getRecordMetadataDateList()
{
final class RecordMetadataDateList extends java.util.AbstractList<de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate>
{
@Override
public de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate get(int i)
{ return RecordInfoSetImpl.this.getRecordMetadataDateArray(i); }
@Override
public de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate set(int i, de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate o)
{
de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate old = RecordInfoSetImpl.this.getRecordMetadataDateArray(i);
RecordInfoSetImpl.this.setRecordMetadataDateArray(i, o);
return old;
}
@Override
public void add(int i, de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate o)
{ RecordInfoSetImpl.this.insertNewRecordMetadataDate(i).set(o); }
@Override
public de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate remove(int i)
{
de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate old = RecordInfoSetImpl.this.getRecordMetadataDateArray(i);
RecordInfoSetImpl.this.removeRecordMetadataDate(i);
return old;
}
@Override
public int size()
{ return RecordInfoSetImpl.this.sizeOfRecordMetadataDateArray(); }
}
synchronized (monitor())
{
check_orphaned();
return new RecordMetadataDateList();
}
}
/**
* Gets array of all "recordMetadataDate" elements
* @deprecated
*/
@Deprecated
public de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate[] getRecordMetadataDateArray()
{
synchronized (monitor())
{
check_orphaned();
java.util.List<de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate> targetList = new java.util.ArrayList<de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate>();
get_store().find_all_element_users(RECORDMETADATADATE$8, targetList);
de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate[] result = new de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate[targetList.size()];
targetList.toArray(result);
return result;
}
}
/**
* Gets ith "recordMetadataDate" element
*/
public de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate getRecordMetadataDateArray(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate target = null;
target = (de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate)get_store().find_element_user(RECORDMETADATADATE$8, i);
if (target == null)
{
throw new IndexOutOfBoundsException();
}
return target;
}
}
/**
* Returns number of "recordMetadataDate" element
*/
public int sizeOfRecordMetadataDateArray()
{
synchronized (monitor())
{
check_orphaned();
return get_store().count_elements(RECORDMETADATADATE$8);
}
}
/**
* Sets array of all "recordMetadataDate" element WARNING: This method is not atomicaly synchronized.
*/
public void setRecordMetadataDateArray(de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate[] recordMetadataDateArray)
{
check_orphaned();
arraySetterHelper(recordMetadataDateArray, RECORDMETADATADATE$8);
}
/**
* Sets ith "recordMetadataDate" element
*/
public void setRecordMetadataDateArray(int i, de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate recordMetadataDate)
{
generatedSetterHelperImpl(recordMetadataDate, RECORDMETADATADATE$8, i, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);
}
/**
* Inserts and returns a new empty value (as xml) as the ith "recordMetadataDate" element
*/
public de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate insertNewRecordMetadataDate(int i)
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate target = null;
target = (de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate)get_store().insert_element_user(RECORDMETADATADATE$8, i);
return target;
}
}
/**
* Appends and returns a new empty value (as xml) as the last "recordMetadataDate" element
*/
public de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate addNewRecordMetadataDate()
{
synchronized (monitor())
{
check_orphaned();
de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate target = null;
target = (de.zib.museum.museumdat.RecordMetadataDateDocument.RecordMetadataDate)get_store().add_element_user(RECORDMETADATADATE$8);
return target;
}
}
/**
* Removes the ith "recordMetadataDate" element
*/
public void removeRecordMetadataDate(int i)
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_element(RECORDMETADATADATE$8, i);
}
}
/**
* Gets the "type" attribute
*/
public java.lang.String getType()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(TYPE$10);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "type" attribute
*/
public org.apache.xmlbeans.XmlString xgetType()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlString target = null;
target = (org.apache.xmlbeans.XmlString)get_store().find_attribute_user(TYPE$10);
return target;
}
}
/**
* True if has "type" attribute
*/
public boolean isSetType()
{
synchronized (monitor())
{
check_orphaned();
return get_store().find_attribute_user(TYPE$10) != null;
}
}
/**
* Sets the "type" attribute
*/
public void setType(java.lang.String type)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(TYPE$10);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(TYPE$10);
}
target.setStringValue(type);
}
}
/**
* Sets (as xml) the "type" attribute
*/
public void xsetType(org.apache.xmlbeans.XmlString type)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlString target = null;
target = (org.apache.xmlbeans.XmlString)get_store().find_attribute_user(TYPE$10);
if (target == null)
{
target = (org.apache.xmlbeans.XmlString)get_store().add_attribute_user(TYPE$10);
}
target.set(type);
}
}
/**
* Unsets the "type" attribute
*/
public void unsetType()
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_attribute(TYPE$10);
}
}
}
}
| 41.01383 | 212 | 0.579358 |
ee1a35c8d9b2bdfd65193c97d3f8e05841255b0c | 1,063 | package ru.greg3d.asserts;
import org.testng.SkipException;
public abstract class Assert extends org.testng.Assert {
public static void ignore(String arg0){
throw new SkipException(arg0);
}
public static void ignoreTrue(boolean condition, String arg0){
try{
org.testng.Assert.assertTrue(condition, arg0);
}catch(AssertionError e){
throw new SkipException(e.getMessage());
}
}
public static void ignoreFalse(boolean condition, String arg0){
try{
org.testng.Assert.assertFalse(condition, arg0);
}catch(AssertionError e){
throw new SkipException(e.getMessage());
}
}
public static void ignoreEquals(double actual, double expected, String arg0){
try{
org.testng.Assert.assertEquals(actual , expected, arg0);
}catch(AssertionError e){
throw new SkipException(e.getMessage());
}
}
public static void ignoreNotEquals(double actual, double expected, String arg0){
try{
org.testng.Assert.assertNotEquals(actual, expected, arg0);
}catch(AssertionError e){
throw new SkipException(e.getMessage());
}
}
}
| 25.309524 | 81 | 0.733772 |
94573ae7f235f1fb3365cfdc0252a61e172a1a1a | 8,992 | /*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.intel.mtwilson.flavor.controller;
import com.intel.mtwilson.flavor.controller.exceptions.NonexistentEntityException;
import com.intel.mtwilson.flavor.data.MwLinkFlavorHost;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.postgresql.util.PSQLException;
/**
*
* @author rksavino
*/
public class MwLinkFlavorHostJpaController implements Serializable {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MwLinkFlavorHostJpaController.class);
public MwLinkFlavorHostJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(MwLinkFlavorHost mwLinkFlavorHost) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(mwLinkFlavorHost);
em.getTransaction().commit();
} catch (RuntimeException e) {
Throwable rootCause = ExceptionUtils.getRootCause(e);
if (PSQLException.class.equals(rootCause.getClass()) && "23505".equals(((PSQLException) rootCause).getSQLState())) {
log.error("The link between flavor and host with id {} already exists", mwLinkFlavorHost.getId());
} else {
throw e;
}
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(MwLinkFlavorHost mwLinkFlavorHost) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
mwLinkFlavorHost = em.merge(mwLinkFlavorHost);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
String id = mwLinkFlavorHost.getId();
if (findMwLinkFlavorHost(id) == null) {
throw new NonexistentEntityException("The link between flavor and host with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(String id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
MwLinkFlavorHost mwLinkFlavorHost;
try {
mwLinkFlavorHost = em.getReference(MwLinkFlavorHost.class, id);
mwLinkFlavorHost.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The link between flavor and host with id " + id + " no longer exists.", enfe);
}
em.remove(mwLinkFlavorHost);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<MwLinkFlavorHost> findMwLinkFlavorHostEntities() {
return findMwLinkFlavorHostEntities(true, -1, -1);
}
public List<MwLinkFlavorHost> findMwLinkFlavorHostEntities(int maxResults, int firstResult) {
return findMwLinkFlavorHostEntities(false, maxResults, firstResult);
}
private List<MwLinkFlavorHost> findMwLinkFlavorHostEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(MwLinkFlavorHost.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public MwLinkFlavorHost findMwLinkFlavorHost(String id) {
EntityManager em = getEntityManager();
try {
return em.find(MwLinkFlavorHost.class, id);
} finally {
em.close();
}
}
/* *
* Retrieves the list of Flavor and host link entries given a flavorID
* */
public List<MwLinkFlavorHost> getMwLinkFlavorHostByFlavorId(String flavorId) {
List<MwLinkFlavorHost> mwLinkFlavorHostList = new ArrayList<MwLinkFlavorHost>();
EntityManager em = getEntityManager();
try {
Query query = em.createNamedQuery("MwLinkFlavorHost.findByFlavorId");
query.setParameter("flavorId", flavorId);
if (query.getResultList() != null && !query.getResultList().isEmpty()) {
mwLinkFlavorHostList = query.getResultList();
}
return mwLinkFlavorHostList;
}finally {
em.close();
}
}
public int getMwLinkFlavorHostCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<MwLinkFlavorHost> rt = cq.from(MwLinkFlavorHost.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
public List<MwLinkFlavorHost> findMwLinkFlavorHostByFlavorId(String flavorId) {
List<MwLinkFlavorHost> mwLinkFlavorHostList = null;
EntityManager em = getEntityManager();
try {
Query query = em.createNamedQuery("MwLinkFlavorHost.findByFlavorId");
query.setParameter("flavorId", flavorId);
if (query.getResultList() != null && !query.getResultList().isEmpty()) {
mwLinkFlavorHostList = query.getResultList();
}
return mwLinkFlavorHostList;
} finally {
em.close();
}
}
public List<MwLinkFlavorHost> findMwLinkFlavorHostByHostId(String hostId) {
List<MwLinkFlavorHost> mwLinkFlavorHostList = null;
EntityManager em = getEntityManager();
try {
Query query = em.createNamedQuery("MwLinkFlavorHost.findByHostId");
query.setParameter("hostId", hostId);
if (query.getResultList() != null && !query.getResultList().isEmpty()) {
mwLinkFlavorHostList = query.getResultList();
}
return mwLinkFlavorHostList;
} finally {
em.close();
}
}
public MwLinkFlavorHost findMwLinkFlavorHostByBothIds(String flavorId, String hostId) {
EntityManager em = getEntityManager();
try {
Query query = em.createNamedQuery("MwLinkFlavorHost.findByBothIds");
query.setParameter("flavorId", flavorId);
query.setParameter("hostId", hostId);
MwLinkFlavorHost result = (MwLinkFlavorHost) query.getSingleResult();
return result;
} catch(NoResultException e){
log.info( "NoResultException : No flavor [{}] host [{}] link exists", flavorId, hostId);
return null;
} finally {
em.close();
}
}
public List<MwLinkFlavorHost> findMwLinkFlavorHostByHostIdAndFlavorGroupId(String hostId, String flavorgroupId) {
EntityManager em = getEntityManager();
List<MwLinkFlavorHost> mwLinkFlavorHostList = null;
try {
Query query = em.createNamedQuery("MwLinkFlavorHost.findByHostIdAndFlavorgroupId");
query.setParameter("flavorgroupId", flavorgroupId);
query.setParameter("hostId", flavorgroupId);
if (query.getResultList() != null && !query.getResultList().isEmpty()) {
mwLinkFlavorHostList = query.getResultList();
}
return mwLinkFlavorHostList;
} catch(NoResultException e){
log.info( "NoResultException : No flavor and host [{}] link exists for flavorgroup [{}]", hostId, flavorgroupId);
return null;
} finally {
em.close();
}
}
}
| 38.592275 | 133 | 0.594751 |
9f335142eb5016fc0401ad68199751c55e4ee118 | 325 | package com.reactive.app.common.constants;
public class MailTemplateConstants {
private MailTemplateConstants() {
}
public static final String REGISTRATION_MAIL_TEMPLATE = "userRegistrationTemplate.ftl";
public static final String PASSWORD_MANAGEMENT_MAIL_TEMPLATE = "passwordManagementTemplate.ftl";
}
| 25 | 98 | 0.790769 |
376eb858fe883a84b2a341619048e422601c84b7 | 90 | package glide.backoffice.locators.fleets.feedbacks;
public class AddCommentFeedback {
}
| 15 | 51 | 0.822222 |
59c120eaecd5a6f9cc07faa2bff307fc16d5497c | 8,589 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.river.test.spec.jeri.util;
import net.jini.jeri.BasicInvocationDispatcher;
import net.jini.jeri.InboundRequest;
import net.jini.jeri.ServerCapabilities;
import net.jini.core.constraint.InvocationConstraints;
import net.jini.core.constraint.MethodConstraints;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.rmi.server.ExportException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.Collection;
/**
* A fake BasicInvocationDispatcher implementation that can be configured
* to throw exceptions in it's protected methods.
*/
public class FakeBasicInvocationDispatcher extends BasicInvocationDispatcher {
Logger logger;
Throwable unmarshalArgumentsException;
Throwable unmarshalMethodException;
Throwable marshalReturnException;
Throwable marshalThrowException;
Throwable createMarshalInputStreamException;
Throwable createMarshalOutputStreamException;
Throwable checkAccessException;
Throwable invokeException;
/**
* Constructs a FakeBasicInvocationDispatcher.
*/
public FakeBasicInvocationDispatcher(Collection methods,
ServerCapabilities serverCaps, MethodConstraints serverConstraints,
Class permClass, ClassLoader classLoader) throws ExportException
{
super(methods,serverCaps,serverConstraints,permClass,classLoader);
logger = Logger.getLogger("org.apache.river.qa.harness.test");
logger.entering(getClass().getName(),"constructor");
}
/***
*** The following methods configure the exceptions to throw from the
*** various protected methods. Mapping from these "set" methods to
*** the corresponding protected method should be obvious.
***
*** @param t the exception to throw
***/
public void setCheckAccessException(Throwable t) {
checkAccessException = t;
}
public void setCreateMarshalInputStreamException(Throwable t) {
createMarshalInputStreamException = t;
}
public void setCreateMarshalOutputStreamException(Throwable t) {
createMarshalOutputStreamException = t;
}
public void setInvokeException(Throwable t) {
invokeException = t;
}
public void setUnmarshalMethodException(Throwable t) {
unmarshalMethodException = t;
}
public void setUnmarshalArgumentsException(Throwable t) {
unmarshalArgumentsException = t;
}
public void setMarshalReturnException(Throwable t) {
marshalReturnException = t;
}
public void setMarshalThrowException(Throwable t) {
marshalThrowException = t;
}
/***
*** Overridden protected methods that will throw a
*** configured exception set with the corresponding
*** "set" method above. If the configured exception is null, then
*** these methods will call <code>super.<method>(...)</code>.
***
*** @throws configured exception if not null
*** @throws AssertionError if configured exception was set but
*** is not an instance of an exception thrown by the method
***/
public void checkAccess(Remote impl, Method method,
InvocationConstraints constraints, Collection context)
{
logger.entering(getClass().getName(),"checkAccess");
if (checkAccessException != null) {
throwUnchecked(checkAccessException);
throw new AssertionError();
}
super.checkAccess(impl,method,constraints,context);
}
public ObjectInputStream createMarshalInputStream(Object impl,
InboundRequest request, boolean integrity, Collection context)
throws IOException
{
logger.entering(getClass().getName(),"createMarshalInputStream");
if (createMarshalInputStreamException != null) {
throwIOE(createMarshalInputStreamException);
throw new AssertionError();
}
return super.createMarshalInputStream(impl,request,integrity,context);
}
public ObjectOutputStream createMarshalOutputStream(Object impl,
Method method, InboundRequest request, Collection context)
throws IOException
{
logger.entering(getClass().getName(),"createMarshalOutputStream");
if (createMarshalOutputStreamException != null) {
throwIOE(createMarshalOutputStreamException);
throw new AssertionError();
}
return super.createMarshalOutputStream(impl,method,request,context);
}
public Object invoke(Remote impl, Method method, Object[] args,
Collection context) throws Throwable
{
logger.entering(getClass().getName(),"invoke");
if (invokeException != null) {
throw invokeException;
}
return super.invoke(impl,method,args,context);
}
public Object[] unmarshalArguments(Remote impl, Method method,
ObjectInputStream in, Collection c)
throws IOException, ClassNotFoundException
{
logger.entering(getClass().getName(),"unmarshalArguments");
if (unmarshalArgumentsException != null) {
throwIOE(unmarshalArgumentsException);
throwCNFE(unmarshalArgumentsException);
throw new AssertionError();
}
return super.unmarshalArguments(impl,method,in,c);
}
public Method unmarshalMethod(Remote impl, ObjectInputStream in,
Collection c)
throws IOException, ClassNotFoundException, NoSuchMethodException
{
logger.entering(getClass().getName(),"unmarshalMethod");
if (unmarshalMethodException != null) {
throwIOE(unmarshalMethodException);
throwCNFE(unmarshalMethodException);
throwNSME(unmarshalMethodException);
throw new AssertionError();
}
return super.unmarshalMethod(impl,in,c);
}
public void marshalReturn(Remote impl, Method method,
Object returnValue, ObjectOutputStream out, Collection c)
throws IOException
{
logger.entering(getClass().getName(),"marshalReturn");
if (marshalReturnException != null) {
throwIOE(marshalReturnException);
throw new AssertionError();
}
super.marshalReturn(impl,method,returnValue,out,c);
}
public void marshalThrow(Remote impl, Method method,
Throwable throwable, ObjectOutputStream out, Collection c)
throws IOException
{
logger.entering(getClass().getName(),"marshalThrow");
if (marshalThrowException != null) {
throwIOE(marshalThrowException);
throw new AssertionError();
}
super.marshalThrow(impl,method,throwable,out,c);
}
public ClassLoader getClassLoader0() {
return super.getClassLoader();
}
// ********************************************** //
private void throwCNFE(Throwable t) throws ClassNotFoundException {
if (t instanceof ClassNotFoundException) {
throw (ClassNotFoundException) t;
}
throwUnchecked(t);
}
private void throwNSME(Throwable t) throws NoSuchMethodException {
if (t instanceof NoSuchMethodException) {
throw (NoSuchMethodException) t;
}
throwUnchecked(t);
}
private void throwIOE(Throwable t) throws IOException {
if (t instanceof IOException) {
throw (IOException) t;
}
throwUnchecked(t);
}
private void throwUnchecked(Throwable t) throws RuntimeException, Error {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
}
}
}
| 36.548936 | 78 | 0.684597 |
a31656d075532acf809d07c027e1cbeba64bb61b | 9,796 | /*
* Copyright (c) 1998, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.jdi;
import java.util.ArrayList;
import java.util.List;
public class JNITypeParser {
static final char SIGNATURE_ENDCLASS = ';';
static final char SIGNATURE_FUNC = '(';
static final char SIGNATURE_ENDFUNC = ')';
private String signature;
private List<String> typeNameList;
private List<String> signatureList;
private int currentIndex;
JNITypeParser(String signature) {
this.signature = signature;
}
static String typeNameToSignature(String typeName) {
StringBuilder sb = new StringBuilder();
int firstIndex = typeName.indexOf('[');
int index = firstIndex;
while (index != -1) {
sb.append('[');
index = typeName.indexOf('[', index + 1);
}
if (firstIndex != -1) {
typeName = typeName.substring(0, firstIndex);
}
if (typeName.equals("boolean")) {
sb.append('Z');
} else if (typeName.equals("byte")) {
sb.append('B');
} else if (typeName.equals("char")) {
sb.append('C');
} else if (typeName.equals("short")) {
sb.append('S');
} else if (typeName.equals("int")) {
sb.append('I');
} else if (typeName.equals("long")) {
sb.append('J');
} else if (typeName.equals("float")) {
sb.append('F');
} else if (typeName.equals("double")) {
sb.append('D');
} else {
sb.append('L');
index = typeName.indexOf("/"); // check if it's a hidden class
if (index < 0) {
sb.append(typeName.replace('.', '/'));
} else {
sb.append(typeName.substring(0, index).replace('.', '/'));
sb.append(".");
sb.append(typeName.substring(index + 1));
}
sb.append(';');
}
return sb.toString();
}
String typeName() {
return typeNameList().get(typeNameList().size()-1);
}
List<String> argumentTypeNames() {
return typeNameList().subList(0, typeNameList().size() - 1);
}
String signature() {
return signatureList().get(signatureList().size()-1);
}
List<String> argumentSignatures() {
return signatureList().subList(0, signatureList().size() - 1);
}
int dimensionCount() {
int count = 0;
String signature = signature();
while (signature.charAt(count) == '[') {
count++;
}
return count;
}
byte jdwpTag() {
return (byte) signature().charAt(0);
}
String componentSignature(int level) {
assert level <= dimensionCount();
return signature().substring(level);
}
String componentSignature() {
assert isArray();
return componentSignature(1);
}
boolean isArray() {
return jdwpTag() == JDWP.Tag.ARRAY;
}
boolean isVoid() {
return jdwpTag() == JDWP.Tag.VOID;
}
boolean isBoolean() {
return jdwpTag() == JDWP.Tag.BOOLEAN;
}
boolean isReference() {
byte tag = jdwpTag();
return tag == JDWP.Tag.ARRAY ||
tag == JDWP.Tag.OBJECT;
}
boolean isPrimitive() {
switch (jdwpTag()) {
case (JDWP.Tag.BOOLEAN):
case (JDWP.Tag.BYTE):
case (JDWP.Tag.CHAR):
case (JDWP.Tag.SHORT):
case (JDWP.Tag.INT):
case (JDWP.Tag.LONG):
case (JDWP.Tag.FLOAT):
case (JDWP.Tag.DOUBLE):
return true;
}
return false;
}
static String convertSignatureToClassname(String classSignature) {
assert classSignature.startsWith("L") && classSignature.endsWith(";");
// trim leading "L" and trailing ";"
String name = classSignature.substring(1, classSignature.length() - 1);
int index = name.indexOf("."); // check if it is a hidden class
if (index < 0) {
return name.replace('/', '.');
} else {
// map the type descriptor from: "L" + N + "." + <suffix> + ";"
// to class name: N.replace('/', '.') + "/" + <suffix>
return name.substring(0, index).replace('/', '.')
+ "/" + name.substring(index + 1);
}
}
private synchronized List<String> signatureList() {
if (signatureList == null) {
signatureList = new ArrayList<>(10);
String elem;
currentIndex = 0;
while(currentIndex < signature.length()) {
elem = nextSignature();
signatureList.add(elem);
}
if (signatureList.size() == 0) {
throw new IllegalArgumentException("Invalid JNI signature '" +
signature + "'");
}
}
return signatureList;
}
private synchronized List<String> typeNameList() {
if (typeNameList == null) {
typeNameList = new ArrayList<>(10);
String elem;
currentIndex = 0;
while(currentIndex < signature.length()) {
elem = nextTypeName();
typeNameList.add(elem);
}
if (typeNameList.size() == 0) {
throw new IllegalArgumentException("Invalid JNI signature '" +
signature + "'");
}
}
return typeNameList;
}
private String nextSignature() {
char key = signature.charAt(currentIndex++);
switch(key) {
case (JDWP.Tag.ARRAY):
return key + nextSignature();
case (JDWP.Tag.OBJECT):
int endClass = signature.indexOf(SIGNATURE_ENDCLASS,
currentIndex);
String retVal = signature.substring(currentIndex - 1,
endClass + 1);
currentIndex = endClass + 1;
return retVal;
case (JDWP.Tag.VOID):
case (JDWP.Tag.BOOLEAN):
case (JDWP.Tag.BYTE):
case (JDWP.Tag.CHAR):
case (JDWP.Tag.SHORT):
case (JDWP.Tag.INT):
case (JDWP.Tag.LONG):
case (JDWP.Tag.FLOAT):
case (JDWP.Tag.DOUBLE):
return String.valueOf(key);
case SIGNATURE_ENDFUNC:
case SIGNATURE_FUNC:
return nextSignature();
default:
throw new IllegalArgumentException(
"Invalid JNI signature character '" + key + "'");
}
}
private String nextTypeName() {
char key = signature.charAt(currentIndex++);
switch(key) {
case (JDWP.Tag.ARRAY):
return nextTypeName() + "[]";
case (JDWP.Tag.BYTE):
return "byte";
case (JDWP.Tag.CHAR):
return "char";
case (JDWP.Tag.OBJECT):
int endClass = signature.indexOf(SIGNATURE_ENDCLASS,
currentIndex);
String retVal = signature.substring(currentIndex,
endClass);
int index = retVal.indexOf(".");
if (index < 0) {
retVal = retVal.replace('/', '.');
} else {
// hidden class
retVal = retVal.substring(0, index).replace('/', '.')
+ "/" + retVal.substring(index + 1);
}
currentIndex = endClass + 1;
return retVal;
case (JDWP.Tag.FLOAT):
return "float";
case (JDWP.Tag.DOUBLE):
return "double";
case (JDWP.Tag.INT):
return "int";
case (JDWP.Tag.LONG):
return "long";
case (JDWP.Tag.SHORT):
return "short";
case (JDWP.Tag.VOID):
return "void";
case (JDWP.Tag.BOOLEAN):
return "boolean";
case SIGNATURE_ENDFUNC:
case SIGNATURE_FUNC:
return nextTypeName();
default:
throw new IllegalArgumentException(
"Invalid JNI signature character '" + key + "'");
}
}
}
| 31.197452 | 79 | 0.513475 |
9787af80d83e92ee07ccfe7553079f5d6d62e4e7 | 512 | package io.sphere.sdk.client;
import io.sphere.sdk.models.SphereException;
import java.util.List;
/**
* Exception thrown by {@link DeprecationExceptionSphereClientDecorator} in case a deprecated feature of the commercetools platform is used.
*/
public class SphereDeprecationException extends SphereException {
static final long serialVersionUID = 0L;
public SphereDeprecationException(final List<String> notices) {
notices.forEach(note -> addNote("deprecation warning: " + note));
}
}
| 30.117647 | 140 | 0.763672 |
9344ebfd6917b53bcd6bbeeaa329c3da847be211 | 4,396 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.inlong.manager.dao.entity;
/**
* ClusterSet
*/
public class ClusterSet {
private String setName;
private String cnName;
private String description;
private String middlewareType;
private String inCharges;
private String followers;
private Integer status;
private Integer isDeleted;
private String creator;
private String modifier;
/**
* get setName
*
* @return the setName
*/
public String getSetName() {
return setName;
}
/**
* set setName
*
* @param setName the setName to set
*/
public void setSetName(String setName) {
this.setName = setName;
}
/**
* get cnName
*
* @return the cnName
*/
public String getCnName() {
return cnName;
}
/**
* set cnName
*
* @param cnName the cnName to set
*/
public void setCnName(String cnName) {
this.cnName = cnName;
}
/**
* get description
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* set description
*
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* get middlewareType
*
* @return the middlewareType
*/
public String getMiddlewareType() {
return middlewareType;
}
/**
* set middlewareType
*
* @param middlewareType the middlewareType to set
*/
public void setMiddlewareType(String middlewareType) {
this.middlewareType = middlewareType;
}
/**
* get inCharges
*
* @return the inCharges
*/
public String getInCharges() {
return inCharges;
}
/**
* set inCharges
*
* @param inCharges the inCharges to set
*/
public void setInCharges(String inCharges) {
this.inCharges = inCharges;
}
/**
* get followers
*
* @return the followers
*/
public String getFollowers() {
return followers;
}
/**
* set followers
*
* @param followers the followers to set
*/
public void setFollowers(String followers) {
this.followers = followers;
}
/**
* get status
*
* @return the status
*/
public Integer getStatus() {
return status;
}
/**
* set status
*
* @param status the status to set
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
* get isDeleted
*
* @return the isDeleted
*/
public Integer getIsDeleted() {
return isDeleted;
}
/**
* set isDeleted
*
* @param isDeleted the isDeleted to set
*/
public void setIsDeleted(Integer isDeleted) {
this.isDeleted = isDeleted;
}
/**
* get creator
*
* @return the creator
*/
public String getCreator() {
return creator;
}
/**
* set creator
*
* @param creator the creator to set
*/
public void setCreator(String creator) {
this.creator = creator;
}
/**
* get modifier
*
* @return the modifier
*/
public String getModifier() {
return modifier;
}
/**
* set modifier
*
* @param modifier the modifier to set
*/
public void setModifier(String modifier) {
this.modifier = modifier;
}
}
| 20.351852 | 75 | 0.583258 |
536dd5d5462c16c801627c108b93c49e22a57b6d | 4,055 | package com.ywh.LoRaWANServer.temp.domain;
import java.lang.reflect.Field;
import java.util.Arrays;
public class InfoLoraModEndForm implements UpInfoForm {
private String time;
private float tmms;
private double tmst;
private float freq;
private int chan;
private int rfch;
private int stat;
private String modu;
private String datr_lora;
private String codr;
private int rssi;
private int lsnr;
private int size;
private byte[] data = null;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public float getTmms() {
return tmms;
}
public void setTmms(float tmms) {
this.tmms = tmms;
}
public void setTmst(double tmst) {
this.tmst = tmst;
}
public double getTmst() {
return tmst;
}
public void setTmst(int tmst) {
this.tmst = tmst;
}
public float getFreq() {
return freq;
}
public void setFreq(float freq) {
this.freq = freq;
}
public int getChan() {
return chan;
}
public void setChan(int chan) {
this.chan = chan;
}
public int getRfch() {
return rfch;
}
public void setRfch(int rfch) {
this.rfch = rfch;
}
public int getStat() {
return stat;
}
public void setStat(int stat) {
this.stat = stat;
}
public String getModu() {
return modu;
}
public void setModu(String modu) {
this.modu = modu;
}
public String getDatr_lora() {
return datr_lora;
}
public void setDatr_lora(String datr_lora) {
this.datr_lora = datr_lora;
}
public String getCodr() {
return codr;
}
public void setCodr(String codr) {
this.codr = codr;
}
public int getRssi() {
return rssi;
}
public void setRssi(int rssi) {
this.rssi = rssi;
}
public int getLsnr() {
return lsnr;
}
public void setLsnr(int lsnr) {
this.lsnr = lsnr;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public void setData(byte[] data) {
this.data = data;
}
@Override
public byte[] getData() {
return this.data;
}
@Override
public void saveData() {
// TODO Auto-generated method stub
System.out.println("Lora");
}
@Override
public String getSysInfo() {
String sysInfo = "{";
try {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field.get(this) != null && !"".equals(field.get(this).toString()) && (!field.getName().equals("data"))) {
sysInfo = sysInfo + "\"" + field.getName() + "\":\"" + field.get(this) + "\",";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sysInfo.substring(0, sysInfo.length() - 1) + "}";
}
@Override
public String toString() {
return "InfoLoraModEndForm [time=" + time + ", tmms=" + tmms + ", tmst=" + tmst + ", freq="
+ freq + ", chan=" + chan + ", rfch=" + rfch + ", stat=" + stat + ", modu=" + modu
+ ", datr_lora=" + datr_lora + ", codr=" + codr + ", rssi=" + rssi + ", lsnr=" + lsnr
+ ", size=" + size + ", data=" + Arrays.toString(data) + "]";
}
public static void main(String[] args) {
InfoLoraModEndForm infoLoraModEndForm = new InfoLoraModEndForm();
infoLoraModEndForm.chan = 0;
infoLoraModEndForm.codr = "31";
byte[] bs = {0x00, 0x01};
infoLoraModEndForm.data = bs;
infoLoraModEndForm.datr_lora = "31";
infoLoraModEndForm.lsnr = 31231;
infoLoraModEndForm.modu = "lora";
System.out.println(infoLoraModEndForm.getSysInfo());
}
} | 21.684492 | 125 | 0.54254 |
6d005e0316ccda070770fb69b617380fce546c0f | 683 | package net.roxeez.advancement.trigger;
import org.bukkit.Material;
import org.junit.jupiter.api.DisplayName;
@DisplayName("EnterBlocck tests")
public class EnterBlockTest extends TriggerTest<EnterBlock> {
@Override
protected EnterBlock getObject() {
EnterBlock object = new EnterBlock();
object.setBlock(Material.ROSE_BUSH);
object.setState("half", "lower");
return object;
}
@Override
protected String getJson() {
return "{\"block\":\"minecraft:rose_bush\",\"state\":{\"half\":\"lower\"}}";
}
@Override
protected TriggerWrapper<EnterBlock> getTrigger() {
return TriggerType.ENTER_BLOCK;
}
}
| 24.392857 | 84 | 0.666179 |
5798028ea9f3bca42d1d8f5c38ac688e5b052d29 | 7,793 | package org.cocos2d.tests;
import org.cocos2d.actions.UpdateCallback;
import org.cocos2d.actions.base.CCAction;
import org.cocos2d.actions.base.CCRepeatForever;
import org.cocos2d.actions.interval.CCIntervalAction;
import org.cocos2d.actions.interval.CCMoveBy;
import org.cocos2d.actions.interval.CCRotateBy;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.menus.CCMenu;
import org.cocos2d.menus.CCMenuItemImage;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCMotionStreak;
import org.cocos2d.nodes.CCNode;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.opengl.CCGLSurfaceView;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor4B;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
public class MotionStreakTest extends Activity {
// private static final String LOG_TAG = CocosNodeTest.class.getSimpleName();
private CCGLSurfaceView mGLSurfaceView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mGLSurfaceView = new CCGLSurfaceView(this);
setContentView(mGLSurfaceView);
}
@Override
public void onStart() {
super.onStart();
// attach the OpenGL view to a window
CCDirector.sharedDirector().attachInView(mGLSurfaceView);
// set landscape mode
CCDirector.sharedDirector().setLandscape(false);
// show FPS
CCDirector.sharedDirector().setDisplayFPS(true);
// frames per second
CCDirector.sharedDirector().setAnimationInterval(1.0f / 60);
CCScene scene = CCScene.node();
scene.addChild(nextAction());
// Make the Scene active
CCDirector.sharedDirector().runWithScene(scene);
}
@Override
public void onPause() {
super.onPause();
CCDirector.sharedDirector().onPause();
}
@Override
public void onResume() {
super.onResume();
CCDirector.sharedDirector().onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
CCDirector.sharedDirector().end();
// CCTextureCache.sharedTextureCache().removeAllTextures();
}
public static final int kTagLabel = 1;
public static final int kTagSprite1 = 2;
public static final int kTagSprite2 = 3;
static int sceneIdx = -1;
static Class<?> transitions[] = {
Test1.class,
Test2.class,
};
static CCLayer nextAction() {
sceneIdx++;
sceneIdx = sceneIdx % transitions.length;
return restartAction();
}
static CCLayer backAction() {
sceneIdx--;
int total = transitions.length;
if (sceneIdx < 0)
sceneIdx += total;
return restartAction();
}
static CCLayer restartAction() {
try {
Class<?> c = transitions[sceneIdx];
return (CCLayer) c.newInstance();
} catch (Exception e) {
return null;
}
}
static class MotionStreakTestLayer extends CCLayer {
public MotionStreakTestLayer() {
CGSize s = CCDirector.sharedDirector().winSize();
CCLabel label = CCLabel.makeLabel(title(), "DroidSans", 18);
addChild(label, kTagLabel);
label.setPosition(CGPoint.make(s.width / 2, s.height / 2 - 50));
CCMenuItemImage item1 = CCMenuItemImage.item("b1.png", "b2.png", this, "backCallback");
CCMenuItemImage item2 = CCMenuItemImage.item("r1.png", "r2.png", this, "restartCallback");
CCMenuItemImage item3 = CCMenuItemImage.item("f1.png", "f2.png", this, "nextCallback");
CCMenu menu = CCMenu.menu(item1, item2, item3);
menu.setPosition(0, 0);
item1.setPosition(s.width / 2 - 100, 30);
item2.setPosition(s.width / 2, 30);
item3.setPosition(s.width / 2 + 100, 30);
addChild(menu, 1);
}
public void restartCallback(Object sender) {
CCScene s = CCScene.node();
s.addChild(restartAction());
CCDirector.sharedDirector().replaceScene(s);
}
public void nextCallback(Object sender) {
CCScene s = CCScene.node();
s.addChild(nextAction());
CCDirector.sharedDirector().replaceScene(s);
}
public void backCallback(Object sender) {
CCScene s = CCScene.node();
s.addChild(backAction());
CCDirector.sharedDirector().replaceScene(s);
}
public String title() {
return "No Title";
}
}
static class Test1 extends MotionStreakTestLayer {
CCNode root;
CCNode target;
CCMotionStreak streak;
public Test1() {
super();
}
public void onEnter() {
super.onEnter();
CGSize s = CCDirector.sharedDirector().winSize();
// the root object just rotates around
root = CCSprite.sprite("r1.png");
addChild(root, 1);
root.setPosition(s.width / 2, s.height / 2);
// the target object is offset from root, and the streak is moved to follow it
target = CCSprite.sprite("r1.png");
root.addChild(target);
target.setPosition(100, 0);
// create the streak object and add it to the scene
streak = new CCMotionStreak(2, 3, "streak.png", 32, 32, new ccColor4B(0, 255, 0, 255));
addChild(streak);
// schedule an update on each frame so we can syncronize the streak with the target
schedule(new UpdateCallback() {
public void update(float d) {
onUpdate(d);
}
});
CCIntervalAction a1 = CCRotateBy.action(2, 360);
CCAction action1 = CCRepeatForever.action(a1);
CCIntervalAction motion = CCMoveBy.action(2, CGPoint.make(100, 0));
root.runAction(CCRepeatForever.action(CCSequence.actions(motion, motion.reverse())));
root.runAction(action1);
}
public void onUpdate(float delta) {
CGPoint p = target.convertToWorldSpace(0, 0);
streak.setPosition(p);
}
public String title() {
return "MotionStreak test 1";
}
}
static class Test2 extends MotionStreakTestLayer {
CCNode root;
CCNode target;
CCMotionStreak streak;
public Test2() {
super();
}
@Override
public void onEnter() {
super.onEnter();
setIsTouchEnabled(true);
CGSize s = CCDirector.sharedDirector().winSize();
// create the streak object and add it to the scene
streak = new CCMotionStreak(3, 3, "streak.png", 64, 32, new ccColor4B(255,255,255,255));
addChild(streak);
streak.setPosition(s.width/2, s.height/2);
}
public boolean ccTouchesMoved(MotionEvent e) {
CGPoint touchLocation = CGPoint.ccp(e.getX(), e.getY());
touchLocation = CCDirector.sharedDirector().convertToGL(touchLocation);
streak.setPosition(touchLocation);
return true;
}
public String title() {
return "MotionStreak(touch and move)";
}
}
}
| 29.631179 | 102 | 0.615424 |
f5a2f71bdf9352a86abd524cef94709e6bc2cc33 | 16,304 | package net.minecraft.entity.passive.horse;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.CarpetBlock;
import net.minecraft.entity.AgeableEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.ILivingEntityData;
import net.minecraft.entity.IRangedAttackMob;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.SpawnReason;
import net.minecraft.entity.ai.goal.BreedGoal;
import net.minecraft.entity.ai.goal.FollowParentGoal;
import net.minecraft.entity.ai.goal.LlamaFollowCaravanGoal;
import net.minecraft.entity.ai.goal.LookAtGoal;
import net.minecraft.entity.ai.goal.LookRandomlyGoal;
import net.minecraft.entity.ai.goal.NearestAttackableTargetGoal;
import net.minecraft.entity.ai.goal.PanicGoal;
import net.minecraft.entity.ai.goal.RangedAttackGoal;
import net.minecraft.entity.ai.goal.RunAroundLikeCrazyGoal;
import net.minecraft.entity.ai.goal.SwimGoal;
import net.minecraft.entity.ai.goal.WaterAvoidingRandomWalkingGoal;
import net.minecraft.entity.passive.AnimalEntity;
import net.minecraft.entity.passive.WolfEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.LlamaSpitEntity;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.DyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.tags.ItemTags;
import net.minecraft.util.DamageSource;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.IWorld;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public class LlamaEntity extends AbstractChestedHorseEntity implements IRangedAttackMob {
private static final DataParameter<Integer> DATA_STRENGTH_ID = EntityDataManager.createKey(LlamaEntity.class, DataSerializers.VARINT);
private static final DataParameter<Integer> DATA_COLOR_ID = EntityDataManager.createKey(LlamaEntity.class, DataSerializers.VARINT);
private static final DataParameter<Integer> DATA_VARIANT_ID = EntityDataManager.createKey(LlamaEntity.class, DataSerializers.VARINT);
private boolean didSpit;
@Nullable
private LlamaEntity caravanHead;
@Nullable
private LlamaEntity caravanTail;
public LlamaEntity(EntityType<? extends LlamaEntity> type, World worldIn) {
super(type, worldIn);
}
@OnlyIn(Dist.CLIENT)
public boolean isTraderLlama() {
return false;
}
private void setStrength(int strengthIn) {
this.dataManager.set(DATA_STRENGTH_ID, Math.max(1, Math.min(5, strengthIn)));
}
private void setRandomStrength() {
int i = this.rand.nextFloat() < 0.04F ? 5 : 3;
this.setStrength(1 + this.rand.nextInt(i));
}
public int getStrength() {
return this.dataManager.get(DATA_STRENGTH_ID);
}
public void writeAdditional(CompoundNBT compound) {
super.writeAdditional(compound);
compound.putInt("Variant", this.getVariant());
compound.putInt("Strength", this.getStrength());
if (!this.horseChest.getStackInSlot(1).isEmpty()) {
compound.put("DecorItem", this.horseChest.getStackInSlot(1).write(new CompoundNBT()));
}
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readAdditional(CompoundNBT compound) {
this.setStrength(compound.getInt("Strength"));
super.readAdditional(compound);
this.setVariant(compound.getInt("Variant"));
if (compound.contains("DecorItem", 10)) {
this.horseChest.setInventorySlotContents(1, ItemStack.read(compound.getCompound("DecorItem")));
}
this.updateHorseSlots();
}
protected void registerGoals() {
this.goalSelector.addGoal(0, new SwimGoal(this));
this.goalSelector.addGoal(1, new RunAroundLikeCrazyGoal(this, 1.2D));
this.goalSelector.addGoal(2, new LlamaFollowCaravanGoal(this, (double)2.1F));
this.goalSelector.addGoal(3, new RangedAttackGoal(this, 1.25D, 40, 20.0F));
this.goalSelector.addGoal(3, new PanicGoal(this, 1.2D));
this.goalSelector.addGoal(4, new BreedGoal(this, 1.0D));
this.goalSelector.addGoal(5, new FollowParentGoal(this, 1.0D));
this.goalSelector.addGoal(6, new WaterAvoidingRandomWalkingGoal(this, 0.7D));
this.goalSelector.addGoal(7, new LookAtGoal(this, PlayerEntity.class, 6.0F));
this.goalSelector.addGoal(8, new LookRandomlyGoal(this));
this.targetSelector.addGoal(1, new LlamaEntity.HurtByTargetGoal(this));
this.targetSelector.addGoal(2, new LlamaEntity.DefendTargetGoal(this));
}
protected void registerAttributes() {
super.registerAttributes();
this.getAttribute(SharedMonsterAttributes.FOLLOW_RANGE).setBaseValue(40.0D);
}
protected void registerData() {
super.registerData();
this.dataManager.register(DATA_STRENGTH_ID, 0);
this.dataManager.register(DATA_COLOR_ID, -1);
this.dataManager.register(DATA_VARIANT_ID, 0);
}
public int getVariant() {
return MathHelper.clamp(this.dataManager.get(DATA_VARIANT_ID), 0, 3);
}
public void setVariant(int variantIn) {
this.dataManager.set(DATA_VARIANT_ID, variantIn);
}
protected int getInventorySize() {
return this.hasChest() ? 2 + 3 * this.getInventoryColumns() : super.getInventorySize();
}
public void updatePassenger(Entity passenger) {
if (this.isPassenger(passenger)) {
float f = MathHelper.cos(this.renderYawOffset * ((float)Math.PI / 180F));
float f1 = MathHelper.sin(this.renderYawOffset * ((float)Math.PI / 180F));
float f2 = 0.3F;
passenger.setPosition(this.getPosX() + (double)(0.3F * f1), this.getPosY() + this.getMountedYOffset() + passenger.getYOffset(), this.getPosZ() - (double)(0.3F * f));
}
}
/**
* Returns the Y offset from the entity's position for any entity riding this one.
*/
public double getMountedYOffset() {
return (double)this.getHeight() * 0.67D;
}
/**
* returns true if all the conditions for steering the entity are met. For pigs, this is true if it is being ridden
* by a player and the player is holding a carrot-on-a-stick
*/
public boolean canBeSteered() {
return false;
}
protected boolean handleEating(PlayerEntity player, ItemStack stack) {
int i = 0;
int j = 0;
float f = 0.0F;
boolean flag = false;
Item item = stack.getItem();
if (item == Items.WHEAT) {
i = 10;
j = 3;
f = 2.0F;
} else if (item == Blocks.HAY_BLOCK.asItem()) {
i = 90;
j = 6;
f = 10.0F;
if (this.isTame() && this.getGrowingAge() == 0 && this.canBreed()) {
flag = true;
this.setInLove(player);
}
}
if (this.getHealth() < this.getMaxHealth() && f > 0.0F) {
this.heal(f);
flag = true;
}
if (this.isChild() && i > 0) {
this.world.addParticle(ParticleTypes.HAPPY_VILLAGER, this.getPosXRandom(1.0D), this.getPosYRandom() + 0.5D, this.getPosZRandom(1.0D), 0.0D, 0.0D, 0.0D);
if (!this.world.isRemote) {
this.addGrowth(i);
}
flag = true;
}
if (j > 0 && (flag || !this.isTame()) && this.getTemper() < this.getMaxTemper()) {
flag = true;
if (!this.world.isRemote) {
this.increaseTemper(j);
}
}
if (flag && !this.isSilent()) {
this.world.playSound((PlayerEntity)null, this.getPosX(), this.getPosY(), this.getPosZ(), SoundEvents.ENTITY_LLAMA_EAT, this.getSoundCategory(), 1.0F, 1.0F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F);
}
return flag;
}
/**
* Dead and sleeping entities cannot move
*/
protected boolean isMovementBlocked() {
return this.getHealth() <= 0.0F || this.isEatingHaystack();
}
@Nullable
public ILivingEntityData onInitialSpawn(IWorld worldIn, DifficultyInstance difficultyIn, SpawnReason reason, @Nullable ILivingEntityData spawnDataIn, @Nullable CompoundNBT dataTag) {
this.setRandomStrength();
int i;
if (spawnDataIn instanceof LlamaEntity.LlamaData) {
i = ((LlamaEntity.LlamaData)spawnDataIn).variant;
} else {
i = this.rand.nextInt(4);
spawnDataIn = new LlamaEntity.LlamaData(i);
}
this.setVariant(i);
return super.onInitialSpawn(worldIn, difficultyIn, reason, spawnDataIn, dataTag);
}
protected SoundEvent getAngrySound() {
return SoundEvents.ENTITY_LLAMA_ANGRY;
}
protected SoundEvent getAmbientSound() {
return SoundEvents.ENTITY_LLAMA_AMBIENT;
}
protected SoundEvent getHurtSound(DamageSource damageSourceIn) {
return SoundEvents.ENTITY_LLAMA_HURT;
}
protected SoundEvent getDeathSound() {
return SoundEvents.ENTITY_LLAMA_DEATH;
}
protected void playStepSound(BlockPos pos, BlockState blockIn) {
this.playSound(SoundEvents.ENTITY_LLAMA_STEP, 0.15F, 1.0F);
}
protected void playChestEquipSound() {
this.playSound(SoundEvents.ENTITY_LLAMA_CHEST, 1.0F, (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F);
}
public void makeMad() {
SoundEvent soundevent = this.getAngrySound();
if (soundevent != null) {
this.playSound(soundevent, this.getSoundVolume(), this.getSoundPitch());
}
}
public int getInventoryColumns() {
return this.getStrength();
}
public boolean wearsArmor() {
return true;
}
public boolean isArmor(ItemStack stack) {
Item item = stack.getItem();
return ItemTags.CARPETS.contains(item);
}
public boolean canBeSaddled() {
return false;
}
/**
* Called by InventoryBasic.onInventoryChanged() on a array that is never filled.
*/
public void onInventoryChanged(IInventory invBasic) {
DyeColor dyecolor = this.getColor();
super.onInventoryChanged(invBasic);
DyeColor dyecolor1 = this.getColor();
if (this.ticksExisted > 20 && dyecolor1 != null && dyecolor1 != dyecolor) {
this.playSound(SoundEvents.ENTITY_LLAMA_SWAG, 0.5F, 1.0F);
}
}
/**
* Updates the items in the saddle and armor slots of the horse's inventory.
*/
protected void updateHorseSlots() {
if (!this.world.isRemote) {
super.updateHorseSlots();
this.setColor(getCarpetColor(this.horseChest.getStackInSlot(1)));
}
}
private void setColor(@Nullable DyeColor color) {
this.dataManager.set(DATA_COLOR_ID, color == null ? -1 : color.getId());
}
@Nullable
private static DyeColor getCarpetColor(ItemStack p_195403_0_) {
Block block = Block.getBlockFromItem(p_195403_0_.getItem());
return block instanceof CarpetBlock ? ((CarpetBlock)block).getColor() : null;
}
@Nullable
public DyeColor getColor() {
int i = this.dataManager.get(DATA_COLOR_ID);
return i == -1 ? null : DyeColor.byId(i);
}
public int getMaxTemper() {
return 30;
}
/**
* Returns true if the mob is currently able to mate with the specified mob.
*/
public boolean canMateWith(AnimalEntity otherAnimal) {
return otherAnimal != this && otherAnimal instanceof LlamaEntity && this.canMate() && ((LlamaEntity)otherAnimal).canMate();
}
public LlamaEntity createChild(AgeableEntity ageable) {
LlamaEntity llamaentity = this.createChild();
this.setOffspringAttributes(ageable, llamaentity);
LlamaEntity llamaentity1 = (LlamaEntity)ageable;
int i = this.rand.nextInt(Math.max(this.getStrength(), llamaentity1.getStrength())) + 1;
if (this.rand.nextFloat() < 0.03F) {
++i;
}
llamaentity.setStrength(i);
llamaentity.setVariant(this.rand.nextBoolean() ? this.getVariant() : llamaentity1.getVariant());
return llamaentity;
}
protected LlamaEntity createChild() {
return EntityType.LLAMA.create(this.world);
}
private void spit(LivingEntity target) {
LlamaSpitEntity llamaspitentity = new LlamaSpitEntity(this.world, this);
double d0 = target.getPosX() - this.getPosX();
double d1 = target.getPosYHeight(0.3333333333333333D) - llamaspitentity.getPosY();
double d2 = target.getPosZ() - this.getPosZ();
float f = MathHelper.sqrt(d0 * d0 + d2 * d2) * 0.2F;
llamaspitentity.shoot(d0, d1 + (double)f, d2, 1.5F, 10.0F);
this.world.playSound((PlayerEntity)null, this.getPosX(), this.getPosY(), this.getPosZ(), SoundEvents.ENTITY_LLAMA_SPIT, this.getSoundCategory(), 1.0F, 1.0F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F);
this.world.addEntity(llamaspitentity);
this.didSpit = true;
}
private void setDidSpit(boolean didSpitIn) {
this.didSpit = didSpitIn;
}
public boolean onLivingFall(float distance, float damageMultiplier) {
int i = this.calculateFallDamage(distance, damageMultiplier);
if (i <= 0) {
return false;
} else {
if (distance >= 6.0F) {
this.attackEntityFrom(DamageSource.FALL, (float)i);
if (this.isBeingRidden()) {
for(Entity entity : this.getRecursivePassengers()) {
entity.attackEntityFrom(DamageSource.FALL, (float)i);
}
}
}
this.playFallSound();
return true;
}
}
public void leaveCaravan() {
if (this.caravanHead != null) {
this.caravanHead.caravanTail = null;
}
this.caravanHead = null;
}
public void joinCaravan(LlamaEntity caravanHeadIn) {
this.caravanHead = caravanHeadIn;
this.caravanHead.caravanTail = this;
}
public boolean hasCaravanTrail() {
return this.caravanTail != null;
}
public boolean inCaravan() {
return this.caravanHead != null;
}
@Nullable
public LlamaEntity getCaravanHead() {
return this.caravanHead;
}
protected double followLeashSpeed() {
return 2.0D;
}
protected void followMother() {
if (!this.inCaravan() && this.isChild()) {
super.followMother();
}
}
public boolean canEatGrass() {
return false;
}
/**
* Attack the specified entity using a ranged attack.
*/
public void attackEntityWithRangedAttack(LivingEntity target, float distanceFactor) {
this.spit(target);
}
static class DefendTargetGoal extends NearestAttackableTargetGoal<WolfEntity> {
public DefendTargetGoal(LlamaEntity llama) {
super(llama, WolfEntity.class, 16, false, true, (p_220789_0_) -> {
return !((WolfEntity)p_220789_0_).isTamed();
});
}
protected double getTargetDistance() {
return super.getTargetDistance() * 0.25D;
}
}
static class HurtByTargetGoal extends net.minecraft.entity.ai.goal.HurtByTargetGoal {
public HurtByTargetGoal(LlamaEntity llama) {
super(llama);
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
public boolean shouldContinueExecuting() {
if (this.goalOwner instanceof LlamaEntity) {
LlamaEntity llamaentity = (LlamaEntity)this.goalOwner;
if (llamaentity.didSpit) {
llamaentity.setDidSpit(false);
return false;
}
}
return super.shouldContinueExecuting();
}
}
static class LlamaData extends AgeableEntity.AgeableData {
public final int variant;
private LlamaData(int variantIn) {
this.variant = variantIn;
}
}
} | 33.825726 | 222 | 0.679036 |
d1b42de7e3d64ff6dd3b8d176b01cb68dc1940e2 | 3,275 | package cloud.xuxiaowei.audit.controller;
import cloud.xuxiaowei.audit.resilience4j.AuthorizationServerResilience4jService;
import cloud.xuxiaowei.oauth2.bo.AuditCodePageBo;
import cloud.xuxiaowei.system.annotation.ControllerAnnotation;
import cloud.xuxiaowei.utils.AssertUtils;
import cloud.xuxiaowei.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 授权码Code
*
* <code>
* 用户权限判断:@PreAuthorize("hasAuthority('user')")
* </code>
* <code>
* 客户范围判断:@PreAuthorize("#oauth2.hasScope('snsapi_base')")
* </code>
*
* @author xuxiaowei
* @since 0.0.1
*/
@RestController
@RequestMapping("/oauth-code")
public class OauthCodeController {
private AuthorizationServerResilience4jService authorizationServerResilience4jService;
@Autowired
public void setAuthorizationServerResilience4jService(AuthorizationServerResilience4jService authorizationServerResilience4jService) {
this.authorizationServerResilience4jService = authorizationServerResilience4jService;
}
/**
* 根据 授权码Code主键 删除 授权码
*
* @param request 请求
* @param response 响应
* @param codeId 授权码Code主键
* @return 返回 删除结果
*/
@ControllerAnnotation(description = "根据 授权码Code主键 删除 授权码")
@PreAuthorize("hasAuthority('audit_code_delete') or #oauth2.hasScope('audit_code_delete')")
@RequestMapping("/removeById/{codeId}")
public Response<?> removeById(HttpServletRequest request, HttpServletResponse response, @PathVariable("codeId") Long codeId) {
return authorizationServerResilience4jService.removeByAuditCodeId(codeId);
}
/**
* 根据 授权码Code主键 批量删除 授权码
*
* @param request 请求
* @param response 响应
* @param codeIds 授权码Code主键
* @return 返回 删除结果
*/
@ControllerAnnotation(description = "根据 授权码Code主键 批量删除 授权码")
@PreAuthorize("hasAuthority('audit_code_delete') or #oauth2.hasScope('audit_code_delete')")
@RequestMapping("/removeByIds")
public Response<?> removeByIds(HttpServletRequest request, HttpServletResponse response, @RequestBody List<Long> codeIds) {
AssertUtils.sizeNonNull(codeIds, 1, 50, "非法数据长度");
return authorizationServerResilience4jService.removeByAuditCodeIds(codeIds);
}
/**
* 分页查询授权码
*
* @param request 请求
* @param response 响应
* @param auditCodePageBo 审计授权码分页参数
* @return 返回 分页查询结果
*/
@ControllerAnnotation(description = "分页查询授权码")
@PreAuthorize("hasAuthority('audit_code_read') or #oauth2.hasScope('audit_code_read')")
@RequestMapping("/page")
public Response<?> page(HttpServletRequest request, HttpServletResponse response,
@RequestBody AuditCodePageBo auditCodePageBo) {
return authorizationServerResilience4jService.pageByAuditCode(auditCodePageBo);
}
}
| 34.473684 | 138 | 0.740458 |
9305497d10ad305d8425d94a97daa0aa27aa6291 | 18,299 | /**
* Items class is used to create items for the money tracking application.
*
* @author Sneha Gupta
*/
package com.company;
import java.util.*;
//import java.time.LocalDate;
//import java.time.format.DateTimeFormatter;
class Items {
private String type;
private String title;
private String month;
private double amount;
//public LocalDate dateFormat;
public Items(String type, String title, String month, double amount) {
this.type = type;
this.title = title;
this.month = month;
this.amount = amount;
//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//this.dateFormat = LocalDate.parse(date, formatter);
}
/**
* Returns a string representation of this list,
* containing all elements in their insertion order.
*/
@Override
public String toString() {
return "" + type + "**" + title + "**" + month + "**" + amount;
}
/**
* Get the `type` of the list element.
* The type is either `Expense` or `Income`
*/
public String getType() {
return this.type;
}
/**
* Get the `title` of the list element.
*/
public String getTitle() {
return this.title;
}
/**
* Get the `month` of the list element.
* The month value are months of the year.
*/
public String getMonth() {
return this.month;
}
/**
* Get the `amount` of the list element.
* The amount is of the type- double.
*/
public double getAmount() {
return this.amount;
}
}
/**
* The MoneyTracking class represents money tracking application.
* This class handles the 4 major features of the application-
* + Display the items
* + Add the items
* + Edit or remove items
* + Save and quit
*
* @author Sneha Gupta
*/
public class MoneyTracking {
private static FileHandler fileHandler = new FileHandler(); // reads the data from the filepath and
private static ArrayList<Items> moneyList = fileHandler.readAsData(); //store it under moneyList.
/**
* Shows the items of the list on the file and also displays new added items
* Items can displayed by types and can be sorted,
* This function calls `show` and `sortOrder` function internally,
* based on user input, which is read using scanner.
*/
public void showItems() {
System.out.println("Pick an option:");
System.out.println("(1) Show Items");
System.out.println("(2) Sort Items");
System.out.println("->");
int userChoice = scanUserInteger();
switch (userChoice) {
case 1 -> show(); //displays each items of the list.
case 2 -> sortOrder(); //sort every items of the list.
default -> System.out.println("Invalid userChoice!");
}
//Added this print satement to solve below problem:
System.out.println("Enter any key to continue-->"); //It is a bit hard to read the list
scanUserString(); // because the main menu pops up directly
} //after and user has to scrolls it up.
/**
* Shows the elements of the list by filtering the type,
* which is based on user input using scanner.
* This method calls the `filterByType` and `printEachItem` methods.
*/
private void show() {
System.out.println("Pick an option:");
System.out.println("(1) All");
System.out.println("(2) Show Expense");
System.out.println("(3) Show Income");
System.out.println("->");
int userChoice = scanUserInteger();
switch (userChoice) {
case 1 -> printEachItem(filterByType("All")); //displays each items of the list.
case 2 -> printEachItem(filterByType("Expense")); //But in case of an empty list, it displays
case 3 -> printEachItem(filterByType("Income")); // a message stating the no item found.
default -> System.out.println("Invalid userChoice!");
}
}
/**
* Sorting order is defined based on user choice.
* Sorting option are Ascending or Descending.
* `sort` method is called inside the method to sort the items.
*/
private void sortOrder() {
System.out.println("Pick a sorting order:");
System.out.println("(1) Ascending");
System.out.println("(2) Descending");
System.out.println("->");
int userChoice = scanUserInteger();
String order = "";
switch (userChoice) {
case 1 -> {
order = "Ascending";
sort(order); //sort the items in ascending order
}
case 2 -> {
order = "Descending";
sort(order); //sort the items in descending order
}
default -> System.out.println("Invalid userChoice!");
}
}
/**
* Asks user to sort on basis of title, month and amount
* and prints the sorted list.
* ´moneyList´ holds the last sorting stage of the list
*
* @param order
*/
private void sort(String order) {
System.out.println("Pick an option:");
System.out.println("(1) Sort by title");
System.out.println("(2) Sort by month");
System.out.println("(3) Sort by amount");
System.out.println("->");
int userChoice = scanUserInteger();
switch (userChoice) {
case 1 -> printEachItem(sortByTitle(order)); //print each item line by line after each sorting
case 2 -> printEachItem(sortByMonth(order));
case 3 -> printEachItem(sortByAmount(order));
default -> System.out.println("Invalid userChoice!");
}
}
/**
* Sort the items of the list based on its title.
* title is of String type, which is sorted by defining custom comparator
*
* @param order
* @return ArrayList<Items>
*/
private ArrayList<Items> sortByTitle(String order) {
//ArrayList<Items> readData = moneyList;
//sort the string in alphabetical order, so all title should be either lower or uppercase
Comparator<Items> compareByTitle = Comparator.comparing(Items::getTitle);
Comparator<Items> ReverseCompareByTitle = compareByTitle.reversed();
if (order.equals("Ascending")) {
Collections.sort(moneyList, compareByTitle);
} else {
Collections.sort(moneyList, ReverseCompareByTitle);
}
return moneyList;
}
/**
* Sort the items of the list based on its month.
* month is of String type but holds a valid name of the year's month name,
* which is stored in an array.
* Index of the month is used to sort by defining a custom comparator.
*
* @param order
* @return ArrayList<Items>
*/
private ArrayList<Items> sortByMonth(String order) {
//ArrayList<Items> readData = moneyList;
List<String> validMonths = Arrays.asList("january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november", "december");
// sort the month based on month index
// month should inserted in same format as listed above.
Comparator<Items> compareByMonth =
Comparator.comparing(item -> Integer.valueOf(validMonths.indexOf(item.getMonth())));
Comparator<Items> ReverseCompareByMonth = compareByMonth.reversed();
if (order.equals("Ascending")) {
Collections.sort(moneyList, compareByMonth);
} else {
Collections.sort(moneyList, ReverseCompareByMonth);
}
return moneyList;
}
/**
* Sort the items of the list based on its amount.
* amount is of double type, which is sorted by defining a custom comparator
*
* @param order
* @return ArrayList<Items>
*/
private ArrayList<Items> sortByAmount(String order) {
//ArrayList<Items> readData = moneyList;
Comparator<Items> compareByAmount = Comparator.comparingDouble(Items::getAmount);
Comparator<Items> ReverseCompareByAmount = compareByAmount.reversed();
if (order.equals("Ascending")) {
Collections.sort(moneyList, compareByAmount);
} else {
Collections.sort(moneyList, ReverseCompareByAmount);
}
return moneyList;
}
/**
* This method adds item to the list.
* Scanner is user to read input of the item type, title, amount and month.
* Expection is thrown is the user inserts wrong inputs.
* The item is added to the ´moneyList´ which can be used by other methods.
*/
public void addItems() {
System.out.println("Pick an option:");
System.out.println("(1) Add Expense");
System.out.println("(2) Add Income");
System.out.println("->");
int userChoice = scanUserInteger();
String type = null;
switch (userChoice) {
case 1 -> type = "Expense";
case 2 -> type = "Income";
default -> System.out.println("Invalid userChoice!");
}
System.out.println("Enter your Title:");
String title = scanUserString();
System.out.println("Enter your month:");
String month = scanUserMonth(); //user month input is formated.
System.out.println("Enter your Amount:");
double amount = scanUserDouble();
Items obj = new Items(type, title, month, amount);
moneyList.add(obj); //holds the values of the item in moneylist, till its saved using savequit feature.
System.out.println("Item added successfully!");
System.out.println("Enter any key to continue-->");
scanUserString();
}
/**
* This method edit or remove the item from the list.
* Scanner is user to read input of user, if he/she wants to edit or remove.
* Based on it ´edit()´ or ´remove()´ function is called.
*/
public void editItems() {
System.out.println("Pick an option:");
System.out.println("(1) Edit item");
System.out.println("(2) Remove item");
System.out.println("->");
int userChoice = scanUserInteger();
switch (userChoice) {
case 1 -> edit();
case 2 -> remove();
default -> System.out.println("Invalid userChoice!");
}
}
/**
* Edit method ask user to re-enter the item's type, title, month and amount.
* User picks the the item to be edited first, before editing.
* Arraylist ´.set()´ method is used to edit the item.
*/
private void edit() {
//ArrayList<Items> readData = moneyList;
int userChoice = pickAnOptionToEdit();
System.out.println("Enter new type:"); //ask user to re-enter the values for title, date, amount
String editType = scanUserType(); //should it be an optional feature??
System.out.println("Enter new title:"); //to ask user to enter only those values which he/she wish to edit
String editTitle = scanUserString();
System.out.println("Enter new month:");
String editDate = scanUserMonth();
System.out.println("Enter new amount:");
double editAmount = scanUserDouble();
for (int i = 0; i < moneyList.size(); i++) { //item value is edited on the moneylist, which gets
if (userChoice == i) { // written in the file after save method is called.
moneyList.set(i, new Items(editType, editTitle, editDate, editAmount));
}
}
System.out.println("Item edited successfully!");
}
/**
* Remove method ask remove the item from the list.
* User picks the the item to be removed first from the list, which is displayed first.
* Arraylist ´.remove()´ method is used to remove the item.
*/
private void remove() {
//ArrayList<Items> readData = moneyList;
int userChoice = pickAnOptionToEdit();
for (int i = 0; i < moneyList.size(); i++) {
if (userChoice == i) { //item value is edited on the moneylist, which gets
moneyList.remove(i); // written in the file after save method is called.
}
}
System.out.println("Item removed successfully!");
}
/**
* This method displays the list with the indexes,
* user inserts the index of the item to be edited/removed.
* If the input is outside the index of the arraylist, user is asked to repick.
*/
private int pickAnOptionToEdit() {
System.out.println("Pick an option:");
for (int i = 0; i < moneyList.size(); i++) {
System.out.println(i + ": " + moneyList.get(i)); //choice from 0,1,.. option, which list item to edit
}
int userChoice = scanUserInteger();
if (userChoice < 0 || userChoice >= moneyList.size()) {
System.out.println("Invalid option. Repick!");
pickAnOptionToEdit(); //recursion call, until the input value is correct
}
return userChoice;
}
/**
* This method saves the list to the file before quiting the application.
* All new added/edited/removed items are reflected to the file after this method.
*/
public void saveQuit() {
FileHandler fileHandler = new FileHandler();
fileHandler.writeAsData(moneyList); // items are writen to the file only in this method
System.out.println("Item saved successfully!");
}
/**
* This method filter the list by its the type.
* If All is passed as a parameter, then the method return the entire list,
* without filtering.
*
* @param filterValue
* @return ArrayList<Items>
*/
private ArrayList<Items> filterByType(String filterValue) {
ArrayList<Items> showData = new ArrayList<>();
ArrayList<Items> readData = moneyList;
if (filterValue.equals("All")) { // returns the ´moneyList´ whole list
return readData;
} else {
for (Items objData : readData) {
if ((objData.getType()).equals(filterValue)) {
showData.add(objData); // if no item is found, then returns an empty list
}
}
}
return showData;
}
/**
* This method scan Integer value.
* It thrown an IllegalArgumentException, if the input is not an integer.
*/
private int scanUserInteger() {
Scanner sc = new Scanner(System.in);
int inputInteger;
try {
inputInteger = sc.nextInt();
} catch (Exception e) {
throw new IllegalArgumentException("Invalid Input. Expecting an integer!");
}
return inputInteger;
}
/**
* This method scan String value.
* It thrown an IllegalArgumentException, if the input is not an string.
*/
private String scanUserString() {
Scanner sc = new Scanner(System.in);
String inputString;
try {
inputString = sc.nextLine();
} catch (Exception e) {
throw new IllegalArgumentException("Invalid Input. Expecting String!");
}
return inputString.toLowerCase();
}
/**
* This method scan String value of the month.
* If the value entered is not a valid month name, it calls itself until
* the right value is passed. It formats the input scanned to lower case.
*/
private String scanUserMonth() {
String month = scanUserString().toLowerCase();
String[] validMonths = {"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november", "december"};
boolean isValid = false;
for (String validMonth : validMonths) { // only the correct month name is accepted
if (month.equals(validMonth)) {
isValid = true;
break;
}
}
if (!isValid) {
System.out.println("Invalid month. Re-enter the month:");
scanUserMonth();
}
return month;
}
/**
* This method scan String value of the type.
* If the value entered is not a valid type, it calls itself until
* the right value is passed. It formats the input scanned to
* first string as uppercase and rest as lower case.
*/
private String scanUserType() {
String type = scanUserString();
type = type.substring(0, 1).toUpperCase() + type.substring(1).toLowerCase();
String[] validTypes = {"Expense", "Income"}; // user input is being formatted
boolean isValid = false;
for (String validType : validTypes) {
if (type.equals(validType)) {
isValid = true;
break;
}
}
if (!isValid) {
System.out.println("Invalid type. Re-enter the type:");
scanUserType();
}
return type;
}
/**
* This method scan Double value.
* It thrown an IllegalArgumentException, if the input is not an double.
*/
private double scanUserDouble() {
Scanner sc = new Scanner(System.in);
double inputDouble;
try {
inputDouble = sc.nextDouble();
} catch (Exception e) {
throw new IllegalArgumentException("Invalid Input. Expecting a Double!");
}
return inputDouble;
}
/**
* This method prints each items of the list line by line.
* If the file is empty/ list is empty, it prints a message
* - No items available.
*/
private void printEachItem(ArrayList<Items> itemList) {
for (Items item : itemList) {
System.out.println(item);
}
if (itemList.size() == 0) { //handles an empty list or an empty file.
System.out.println("No items available.");
}
}
} | 36.30754 | 123 | 0.587464 |
ea7056be05c9221badca2b518b96374c9d9af880 | 13,131 | package com.wishhard.h24;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.muddzdev.styleabletoastlibrary.StyleableToast;
import com.wishhard.h24.frag.Wheeler;
import com.wishhard.h24.shared_pref_util.TimeSharedPref;
import com.wishhard.h24.utils.ScreenUtility;
import com.wishhard.h24.view.StopWatch;
import com.wishhard.h24.view.TheFrame;
public class WatchActivity extends AppCompatActivity implements HeadlessFrag.TaskStatusCallback, TheFrame.ClickEvent
, Wheeler.WheelerFragmentListener{
private static final String TIME_KEY = "24_time_key";
private static final String[] TIME_INSTENT_STATE_KEY = new String[] {
"hor_kry","min_key","sec_key"
};
private static final String[] REMAINING_TIME_PRAF = new String[]{"com.wishhard.remainder_h","com.wishhard.remainder_m",
"com.wishhard.remainder_s"};
public static final String TIME_MIN_LIMIT = "00:00:00";
private static final String TIME_MAX_LIMIT = "24:00:00";
private StopWatch stopWatch;
private HeadlessFrag frag;
private TheFrame theFrame;
private SharedPreferences defaultSharedPreferences;
private InterstitialAd mInterstitialAd;
View mContent;
TimeSharedPref timeSharedPref;
private String h = Wheeler.DEFUALT_VALUE,m = Wheeler.DEFUALT_VALUE,s = Wheeler.DEFUALT_VALUE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch);
noWheelerOnCreate();
defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
ScreenUtility.initContext(this);
timeSharedPref = TimeSharedPref.getInstance(this);
setHMSFromPrafs();
theFrame = findViewById(R.id.mainFrame);
theFrame.initViews();
theFrame.setOnClickEventListener(this);
mContent = findViewById(com.wishhard.h24.R.id.act);
stopWatch = findViewById(R.id.sw_tv);
stopWatch.setText(setTimeStr(h,m,s));
if(savedInstanceState != null) {
String strTime = savedInstanceState.getString(TIME_KEY);
h = savedInstanceState.getString(TIME_INSTENT_STATE_KEY[0]);
m = savedInstanceState.getString(TIME_INSTENT_STATE_KEY[1]);
s = savedInstanceState.getString(TIME_INSTENT_STATE_KEY[2]);
if(strTime.equals("")) {
stopWatch.setText(setTimeStr(h,m,strTime));
} else {
stopWatch.setText(strTime);
}
}
FragmentManager mgr = getSupportFragmentManager();
frag = (HeadlessFrag) mgr.findFragmentByTag(HeadlessFrag.HEADLESS_FRAG_TAG);
if(frag == null) {
frag = new HeadlessFrag();
mgr.beginTransaction().add(frag,HeadlessFrag.HEADLESS_FRAG_TAG).commit();
}
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3133582463179859/3445815489");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
startActivity(new Intent(WatchActivity.this,SettingsActivity.class));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
mContent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
noWheelerOnCreate();
theFrame.makeTheFrameVisibleWithAnim();
if(theFrame.isPlaying()) {
theFrame.setPlaying(false);
if(frag != null) {
frag.cancelBackgroundTask();
}
theFrame.enablePlayAndReset(isCountUp(),stopWatch.getText().toString());
}
}
});
}
@Override
protected void onUserLeaveHint() {
saveRemainingTimeToPraf();
noWheelerOnCreate();
if(frag != null) {
frag.cancelBackgroundTask();
}
theFrame.setPlaying(false);
super.onUserLeaveHint();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(TIME_KEY,stopWatch.getText().toString());
outState.putString(TIME_INSTENT_STATE_KEY[0],h);
outState.putString(TIME_INSTENT_STATE_KEY[1],m);
outState.putString(TIME_INSTENT_STATE_KEY[2],s);
}
@Override
public void onBackPressed() {
saveRemainingTimeToPraf();
if(frag != null) {
frag.cancelBackgroundTask();
}
super.onBackPressed();
}
@Override
protected void onResume() {
super.onResume();
theFrame.enablePlayAndReset(isCountUp(),stopWatch.getText().toString());
theFrame.upDateViewSavedState();
screenLight(theFrame.isPlaying());
}
@Override
protected void onPause() {
doWhenScreenIsOff();
super.onPause();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
doWhenPowerLongPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onProgressUpdate(String[] t) {
h = t[0];
m = t[1];
s = t[2];
stopWatch.setText(setTimeStr(h,m,s));
}
@Override
public void onPostExecute() {
if(frag != null) {
frag.upDateExecutingStatus(false);
}
saveRemainingTimeToPraf(Wheeler.DEFUALT_VALUE,Wheeler.DEFUALT_VALUE,Wheeler.DEFUALT_VALUE);
theFrame.setPlaying(false);
theFrame.enablePlayAndReset(isCountUp(),setTimeStr(h,m,s));
screenLight(theFrame.isPlaying());
}
@Override
public void setings() {
if(mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
startActivity(new Intent(this,SettingsActivity.class));
}
theFrame.setVisibility(View.GONE);
theFrame.setVisibilityGone(true);
}
@Override
public void setTimer() {
Wheeler wheelerFrag = new Wheeler();
theFrame.makeTheFrameVisibleWithAnim();
getSupportFragmentManager().beginTransaction().addToBackStack(null).add(com.wishhard.h24.R.id.wheeler, wheelerFrag).commit();
}
@Override
public void resetTimer() {
resetShopWatch();
}
@Override
public void playAndPase(boolean isPlaying) {
screenLight(isPlaying);
theFrame.enableReset(isPlaying);
startAndShopWatch(isPlaying);
theFrame.makeTheFrameVisibleWithAnim();
}
public void onCanncelDiagolOressed() {
Wheeler wheelerFrag = (Wheeler) getSupportFragmentManager().findFragmentById(com.wishhard.h24.R.id.wheeler);
getSupportFragmentManager().beginTransaction().remove(wheelerFrag).commit();
}
private void noWheelerOnCreate() {
Wheeler wheelerFrag = (Wheeler) getSupportFragmentManager().findFragmentById(com.wishhard.h24.R.id.wheeler);
if(wheelerFrag != null) {
getSupportFragmentManager().beginTransaction().remove(wheelerFrag).commit();
}
}
private void startAndShopWatch(boolean b) {
if(b) {
if(frag != null) {
frag.startBackgroundTask(h,m,s);
}
} else {
if(frag != null) {
frag.cancelBackgroundTask();
}
}
}
private String setTimeStr(String h,String m,String s) {
return String.format("%s:%s:%s",h,m,s);
}
private void saveRemainingTimeToPraf() {
if(!stopWatch.getText().toString().equals("")) {
timeSharedPref.setValue(REMAINING_TIME_PRAF[0],h);
timeSharedPref.setValue(REMAINING_TIME_PRAF[1],m);
timeSharedPref.setValue(REMAINING_TIME_PRAF[2],s);
}
}
private void saveRemainingTimeToPraf(String ho,String mi,String se) {
timeSharedPref.setValue(REMAINING_TIME_PRAF[0],ho);
timeSharedPref.setValue(REMAINING_TIME_PRAF[1],mi);
timeSharedPref.setValue(REMAINING_TIME_PRAF[2],se);
}
private String[] getRemainingTimeForPraf() {
String[] s = new String[3];
s[0] = timeSharedPref.getStringValue(REMAINING_TIME_PRAF[0],Wheeler.DEFUALT_VALUE);
s[1] = timeSharedPref.getStringValue(REMAINING_TIME_PRAF[1],Wheeler.DEFUALT_VALUE);
s[2] = timeSharedPref.getStringValue(REMAINING_TIME_PRAF[2],Wheeler.DEFUALT_VALUE);
return s;
}
public boolean isCountUp() {
return defaultSharedPreferences.getBoolean(SettingsActivity.COUNTUP_PREF_KEY,true);
}
private boolean isKeepScreenOn() {
return defaultSharedPreferences.getBoolean(SettingsActivity.KEEP_SCREEN_ON,false);
}
public boolean isSoundEffeect() {
return defaultSharedPreferences.getBoolean(SettingsActivity.SOUND_EFFECT_KEY,true);
}
private void doWhenScreenIsOff() {
if(theFrame.isPlaying() && !ScreenUtility.isScreenOn()) {
if(frag != null) {
frag.cancelBackgroundTask();
}
theFrame.setPlaying(false);
}
}
private void doWhenPowerLongPressed() {
saveRemainingTimeToPraf();
if(frag != null) {
frag.cancelBackgroundTask();
}
theFrame.setPlaying(false);
theFrame.enablePlayAndReset(isCountUp(),setTimeStr(h,m,s));
}
private void screenLight(boolean isPlaying) {
if(isKeepScreenOn()) {
if(isPlaying) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
}
private String[] getWheelerPrafValue() {
String[] s = new String[3];
s[0] = timeSharedPref.getStringValue(Wheeler.PREF_KEYS_FOR_TIME[0],Wheeler.DEFUALT_VALUE);
s[1] = timeSharedPref.getStringValue(Wheeler.PREF_KEYS_FOR_TIME[1],Wheeler.DEFUALT_VALUE);
s[2] = timeSharedPref.getStringValue(Wheeler.PREF_KEYS_FOR_TIME[2],Wheeler.DEFUALT_VALUE);
return s;
}
private void setHMSFromPrafs() {
String[] remainingTime = getRemainingTimeForPraf();
h = remainingTime[0];
m = remainingTime[1];
s = remainingTime[2];
}
private void resetShopWatch() {
String[] forWheeler = getWheelerPrafValue();
h = forWheeler[0];
m = forWheeler[1];
s = forWheeler[2];
stopWatch.setText(setTimeStr(h,m,s));
if(!isCountUp() && stopWatch.getText().equals(TIME_MIN_LIMIT)) {
new StyleableToast.Builder(this).text("Can't countdown from " +
TIME_MIN_LIMIT + ". CountUp is unchecked!").textColor(Color.BLACK).
backgroundColor(Color.YELLOW).show();
} else if(isCountUp() && stopWatch.getText().equals(TIME_MAX_LIMIT)) {
new StyleableToast.Builder(this).text("Can't count up from " +
TIME_MAX_LIMIT + ". CountUp is checked!").textColor(Color.BLACK).
backgroundColor(Color.YELLOW).show();
}
theFrame.enablePlayAndReset(isCountUp(),setTimeStr(h,m,s));
}
@Override
public void timeStringValues(String hourStr, String minStr, String secStr) {
saveRemainingTimeToPraf(Wheeler.DEFUALT_VALUE,Wheeler.DEFUALT_VALUE,Wheeler.DEFUALT_VALUE);
h = hourStr;
m = minStr;
s = secStr;
stopWatch.setText(setTimeStr(h,m,s));
theFrame.enablePlayAndReset(isCountUp(),setTimeStr(h,m,s));
Wheeler wheelerFrag = (Wheeler) getSupportFragmentManager().findFragmentById(com.wishhard.h24.R.id.wheeler);
getSupportFragmentManager().beginTransaction().remove(wheelerFrag).commit();
}
}
| 32.583127 | 142 | 0.617927 |
2c641803d87774a632a241323ac1ad2e2f33b2e8 | 1,457 | package com.github.mforoni.jsupport;
import javax.annotation.Nullable;
import org.fluttercode.datafactory.impl.DataFactory;
import org.joda.time.LocalDate;
import com.google.common.base.Function;
/**
* @author Foroni Marco
*/
public class Person {
public enum Gender {
MALE, FEMALE;
public static Gender random(final DataFactory dataFactory) {
return dataFactory.chance(50) ? Gender.MALE : Gender.FEMALE;
}
}
public static final Function<Person, String> GET_LASTNAME = new Function<Person, String>() {
@Override
public String apply(@Nullable final Person p) {
return p == null ? null : p.getLastName();
}
};
protected String firstName;
protected String lastName;
protected LocalDate dateBirth;
protected Gender gender;
protected String email;
Person(final String firstName, final String lastName, final LocalDate dateBirth,
final Gender gender, final String email) {
this.firstName = firstName;
this.lastName = lastName;
this.dateBirth = dateBirth;
this.gender = gender;
this.email = email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public LocalDate getDateBirth() {
return dateBirth;
}
public Gender getGender() {
return gender;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return firstName + " " + lastName;
}
}
| 22.415385 | 94 | 0.693205 |
a3e0c8c7f002c2683962a2bcdc6f6a243f9de1e7 | 3,892 | /*
* Copyright 2020 Raffaele Ragni <[email protected]>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package baselib;
import static baselib.ExceptionWrapper.ex;
import java.lang.reflect.RecordComponent;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
/**
*
* @author Raffaele Ragni <[email protected]>
*/
public final class Records {
private Records() {
}
public static Map<String, Object> toMap(Object rec) {
Objects.requireNonNull(rec);
if (!isRecord(rec))
throw recordRequiredException();
var result = new HashMap<String, Object>();
for (var field: getRecordFields(rec)) {
var value = getFieldValue(field, rec);
if (isRecord(value))
result.put(field.getName(), toMap(value));
else
result.put(field.getName(), value);
}
return result;
}
public static <T> T fromMap(Class<T> clazz, Map<String, Object> map) {
if (map == null)
return null;
return fromPropertyDiscover(clazz, map::get);
}
public static <T> T fromPropertyDiscover(Class<T> clazz, Function<String, Object> fetch) {
if (fetch == null)
return null;
if (!clazz.isRecord())
throw recordRequiredException();
var params = new LinkedList<Object>();
var types = new LinkedList<Class<?>>();
for (var field: getDeclaredFields(clazz)) {
var type = field.getType();
var value = getValueWithNameCases(fetch, field);
types.add(type);
if (type.isRecord() && value instanceof Map m)//NOSONAR
params.add(fromMap(type, m));
else if (type.isEnum())
params.add(fromEnum(type, value));
else
params.add(value);
}
var constructor = ex(() -> clazz.getDeclaredConstructor(types.toArray(new Class[]{})));
return ex(() -> constructor.newInstance(params.toArray()));
}
static Object fromEnum(Class<?> type, Object value) {
return Arrays.stream(type.getEnumConstants())
.filter(e -> e.toString().equals(value.toString()))
.findAny()
.orElse(null);
}
static Object getValueWithNameCases(Function<String, Object> fetch, RecordComponent e) {
var value = fetch.apply(e.getName());
if (value != null)
return value;
var snakeName = NameTransform.SNAKE.apply(e.getName());
value = fetch.apply(snakeName.toLowerCase());
if (value != null)
return value;
value = fetch.apply(snakeName.toUpperCase());
if (value != null)
return value;
var kebabName = NameTransform.KEBAB.apply(e.getName());
value = fetch.apply(kebabName.toLowerCase());
if (value != null)
return value;
value = fetch.apply(kebabName.toUpperCase());
return value;
}
static boolean isRecord(Object value) {
return value.getClass().isRecord();
}
static RecordComponent[] getRecordFields(Object rec) {
return getDeclaredFields(rec.getClass());
}
static Object getFieldValue(RecordComponent field, Object rec) {
return ex(() -> field.getAccessor().invoke(rec));
}
static IllegalArgumentException recordRequiredException() {
return new IllegalArgumentException("Required a java record");
}
static RecordComponent[] getDeclaredFields(Class<?> clazz) {
return clazz.getRecordComponents();
}
}
| 28.617647 | 92 | 0.675745 |
7b293f1d7944a2d6605e585c5e0bcaafac81358a | 4,346 | package com.readonlydev.lib.world.gen.feature;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockVine;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;
public class WorldGenVinesRTG extends WorldGenerator {
protected Block vineBlock;
protected int maxY;
protected PropertyBool propNorth;
protected PropertyBool propEast;
protected PropertyBool propSouth;
protected PropertyBool propWest;
public WorldGenVinesRTG() {
this.vineBlock = Blocks.VINE;
this.setMaxY(254);
this.propNorth = BlockVine.NORTH;
this.propEast = BlockVine.EAST;
this.propSouth = BlockVine.SOUTH;
this.propWest = BlockVine.WEST;
}
public WorldGenVinesRTG(Block vineBlock, int maxY, PropertyBool propNorth, PropertyBool propEast, PropertyBool propSouth, PropertyBool propWest) {
this();
this.vineBlock = vineBlock;
this.maxY = maxY;
this.propNorth = propNorth;
this.propEast = propEast;
this.propSouth = propSouth;
this.propWest = propWest;
}
@Override
public boolean generate(World worldIn, Random rand, BlockPos position) {
for (; position.getY() < this.maxY; position = position.up()) {
if (worldIn.isAirBlock(position)) {
Block north = worldIn.getBlockState(position.north()).getBlock();
Block south = worldIn.getBlockState(position.south()).getBlock();
Block east = worldIn.getBlockState(position.east()).getBlock();
Block west = worldIn.getBlockState(position.west()).getBlock();
for (EnumFacing enumfacing : EnumFacing.Plane.HORIZONTAL.facings()) {
if (this.vineBlock.canPlaceBlockOnSide(worldIn, position, enumfacing)) {
this.addVine(worldIn, rand, position, enumfacing);
break;
}
}
}
else {
position = position.add(rand.nextInt(4) - rand.nextInt(4), 0, rand.nextInt(4) - rand.nextInt(4));
}
}
return true;
}
protected void addVine(World worldIn, Random rand, BlockPos pos, EnumFacing enumfacing) {
IBlockState iblockstate = this.vineBlock.getDefaultState()
.withProperty(this.propNorth, enumfacing == EnumFacing.SOUTH)
.withProperty(this.propEast, enumfacing == EnumFacing.WEST)
.withProperty(this.propSouth, enumfacing == EnumFacing.NORTH)
.withProperty(this.propWest, enumfacing == EnumFacing.EAST);
this.setBlockAndNotifyAdequately(worldIn, pos, iblockstate);
int i = rand.nextInt(4) + 1;
for (pos = pos.down(); worldIn.isAirBlock(pos) && i > 0; --i) {
this.setBlockAndNotifyAdequately(worldIn, pos, iblockstate);
pos = pos.down();
}
}
public Block getVineBlock() {
return vineBlock;
}
public WorldGenVinesRTG setVineBlock(Block vineBlock) {
this.vineBlock = vineBlock;
return this;
}
public int getMaxY() {
return maxY;
}
public WorldGenVinesRTG setMaxY(int maxY) {
this.maxY = maxY;
return this;
}
public PropertyBool getPropNorth() {
return propNorth;
}
public WorldGenVinesRTG setPropNorth(PropertyBool propNorth) {
this.propNorth = propNorth;
return this;
}
public PropertyBool getPropEast() {
return propEast;
}
public WorldGenVinesRTG setPropEast(PropertyBool propEast) {
this.propEast = propEast;
return this;
}
public PropertyBool getPropSouth() {
return propSouth;
}
public WorldGenVinesRTG setPropSouth(PropertyBool propSouth) {
this.propSouth = propSouth;
return this;
}
public PropertyBool getPropWest() {
return propWest;
}
public WorldGenVinesRTG setPropWest(PropertyBool propWest) {
this.propWest = propWest;
return this;
}
} | 27.506329 | 150 | 0.636677 |
381e32b0152bc10870282aa87b02ec71b79b64d8 | 2,447 | package cz.muni.fi.gag.web.services.websocket.endpoint.packet.actions;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import org.jboss.logging.Logger;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
import java.io.IOException;
/**
* @author Vojtech Prusa
* <p>
* {@link ActionDecoder}
* {@link RecognitionActions}
* {@link PlayerActions}
*/
public abstract class ActionDecoderBase<Act extends Action> implements Decoder.Text<Act> {
public static final Logger log = Logger.getLogger(ActionDecoderBase.class.getSimpleName());
private ObjectMapper objectMapper;
private final Action.ActionsTypesEnum typeEnum;
private final Class actionClass;
public ActionDecoderBase(final Class actionClass, final Action.ActionsTypesEnum typeEnum) {
this.typeEnum = typeEnum;
this.actionClass = actionClass;
objectMapper = new ObjectMapper();
}
@Override
public Act decode(String s) {
// log.info("decode: " + this.getClass().getSimpleName());
ObjectReader objectReader = objectMapper.reader().forType(actionClass);
try {
Act cmd = objectReader.readValue(s);
// log.info(cmd.toString());
return cmd;
} catch (IOException e) {
e.printStackTrace();
//throw new DecodeException("","");
}
return null;
}
@Override
public boolean willDecode(String s) {
// log.info(s);
// log.info("typeEnum");
// log.info(typeEnum);
// log.info("actionClass");
// log.info(actionClass);
if (typeEnum == null) {
// log.info("Will ret? " + s.contains("\"type\""));
return s.contains("\"type\"");
} else {
// log.info("Will ret? " + (s.contains("\"type\"") && s.contains("\"" + typeEnum.toString() + "\"")));
// return s.contains("\"type\"") && s.contains("\"" + actionClass.toString() + "\"");
return s.contains("\"type\":" + typeEnum.ordinal()) || s.contains("\"type\":\"" + typeEnum.toString() + "\"");
}
}
@Override
public void init(EndpointConfig config) {
objectMapper = new ObjectMapper();
}
@Override
public void destroy() {
// TODO https://www.geeksforgeeks.org/how-to-make-object-eligible-for-garbage-collection/
//objectMapper = null;
}
}
| 32.197368 | 122 | 0.617491 |
6c336cb83a98896a64fa89777b386b1dae8417a1 | 106 | package audionote;
public class sum{
public static int sum(int a, int b){
return a+b;
}
} | 15.142857 | 40 | 0.603774 |
10731475461837c5fac5d536838d5fe8cf57318f | 1,029 | package joshie.progression.network.core;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
public class PenguinNetwork {
private final SimpleNetworkWrapper INSTANCE;
private final PenguinPacketHandler handler;
private int id;
public PenguinNetwork(String name) {
INSTANCE = new SimpleNetworkWrapper(name);
handler = new PenguinPacketHandler();
}
public void registerPacket(Class clazz, Side side) {
INSTANCE.registerMessage(handler, clazz, id++, side);
}
public void sendToClient(IMessage message, EntityPlayerMP player) {
INSTANCE.sendTo(message, player);
}
public void sendToServer(IMessage message) {
INSTANCE.sendToServer(message);
}
public void sendToEveryone(IMessage message) {
INSTANCE.sendToAll(message);
}
}
| 30.264706 | 77 | 0.728863 |
46ce148d32e6308b34ef860864f51a5d268db0c8 | 10,323 | package com.sstechcanada.todo.adapters;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.graphics.drawable.GradientDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import com.sstechcanada.todo.R;
import com.sstechcanada.todo.custom_views.PriorityStarImageView;
import com.sstechcanada.todo.data.TodoListContract;
import com.sstechcanada.todo.models.TodoTask;
import com.sstechcanada.todo.utils.TodoDateUtils;
public class TodoListAdapter extends RecyclerView.Adapter<TodoListAdapter.TodoListAdapterViewHolder> {
private final static String TAG = TodoListAdapter.class.getSimpleName();
private final TodoListAdapterOnClickHandler mClickHandler;
private final Context mContext;
private final Resources mRes;
private final ColorStateList completedCheckboxColors;
private final ColorStateList unCompletedCheckboxColors;
private Cursor mCursor;
private int mDescriptionIndex;
private int mPriorityIndex;
private int mDueDateIndex;
private int m_IDIndex;
private int mCompletedIndex;
//Circle Text View
public TodoListAdapter(Context context, TodoListAdapterOnClickHandler todoListAdapterOnClickHandler) {
mClickHandler = todoListAdapterOnClickHandler;
mContext = context;
mRes = context.getResources();
completedCheckboxColors = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_checked},
new int[]{android.R.attr.state_checked},
},
new int[]{
Color.DKGRAY,
mRes.getColor(R.color.colorCompleted),
});
unCompletedCheckboxColors = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_checked},
new int[]{android.R.attr.state_checked},
},
new int[]{
Color.DKGRAY,
mRes.getColor(R.color.colorAccent),
});
}
@Override
public TodoListAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.item_todo_list;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
TodoListAdapterViewHolder viewHolder = new TodoListAdapterViewHolder(view);
return viewHolder;
}
@SuppressLint("RestrictedApi")
@Override
public void onBindViewHolder(@NonNull TodoListAdapter.TodoListAdapterViewHolder holder, int position) {
mCursor.moveToPosition(position);
holder.tvTextDesc.setText(mCursor.getString(mDescriptionIndex));
holder.tvTodoDueDate.setTextColor(holder.tvTodoPriority.getCurrentTextColor());
String dueDateString;
long dueDate = mCursor.getLong(mDueDateIndex);
Log.d(TAG, mCursor.getString(mDescriptionIndex) + " " + dueDate);
if (dueDate == TodoTask.NO_DUE_DATE) {
dueDateString = mContext.getString(R.string.no_due_date);
} else {
dueDateString = TodoDateUtils.formatDueDate(mContext, dueDate);
}
//
// int priority = mCursor.getInt(mPriorityIndex);
holder.tvTodoDueDate.setText(dueDateString);
// holder.tvTodoPriority.setText(mRes.getStringArray(R.array.priorities)[priority]);
int isCompleted = mCursor.getInt(mCompletedIndex);
holder.cbTodoDescription.setChecked(isCompleted == TodoTask.TASK_COMPLETED);
if (isCompleted == TodoTask.TASK_COMPLETED) {
// if the task is completed, we want everything grey
holder.clTodoListItem.setBackground(mRes.getDrawable(R.drawable.list_item_completed_touch_selector));
holder.tvTextDesc.setTextColor(mRes.getColor(R.color.colorCompleted));
holder.cbTodoDescription.setSupportButtonTintList(completedCheckboxColors);
holder.tvTodoPriority.setText(mRes.getString(R.string.completed));
holder.customCheckbox.setChecked(true);
// priority = PriorityStarImageView.COMPLETED;
} else {
holder.clTodoListItem.setBackground(mRes.getDrawable(R.drawable.list_item_touch_selector));
holder.tvTextDesc.setTextColor(mRes.getColor(R.color.textHeadings));
holder.cbTodoDescription.setSupportButtonTintList(unCompletedCheckboxColors);
holder.customCheckbox.setChecked(false);
// holder.tvTodoPriority.setText(mRes.getStringArray(R.array.priorities)[priority]);
if (dueDate < TodoDateUtils.getTodaysDateInMillis()) {
// display overdue tasks with the date in red
// yeah, I know red for both overdue and high priority may be not the best idea
holder.tvTodoDueDate.setTextColor(mRes.getColor(R.color.colorOverdue));
} else {
holder.tvTodoDueDate.setTextColor(holder.tvTodoPriority.getCurrentTextColor());
Log.d(TAG, "color is " + (holder.tvTodoPriority.getCurrentTextColor()));
}
}
// holder.ivTodoPriorityStar.setPriority(priority);
//Circle
// Set the proper background color on the magnitude circle.
// Fetch the background from the TextView, which is a GradientDrawable.
GradientDrawable magnitudeCircle = (GradientDrawable) holder.circle_per.getBackground();
// Get the appropriate background color based on the current earthquake magnitude
int magnitudeColor = getMagnitudeColor(position%9);
// Set the color on the magnitude circle
magnitudeCircle.setColor(magnitudeColor);
}
@Override
public int getItemCount() {
if (mCursor == null) {
return 0;
} else {
return mCursor.getCount();
}
}
public void swapCursor(Cursor newCursor) {
mCursor = newCursor;
if (mCursor != null) {
mDescriptionIndex = mCursor.getColumnIndex(TodoListContract.TodoListEntry.COLUMN_DESCRIPTION);
mPriorityIndex = mCursor.getColumnIndex(TodoListContract.TodoListEntry.COLUMN_PRIORITY);
mDueDateIndex = mCursor.getColumnIndex(TodoListContract.TodoListEntry.COLUMN_DUE_DATE);
m_IDIndex = mCursor.getColumnIndex(TodoListContract.TodoListEntry.COLUMN_ID);
mCompletedIndex = mCursor.getColumnIndex(TodoListContract.TodoListEntry.COLUMN_COMPLETED);
}
notifyDataSetChanged();
}
public interface TodoListAdapterOnClickHandler {
void onClick(TodoTask todoTask, View view);
}
public class TodoListAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final AppCompatCheckBox cbTodoDescription;
TextView tvTodoDueDate, tvTextDesc, circle_per;
final TextView tvTodoPriority;
final PriorityStarImageView ivTodoPriorityStar;
final ConstraintLayout clTodoListItem;
CheckBox customCheckbox;
public TodoListAdapterViewHolder(View itemView) {
super(itemView);
cbTodoDescription = itemView.findViewById(R.id.cb_todo_description);
tvTextDesc = itemView.findViewById(R.id.tv_todo_desc);
tvTodoDueDate = itemView.findViewById(R.id.tv_todo_due_date);
tvTodoPriority = itemView.findViewById(R.id.tv_todo_priority);
ivTodoPriorityStar = itemView.findViewById(R.id.iv_todo_priority_star);
customCheckbox = itemView.findViewById(R.id.checkb);
clTodoListItem = (ConstraintLayout) itemView;
itemView.setOnClickListener(this);
cbTodoDescription.setOnClickListener(this);
//Circle
circle_per = itemView.findViewById(R.id.circle_per_item);
}
@Override
public void onClick(View view) {
mCursor.moveToPosition(getAdapterPosition());
TodoTask todoTask = new TodoTask(mCursor.getString(mDescriptionIndex),
mCursor.getInt(mPriorityIndex),
mCursor.getLong(mDueDateIndex),
mCursor.getInt(m_IDIndex),
mCursor.getInt(mCompletedIndex));
mClickHandler.onClick(todoTask, view);
}
}
private int getMagnitudeColor(int pos) {
int magnitudeColorResourceId;
int magnitudeFloor = pos;
switch (magnitudeFloor) {
case 0:
case 1:
magnitudeColorResourceId = R.color.circle1;
break;
case 2:
magnitudeColorResourceId = R.color.circle2;
break;
case 3:
magnitudeColorResourceId = R.color.circle3;
break;
case 4:
magnitudeColorResourceId = R.color.circle4;
break;
case 5:
magnitudeColorResourceId = R.color.circle5;
break;
case 6:
magnitudeColorResourceId = R.color.circle6;
break;
case 7:
magnitudeColorResourceId = R.color.circle7;
break;
case 8:
magnitudeColorResourceId = R.color.circle8;
break;
case 9:
magnitudeColorResourceId = R.color.circle9;
break;
default:
magnitudeColorResourceId = R.color.circle1;
break;
}
return ContextCompat.getColor(mContext, magnitudeColorResourceId);
}
}
| 42.657025 | 113 | 0.664729 |
4f670305e0cbb821b24f875a17392391c9cb82cd | 1,487 | /*
* (C) Copyright 2012-2013 Nuxeo SA (http://nuxeo.com/) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.nuxeo.connect.tools.report.web;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import org.nuxeo.ecm.webengine.model.Access;
import org.nuxeo.ecm.webengine.model.Template;
import org.nuxeo.ecm.webengine.model.WebObject;
import org.nuxeo.ecm.webengine.model.impl.ModuleRoot;
/**
* Routes request to the report runner.
*
* @ToDo move root in another module and define report runner as a fragment
*
* @since 8.3
*/
@Path("/connect-tools")
@WebObject(type = "root", administrator = Access.GRANT)
public class ConnectToolsRoot extends ModuleRoot {
@GET
public Template index() {
return getView("index");
}
@Path("/{resource}")
public ReportRunnerObject report(@PathParam("resource") String resource) {
return (ReportRunnerObject) newObject(resource, this);
}
}
| 29.74 | 78 | 0.722932 |
1af75a7b0dc256f0270045ecc51d8cded0505e97 | 591 | package org.ofdrw.core.text.transform;
import org.junit.jupiter.api.Test;
import org.ofdrw.TestTool;
import org.ofdrw.core.basicType.ST_Array;
import org.ofdrw.core.text.CT_CGTransfrom;
public class CT_CGTransfromTest {
public static CT_CGTransfrom cgTransfromCase(){
return new CT_CGTransfrom()
.setCodePosition(1)
.setCodeCount(2)
.setGlyphCount(2)
.setGlyphs(new ST_Array(68, 74));
}
@Test
public void gen() throws Exception {
TestTool.genXml("CT_CGTransfrom", cgTransfromCase());
}
} | 26.863636 | 61 | 0.656514 |
f61010a7878cd77e88c0053b2908a0ec982d7268 | 594 | package com.longbow.api.user.dto;
import lombok.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* Created by zhangbin on 2019/3/19.
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class RegisterUserRequest implements Serializable {
@NotNull(message="用户名不能为空")
private String username;
@NotEmpty(message = "密码不能为空")
private String password;
@Email(message="邮箱格式错误")
private String email;
private String mobile;
}
| 22 | 58 | 0.759259 |
c919550241e1159d8d9e2041dc841576b14b0659 | 47 | package github.chorman0773.pokemonsms.net.test; | 47 | 47 | 0.87234 |
290db5ac4063eab5deece884cc45a72000bb16bd | 10,415 | /******************************************************************/
/* ACM ICPC 2015-2016, NEERC */
/* Northern Subregional Contest */
/* St Petersburg, October 24, 2015 */
/******************************************************************/
/* Problem F. Fygon */
/* */
/* Original idea Pavel Mavrin */
/* Problem statement Pavel Mavrin */
/* Test set Pavel Mavrin */
/******************************************************************/
/* Checker */
/* */
/* Author Pavel Mavrin */
/******************************************************************/
import ru.ifmo.testlib.Checker;
import ru.ifmo.testlib.InStream;
import ru.ifmo.testlib.Outcome;
import static ru.ifmo.testlib.Outcome.Type.*;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Check implements Checker {
private static final int MAX_LENGTH = 100;
public Outcome outcome(Outcome.Type type, final String format, final Object... args) {
return new Outcome(type, String.format(format, args));
}
public Outcome test(InStream inf, InStream ouf, InStream ans) {
Polynomial jury = null;
try {
jury = parse(ans.nextLine());
} catch (ParseException e) {
return outcome(FAIL, e.getMessage());
}
Polynomial user = null;
try {
user = parse(ouf.nextLine());
} catch (ParseException e) {
return outcome(WA, e.getMessage());
}
if (!jury.equals(user)) {
return outcome(WA, "Expected " + jury.toString() + " found " + user.toString());
}
return outcome(OK, jury.toString());
}
private Polynomial parse(String s) throws ParseException {
s = compress(s);
if (s.length() > MAX_LENGTH) throw new ParseException("String is too long", -1);
this.s = s + ".";
pos = 0;
Polynomial res = parseExpression();
if (pos != s.length()) {
throw new ParseException("Extra characters after " + pos + ": '" + current() + "'", pos);
}
return res;
}
private Polynomial parseExpression() throws ParseException {
Polynomial res = parseProduct();
while (current() == '+' || current() == '-') {
if (current() == '+') {
next();
res = res.add(parseProduct());
} else {
next();
res = res.subtract(parseProduct());
}
}
return res;
}
private Polynomial parseProduct() throws ParseException {
Polynomial res = parseValue();
while (current() == '*') {
next();
res = res.multiply(parseValue());
}
return res;
}
private Polynomial parseValue() throws ParseException {
if (current() == 'n') {
next();
return N;
} else if (current() == '-') {
next();
return parseValue().negate();
} else if (current() >= '0' && current() <= '9') {
BigInteger p = parseInteger();
BigInteger q = BigInteger.ONE;
if (current() == '/') {
next();
q = parseInteger();
if (q.equals(BigInteger.ZERO)) {
throw new ParseException("Division by zero", pos);
}
}
Polynomial res = new Polynomial();
res.c.add(new Rational(p, q));
return res;
} else if (current() == '(') {
next();
Polynomial res = parseExpression();
if (current() != ')') throw new ParseException("Unexpected " + current() + " instead of )", pos);
next();
return res;
} else {
throw new ParseException("Unexpected " + current(), pos);
}
}
private BigInteger parseInteger() throws ParseException {
if (current() < '0' || current() > '9') throw new ParseException("Unexpected " + current() + " instead of digit", pos);
BigInteger res = BigInteger.valueOf(current() - '0');
next();
while (current() >= '0' && current() <= '9') {
res = res.multiply(BigInteger.TEN).add(BigInteger.valueOf(current() - '0'));
next();
}
return res;
}
private void next() {
pos++;
}
private char current() {
return s.charAt(pos);
}
String s;
int pos;
private String compress(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
return sb.toString();
}
class Polynomial {
List<Rational> c;
public Polynomial(List<Rational> c) {
this.c = c;
while (c.size() > 0 && c.get(c.size() - 1).p.signum() == 0) {
c.remove(c.size() - 1);
}
}
public Polynomial() {
c = new ArrayList<>();
}
public Polynomial negate() {
Polynomial res = new Polynomial();
for (Rational cc : c) {
res.c.add(cc.negate());
}
return res;
}
public Polynomial add(Polynomial o) {
List<Rational> res = new ArrayList<>();
for (int i = 0; i < Math.min(c.size(), o.c.size()); i++) {
res.add(c.get(i).add(o.c.get(i)));
}
for (int i = res.size(); i < c.size(); i++) {
res.add(c.get(i));
}
for (int i = res.size(); i < o.c.size(); i++) {
res.add(o.c.get(i));
}
return new Polynomial(res);
}
public Polynomial subtract(Polynomial o) {
return add(o.negate());
}
public Polynomial multiply(Polynomial o) {
List<Rational> res = new ArrayList<>();
for (int i = 0; i < c.size() + o.c.size() - 1; i++) {
Rational q = new Rational(0, 1);
for (int j = 0; j < c.size(); j++) {
int k = i - j;
if (k >= 0 && k < o.c.size()) {
q = q.add(c.get(j).multiply(o.c.get(k)));
}
}
res. add(q);
}
return new Polynomial(res);
}
@Override
public boolean equals(Object obj) {
Polynomial o = (Polynomial) obj;
if (o.c.size() != c.size()) return false;
for (int i = 0; i < c.size(); i++) {
if (!c.get(i).equals(o.c.get(i))) return false;
}
return true;
}
@Override
public String toString() {
if (c.size() == 0) return "0";
StringBuilder res = new StringBuilder();
boolean first = true;
for (int i = c.size() - 1; i >= 0; i--) {
if (c.get(i).p.signum() != 0) {
if (!first) {
res.append(" ").append(c.get(i).p.signum() > 0 ? "+" : "-").append(" ");
}
first = false;
if (i > 0 && c.get(i).p.abs().equals(BigInteger.ONE) && c.get(i).q.equals(BigInteger.ONE)) {
res.append("n");
for (int j = 0; j < i - 1; j++) {
res.append("*n");
}
} else {
res.append(c.get(i).p.abs());
if (!c.get(i).q.equals(BigInteger.ONE)) {
res.append("/").append(c.get(i).q);
}
for (int j = 0; j < i; j++) {
res.append("*n");
}
}
}
}
return res.toString();
}
}
Polynomial ONE;
Polynomial N;
{
ONE = new Polynomial();
ONE.c.add(new Rational(1, 1));
N = new Polynomial();
N.c.add(new Rational(0, 1));
N.c.add(new Rational(1, 1));
}
class Rational {
BigInteger p;
BigInteger q;
public Rational(BigInteger p, BigInteger q) {
if (q.signum() < 0) {
q = q.negate();
p = p.negate();
}
BigInteger d = p.gcd(q);
this.p = p.divide(d);
this.q = q.divide(d);
}
public Rational(long p, long q) {
this(BigInteger.valueOf(p), BigInteger.valueOf(q));
}
public Rational divide(Rational o) {
return new Rational(p.multiply(o.q), q.multiply(o.p));
}
public Rational multiply(Rational o) {
return new Rational(p.multiply(o.p), q.multiply(o.q));
}
public Rational subtract(Rational o) {
return new Rational(p.multiply(o.q).subtract(o.p.multiply(q)), q.multiply(o.q));
}
@Override
public String toString() {
return p + "/" + q;
}
public Rational negate() {
return new Rational(p.negate(), q);
}
public Rational add(Rational o) {
return new Rational(p.multiply(o.q).add(o.p.multiply(q)), q.multiply(o.q));
}
@Override
public boolean equals(Object o) {
return p.equals(((Rational)o).p) & q.equals(((Rational)o).q);
}
}
}
| 33.38141 | 128 | 0.412194 |
bc5b9ec5a7693b88d1b63297cb72e239beff5e6e | 4,477 | /*
* Copyright 2019 Ericsson, https://www.ericsson.com/en
*
* 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.ericsson.mts.asn1.translator;
import com.ericsson.mts.asn1.ASN1Parser;
import com.ericsson.mts.asn1.BitArray;
import com.ericsson.mts.asn1.BitInputStream;
import com.ericsson.mts.asn1.TranslatorContext;
import com.ericsson.mts.asn1.exception.NotHandledCaseException;
import com.ericsson.mts.asn1.factory.FormatReader;
import com.ericsson.mts.asn1.factory.FormatWriter;
import com.ericsson.mts.asn1.registry.MainRegistry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ReferenceTranslator extends AbstractTranslator {
private AbstractTranslator referencedTranslator;
public AbstractTranslator init(MainRegistry mainRegistry, ASN1Parser.ReferencedTypeContext referencedTypeContext) {
if (referencedTypeContext.definedType().DOT() != null) {
throw new NotHandledCaseException();
}
String identifier = referencedTypeContext.definedType().IDENTIFIER(0).getText();
referencedTranslator = mainRegistry.getTranslatorFromName(identifier);
if (referencedTranslator == null) {
throw new RuntimeException("Can't find translator " + identifier + " , context : " + referencedTypeContext.getText());
}
return this;
}
public AbstractTranslator init(MainRegistry mainRegistry, ASN1Parser.ReferencedTypeContext referencedTypeContext, ASN1Parser.ParameterListContext parameterListContext) {
addParameters(parameterListContext);
return init(mainRegistry, referencedTypeContext);
}
@Override
public final void encode(String name, BitArray s, FormatReader reader, TranslatorContext translatorContext, List<String> parameters) throws Exception {
logger.trace("Enter {} encoder, name {}", this.getClass().getSimpleName(), this.name);
Map<String, String> registry = getRegister(parameters);
List<String> parametersNeeded = referencedTranslator.getParameters();
if (parametersNeeded.isEmpty()) {
referencedTranslator.encode(name, s, reader, translatorContext);
} else {
//Building parameter list to pass to target translator
List<String> inputParameters = new ArrayList<>();
for (String parameter : parametersNeeded) {
inputParameters.add(registry.get(parameter));
}
referencedTranslator.encode(name, s, reader, translatorContext, inputParameters);
}
}
@Override
public final void decode(String name, BitInputStream s, FormatWriter writer, TranslatorContext translatorContext, List<String> parameters) throws Exception {
logger.trace("Enter {} translator, name {}", this.getClass().getSimpleName(), this.name);
Map<String, String> registry = getRegister(parameters);
List<String> parametersNeeded = referencedTranslator.getParameters();
if (parametersNeeded.isEmpty()) {
referencedTranslator.decode(name, s, writer, translatorContext);
} else {
//Building parameter list to pass to target translator
List<String> inputParameters = new ArrayList<>();
for (String parameter : parametersNeeded) {
inputParameters.add(registry.get(parameter));
}
referencedTranslator.decode(name, s, writer, translatorContext, inputParameters);
}
}
}
| 55.9625 | 463 | 0.72973 |
0643ad3bedfde7a9c26de5c174757144714121df | 5,989 | package bptree;
import com.microdb.model.DataBase;
import com.microdb.model.table.DbTable;
import com.microdb.model.row.Row;
import com.microdb.model.table.TableDesc;
import com.microdb.model.table.tablefile.BPTreeTableFile;
import com.microdb.model.field.FieldType;
import com.microdb.model.field.IntField;
import com.microdb.operator.Delete;
import com.microdb.operator.PredicateEnum;
import com.microdb.operator.SeqScan;
import com.microdb.operator.bptree.BPTreeScan;
import com.microdb.operator.bptree.IndexPredicate;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static org.junit.Assert.assertFalse;
/**
* TODO
*
* @author zhangjw
* @version 1.0
*/
public class BPTreeTest {
public DataBase dataBase;
private TableDesc personTableDesc;
@Before
public void initDataBase() {
DataBase dataBase = DataBase.getInstance();
// 创建数据库文件
String fileName = UUID.randomUUID().toString();
// 表中有两个int类型字段,person_id 字段为索引字段
List<TableDesc.Attribute> attributes = Arrays.asList(new TableDesc.Attribute("person_id", FieldType.INT),
new TableDesc.Attribute("person_age", FieldType.INT));
File file = new File(fileName);
file.deleteOnExit();
TableDesc tableDesc = new TableDesc(attributes);
BPTreeTableFile bpTreeTableFile = new BPTreeTableFile(file, tableDesc, 0);
dataBase.addTable(bpTreeTableFile, "t_person");
this.dataBase = dataBase;
personTableDesc = tableDesc;
}
/**
* t_person表 Leaf页可存储453行记录,Internal页可以存储455个索引
*/
@Test
public void testInsert() throws IOException {
DbTable t_person = dataBase.getDbTableByName("t_person");
long l1 = System.currentTimeMillis();
int num = 453;
// 第一页
for (int i = 0; i < num; i++) {
Row row = new Row(personTableDesc);
row.setField(0, new IntField(i));
row.setField(1, new IntField(18));
t_person.insertRow(row);
}
System.out.println("插入" + num + "条记录,耗时(ms)" + (System.currentTimeMillis() - l1));
// 第2页,触发页分裂
// 测试 leaf页分裂逻辑
for (int i = 0; i < 1; i++) {
Row row = new Row(personTableDesc);
row.setField(0, new IntField(i));
row.setField(1, new IntField(18));
t_person.insertRow(row);
}
//
for (int i = 0; i < num; i++) {
Row row = new Row(personTableDesc);
row.setField(0, new IntField(i));
row.setField(1, new IntField(18));
t_person.insertRow(row);
}
}
/**
* t_person表 Leaf页可存储453行记录,Internal页可以存储455个索引
* <p>
* 需要>455个leaf页来触发Internal页分裂
*/
@Test
public void testInternalPageSplit() throws IOException {
DbTable t_person = dataBase.getDbTableByName("t_person");
long l1 = System.currentTimeMillis();
int num = 453;
for (int j = 0; j < 456; j++) {
for (int i = 0; i < num; i++) {
Row row = new Row(personTableDesc);
row.setField(0, new IntField(i));
row.setField(1, new IntField(18));
t_person.insertRow(row);
}
}
System.out.println("插入" + 453 * num + "条记录,耗时(ms)" + (System.currentTimeMillis() - l1));
}
/**
* 将Page的默认大小设置为48字节,便于测测试
*/
@Test
public void testInternalPageSplitWithSmallPage() throws IOException {
DbTable t_person = dataBase.getDbTableByName("t_person");
// 完成内部页分裂
for (int i = 1; i < 14; i++) {
Row row = new Row(personTableDesc);
row.setField(0, new IntField(i));
row.setField(1, new IntField(18));
t_person.insertRow(row);
}
// 全部删除
SeqScan scan = new SeqScan(t_person.getTableId());
Delete delete = new Delete(scan);
delete.loopDelete();
}
/**
* BPTreeScan
* 带索引条件的扫描
*/
@Test
public void BPTreeScan() throws IOException {
DbTable person = dataBase.getDbTableByName("t_person");
long l1 = System.currentTimeMillis();
int num = 12;
// 完成内部页分裂
for (int i = 1; i < 14; i++) {
Row row = new Row(personTableDesc);
row.setField(0, new IntField(i));
row.setField(1, new IntField(18));
person.insertRow(row);
}
// 带索引的扫描
IndexPredicate predicate =
new IndexPredicate(PredicateEnum.GREATER_THAN_OR_EQ, new IntField(5));
BPTreeScan scan = new BPTreeScan(person.getTableId(), predicate);
scan.open();
while (scan.hasNext()) {
Row next = scan.next();
System.out.println(next);
}
// 不带索引的扫描
BPTreeScan scanNoIndex = new BPTreeScan(person.getTableId(),null);
scanNoIndex.open();
while (scanNoIndex.hasNext()) {
Row next = scanNoIndex.next();
System.out.println(next);
}
}
/**
* BPTreeScan
* 带索引条件的扫描
*/
@Test
public void BPTreeDelete() throws IOException {
DbTable person = dataBase.getDbTableByName("t_person");
long l1 = System.currentTimeMillis();
int num = 12;
// 完成内部页分裂
// FIXME 3000 以内数据能跑通测试,页重分布还是有问题
for (int i = 1; i < 1000; i++) {
Row row = new Row(personTableDesc);
row.setField(0, new IntField(i));
row.setField(1, new IntField(18));
person.insertRow(row);
}
BPTreeScan scan = new BPTreeScan(person.getTableId(), null);
scan.open();
Row next = scan.next();
// 全部删
Delete delete = new Delete(scan);
delete.loopDelete();
scan.open();
assertFalse(scan.hasNext());
}
}
| 28.932367 | 113 | 0.584906 |
97b0d248cdfec72b26fc7de534f70e36fd206f07 | 608 | /**
* Copyright Liaison Technologies, Inc. All rights reserved.
*
* This software is the confidential and proprietary information of
* Liaison Technologies, Inc. ("Confidential Information"). You shall
* not disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Liaison Technologies.
*/
package com.liaison.mailbox.dtdm.dao;
/**
* Interface to hold the persistence unit name for config time database.
*
* @author OFS
*/
public interface MailboxDTDMDAO {
String PERSISTENCE_UNIT_NAME = "mailbox-dtdm";
}
| 27.636364 | 72 | 0.754934 |
b5ebf2a7a54019a6e8550b675752b0072f1f8ccc | 2,202 | package org.ideaccum.libs.commons.config;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* プロパティアクセスキーを列挙形式のクラスとして提供します。<br>
* <p>
* プロパティキーのリファクタリング効率を上げるために文字列形式でのアクセスを隠蔽化してクラスフィールドとして提供します。<br>
* このクラスはプロパティアクセスキークラスの上位抽象クラスであり、実際のプロパティキークラスはこれを継承して設置します。<br>
* 継承関係のクラス構造を前提としたプロパティキークラスとしているため、列挙型クラスとして提供せず、列挙形式のクラスとして提供します。<br>
* 尚、サブクラスとしてプロパティアクセスキークラスを実装する際は{@link #ConfigName(String)}コンストラクタをprotectedレベルで設置して下さい(あくまでも列挙フィールドインスタンス化の目的であり、publicとはしない)。<br>
* </p>
*
*<!--
* 更新日 更新者 更新内容
* 2010/07/03 Kitagawa 新規作成
* 2018/05/02 Kitagawa 再構築(SourceForge.jpからGitHubへの移行に併せて全面改訂)
* 2019/10/29 Kitagawa ConfigNameに対してプロパティ定義値型を限定する仕様に変更
*-->
*/
public abstract class ConfigName<T> implements Serializable {
/** ロックオブジェクト */
private static Object lock = new Object();
/** プロパティキー */
private String key;
/** プロパティパーサークラス */
private Class<? extends ConfigValueParser<?>> parserClass;
/** インスタンスキャッシュ */
private static Map<String, ConfigName<?>> instances = new HashMap<>();
/**
* コンストラクタ<br>
* @param key プロパティキー
* @param parserClass プロパティパーサークラス
*/
protected ConfigName(String key, Class<? extends ConfigValueParser<T>> parserClass) {
synchronized (lock) {
this.key = key;
this.parserClass = parserClass;
instances.put(key, this);
}
}
/**
* クラス情報を文字列で定義します。<br>
* @return クラス情報文字列
* @see java.lang.Object#toString()
*/
@Override
public final String toString() {
return key;
}
/**
* 定義列挙型クラスインスタンスのプロパティキー文字列を取得します。<br>
* @return プロパティキー文字列
*/
public final String getKey() {
return key;
}
/**
* プロパティパーサークラスを取得します。<br>
* @return プロパティパーサークラス
*/
protected final Class<? extends ConfigValueParser<?>> getParserClass() {
return parserClass;
}
/**
* 指定されたプロパティキーのプロパティアクセスキーインスタンスを提供します。<br>
* 管理されていないプロパティキーの場合はnullが返却されます。<br>
* @param key プロパティキー文字列
* @return プロパティアクセスキーインスタンス
*/
public static final ConfigName<?> valueOf(String key) {
if (!instances.containsKey(key)) {
return null;
}
return instances.get(key);
}
}
| 24.741573 | 134 | 0.676203 |
79f7138059382d0cea8a0e3d15bc72421a4e14b0 | 2,144 | package com.myplace.myplace;
/**
* Created by jsepr on 2017-05-15.
*/
import android.content.Context;
import com.myplace.myplace.models.Message;
import com.myplace.myplace.models.Room;
import static android.support.test.InstrumentationRegistry.getContext;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.InstrumentationRegistry.getTargetContext;
import static junit.framework.Assert.assertEquals;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.RenamingDelegatingContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Created by jsepr on 2017-05-15.
*/
@RunWith(AndroidJUnit4.class)
public class RoomInstrumentedTest {
private static final String TEST_DATABASE = "test_db";
private static int TEST_ROOM_ID = 123;
private static String TEST_ROOM_NAME = "TestRoom";
private static String TEST_NAME = "Anders";
private static String TEST_MESSAGE = "Hej123";
private Context testContext;
private RoomDbHelper db = null;
@Before
public void setup() {
RoomDbHelper.DATABASE_NAME = TEST_DATABASE;
Message testMessage = new Message(TEST_NAME, TEST_MESSAGE);
testContext = getInstrumentation().getTargetContext();
db = new RoomDbHelper(testContext);
db.createRoomTable(TEST_ROOM_ID, TEST_ROOM_NAME);
db.addMessage(TEST_ROOM_ID, testMessage);
}
@Test
public void getLastMessageTest() {
Room room = new Room(TEST_ROOM_ID, TEST_ROOM_NAME);
String lastMessage = room.getLastMessageText(testContext);
assertEquals(lastMessage, TEST_MESSAGE);
}
@Test
public void getLastSenderTest() {
Room room = new Room(TEST_ROOM_ID, TEST_ROOM_NAME);
String lastSender = room.getLastSender(testContext);
assertEquals(lastSender, TEST_NAME);
}
@After
public void teardown() {
RoomDbHelper.DATABASE_NAME = TEST_DATABASE;
db.dropAllTables();
}
} | 29.777778 | 78 | 0.729478 |
43b6ca8eb5ca7c5521ceacd55aaac3b77e1449e6 | 538 | package es.agustruiz.deadpoolcomics.presentation;
import android.os.Handler;
import android.os.Looper;
import javax.inject.Inject;
import javax.inject.Singleton;
import es.agustruiz.deadpoolcomics.domain.executor.PostExecutionThread;
@Singleton
public class UIThread implements PostExecutionThread {
private final Handler mHandler;
@Inject
public UIThread() {
mHandler = new Handler(Looper.getMainLooper());
}
@Override
public void post(Runnable runnable) {
mHandler.post(runnable);
}
}
| 20.692308 | 71 | 0.741636 |
4f2487144c0ff8b46234fc4ee951b585e14af472 | 498 | package GraceJava;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
public class SQLConnection {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getConnection(){
Connection conn=null;
try{
conn=dataSource.getConnection();
}
catch (SQLException e){
e.printStackTrace();
}
return conn;
}
}
| 19.153846 | 51 | 0.746988 |
cf03030d8e769381f3cb04b331f9356d5a507a5f | 1,642 | package com.thinkbiganalytics.metadata.jpa.sla;
/*-
* #%L
* thinkbig-operational-metadata-jpa
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.thinkbiganalytics.jpa.BaseJpaId;
import com.thinkbiganalytics.metadata.api.feed.OpsManagerFeed;
import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement;
import java.io.Serializable;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* The primary key for a {@link OpsManagerFeed}
*/
@Embeddable
public class ServiceLevelAgreementDescriptionId extends BaseJpaId implements ServiceLevelAgreement.ID, Serializable {
private static final long serialVersionUID = 6965221468619613881L;
@Column(name = "SLA_ID")
private UUID uuid;
public ServiceLevelAgreementDescriptionId() {
}
public ServiceLevelAgreementDescriptionId(Serializable ser) {
super(ser);
}
@Override
public UUID getUuid() {
return this.uuid;
}
@Override
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
}
| 26.918033 | 117 | 0.732643 |
9804d8fdf3a905b07409e7e64bf5bfd2e9a0d802 | 4,395 | import java.util.*;
public class findDeepNodesParent {
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
private class Solution {
ArrayList<TreeNode> deepParent;
int maxDepth;
public TreeNode subtreeWithAllDeepest(TreeNode root) {
if (root == null) return null;
if (root.left == null && root.right == null) return root;
deepParent = new ArrayList<>();
maxDepth = -1;
getMaxDepth(root, null, 0);
addMaxDepth(root, 0);
return findDeepParent(root);
}
boolean cover(TreeNode root, TreeNode node)
{
if (root == null) return false;
if (root.val == node.val) return true;
if (cover(root.left, node)) return true;
if (cover(root.right, node)) return true;
return false;
}
boolean coverAll(TreeNode at)
{
for (TreeNode node : deepParent)
if (!cover(at, node))
return false;
return true;
}
TreeNode findDeepParent(TreeNode at)
{
if (at == null) return null;
boolean left = coverAll(at.left);
boolean right = coverAll(at.right);
if (left) return findDeepParent(at.left);
if (right) return findDeepParent(at.right);
return at;
}
void addMaxDepth(TreeNode at, int depth)
{
if (at == null) return;
if (depth == maxDepth)
deepParent.add(at);
addMaxDepth(at.left, depth + 1);
addMaxDepth(at.right, depth + 1);
}
int getMaxDepth(TreeNode at, TreeNode parent, int depth)
{
if (at == null) return depth - 1;
if (at.left == null && at.right == null) return depth;
int ldepth = getMaxDepth(at.left, at, depth + 1);
int rdepth = getMaxDepth(at.right, at, depth + 1);
maxDepth = Math.max(maxDepth, Math.max(ldepth, rdepth));
return depth;
}
}
private class Solution_opt {
TreeNode deepParent;
int maxDepth;
public TreeNode subtreeWithAllDeepest(TreeNode root) {
deepParent = null;
maxDepth = -1;
getMaxDepth(root, 0);
return deepParent;
}
int getMaxDepth(TreeNode at, int depth)
{
if (at == null) return depth;
int ldepth = getMaxDepth(at.left, depth + 1);
int rdepth = getMaxDepth(at.right, depth + 1);
int atdepth = Math.max(ldepth, rdepth);
maxDepth = Math.max(maxDepth, atdepth);
if (ldepth == maxDepth && rdepth == maxDepth)
deepParent = at;
return atdepth;
}
}
private class Solution_opt1 {
private class Pair<T, K> {
final T key;
final K value;
public Pair(T key, K value) {
this.key = key;
this.value = value;
}
public K getValue() {
return value;
}
public T getKey() {
return key;
}
}
public TreeNode subtreeWithAllDeepest(TreeNode root) {
return height(root).getValue();
}
private Pair<Integer, TreeNode> height(TreeNode root) {
if (root == null) return new Pair(0, null);
Pair<Integer, TreeNode> left = height(root.left);
Pair<Integer, TreeNode> right = height(root.right);
int leftHeight = left.getKey();
int rightHeight = right.getKey();
if (leftHeight == rightHeight) {
return new Pair(leftHeight + 1, root);
}
else if (leftHeight < rightHeight) {
return new Pair(rightHeight + 1, right.getValue());
}
else {
return new Pair(leftHeight + 1, left.getValue());
}
}
}
}
| 26.005917 | 69 | 0.495336 |
816178c25aefd8d36c68a08f1204c3fce5049d42 | 1,929 | import java.util.Arrays;
public class Solution {
public int minDistance(String word1, String word2) {
// 由于 word1.charAt(i) 操作会去检查下标是否越界,因此
// 在 Java 里,将字符串转换成字符数组是常见额操作
char[] word1Array = word1.toCharArray();
char[] word2Array = word2.toCharArray();
int len1 = word1Array.length;
int len2 = word2Array.length;
// 多开一行一列是为了保存边界条件,即字符长度为 0 的情况,这一点在字符串的动态规划问题中比较常见
int[][] dp = new int[len1 + 1][len2 + 1];
// 初始化:当 word 2 长度为 0 时,将 word1 的全部删除即可
for (int i = 1; i <= len1; i++) {
dp[i][0] = i;
}
// 当 word1 长度为 0 时,就插入所有 word2 的字符即可
for (int j = 1; j <= len2; j++) {
dp[0][j] = j;
}
// 注意:填写 dp 数组的时候,由于初始化多设置了一行一列,横纵坐标有个偏移
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
// 这是最佳情况
if (word1Array[i - 1] == word2Array[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
continue;
}
// 否则在以下三种情况中选出步骤最少的,这是「动态规划」的「最优子结构」
// 1、在下标 i 处插入一个字符
int insert = dp[i][j - 1] + 1;
// 2、替换一个字符
int replace = dp[i - 1][j - 1] + 1;
// 3、删除一个字符
int delete = dp[i - 1][j] + 1;
dp[i][j] = Math.min(Math.min(insert, replace), delete);
}
}
// 打印状态表格进行调试
// for (int i = 0; i <=len1; i++) {
// System.out.println(Arrays.toString(dp[i]));
// }
return dp[len1][len2];
}
public static void main(String[] args) {
String word1 = "horse";
String word2 = "ros";
// String word1 = "aaaa";
// String word2 = "aaaa";
Solution solution = new Solution();
int res = solution.minDistance(word1, word2);
System.out.println(res);
}
}
| 28.791045 | 71 | 0.459824 |
de5589a42cc2f8d1e66a5003710b6f193bc623ed | 205 | package il.ac.bgu.cs.bp.bprobot.robot.grovewrappers.set;
/**
* Create a wrapper for all the sensors that have set function
*/
public interface IGroveSensorSetWrapper {
boolean set(boolean value);
}
| 22.777778 | 62 | 0.75122 |
385730dfb1fb93c608b891b225d039504d517092 | 457 | package dao;
import org.json.JSONArray;
import repository.ProductRepository;
import repository.UserRepository;
import javax.inject.Inject;
import java.sql.SQLException;
public class UserDao {
private UserRepository repository;
@Inject
public UserDao(UserRepository repository) {
this.repository = repository;
}
public JSONArray getById(Long user_id) throws SQLException {
return repository.getById(user_id);
}
}
| 20.772727 | 64 | 0.743982 |
9835cbaced56e67fc897c1a9e86207f0a856151b | 4,257 | /*
* Copyright 2016-2019 The Sponge authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openksavi.sponge.kotlin;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.openksavi.sponge.ProcessorOnInitCallback;
import org.openksavi.sponge.core.correlator.BaseCorrelatorBuilder;
import org.openksavi.sponge.correlator.Correlator;
import org.openksavi.sponge.correlator.CorrelatorOnAcceptAsFirstCallback;
import org.openksavi.sponge.correlator.CorrelatorOnDurationCallback;
import org.openksavi.sponge.correlator.CorrelatorOnEventCallback;
/**
* Kotlin-specific implementation of a correlator builder.
*/
public class KCorrelatorBuilder extends BaseCorrelatorBuilder {
public KCorrelatorBuilder(String name) {
super(name);
}
@Override
public KCorrelatorBuilder withName(String name) {
return (KCorrelatorBuilder) super.withName(name);
}
@Override
public KCorrelatorBuilder withLabel(String label) {
return (KCorrelatorBuilder) super.withLabel(label);
}
@Override
public KCorrelatorBuilder withDescription(String description) {
return (KCorrelatorBuilder) super.withDescription(description);
}
@Override
public KCorrelatorBuilder withVersion(Integer version) {
return (KCorrelatorBuilder) super.withVersion(version);
}
@Override
public KCorrelatorBuilder withFeatures(Map<String, Object> features) {
return (KCorrelatorBuilder) super.withFeatures(features);
}
@Override
public KCorrelatorBuilder withFeature(String name, Object value) {
return (KCorrelatorBuilder) super.withFeature(name, value);
}
@Override
public KCorrelatorBuilder withCategory(String category) {
return (KCorrelatorBuilder) super.withCategory(category);
}
@Override
public KCorrelatorBuilder withEvents(List<String> eventNames) {
return (KCorrelatorBuilder) super.withEvents(eventNames);
}
public KCorrelatorBuilder withEvents(String... eventNames) {
return withEvents(Arrays.asList(eventNames));
}
@Override
public KCorrelatorBuilder withEvent(String eventName) {
return (KCorrelatorBuilder) super.withEvent(eventName);
}
@Override
public KCorrelatorBuilder withDuration(Duration duration) {
return (KCorrelatorBuilder) super.withDuration(duration);
}
@Override
public KCorrelatorBuilder withSynchronous(Boolean synchronous) {
return (KCorrelatorBuilder) super.withSynchronous(synchronous);
}
@Override
public KCorrelatorBuilder withMaxInstances(int maxInstances) {
return (KCorrelatorBuilder) super.withMaxInstances(maxInstances);
}
@Override
public KCorrelatorBuilder withInstanceSynchronous(boolean instanceSynchronous) {
return (KCorrelatorBuilder) super.withInstanceSynchronous(instanceSynchronous);
}
@Override
public KCorrelatorBuilder withOnInit(ProcessorOnInitCallback<Correlator> onInitCallback) {
return (KCorrelatorBuilder) super.withOnInit(onInitCallback);
}
@Override
public KCorrelatorBuilder withOnAcceptAsFirst(CorrelatorOnAcceptAsFirstCallback onAcceptAsFirstCallback) {
return (KCorrelatorBuilder) super.withOnAcceptAsFirst(onAcceptAsFirstCallback);
}
@Override
public KCorrelatorBuilder withOnEvent(CorrelatorOnEventCallback onEventCallback) {
return (KCorrelatorBuilder) super.withOnEvent(onEventCallback);
}
@Override
public KCorrelatorBuilder withOnDuration(CorrelatorOnDurationCallback onDurationCallback) {
return (KCorrelatorBuilder) super.withOnDuration(onDurationCallback);
}
}
| 33 | 110 | 0.752173 |
e64ddc5cdd33db9f5013d0778943533a376d5e58 | 2,208 | /*
* Copyright (c) 2017 org.hrodberaht
*
* 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.hrodberaht.injection.plugin.datasource.embedded;
import org.hrodberaht.injection.plugin.datasource.embedded.vendors.HsqlBDDataSourceConfigurationRestorable;
import org.hrodberaht.injection.plugin.junit.ResourceWatcher;
import org.hrodberaht.injection.plugin.junit.datasource.DataSourceProxyInterface;
import org.hrodberaht.injection.plugin.junit.datasource.ProxyResourceCreator;
public class DataSourceConfigFactory {
private DataSourceProxyInterface dataSourceProxyInterface;
private ResourceWatcher resourceWatcher;
private String dbName;
public DataSourceConfigFactory(DataSourceProxyInterface dataSourceProxyInterface,
ResourceWatcher resourceWatcher, String dbName) {
this.dataSourceProxyInterface = dataSourceProxyInterface;
this.resourceWatcher = resourceWatcher;
this.dbName = dbName;
}
public DataSourceConfiguration createConfiguration(
ProxyResourceCreator.DataSourceProvider provider,
ProxyResourceCreator.DataSourcePersistence persistence) {
if (provider == ProxyResourceCreator.DataSourceProvider.HSQLDB) {
if (persistence == ProxyResourceCreator.DataSourcePersistence.MEM) {
return new HsqlBDDataSourceConfigurationRestorable(dbName, null);
} else if (persistence == ProxyResourceCreator.DataSourcePersistence.RESTORABLE) {
return new HsqlBDDataSourceConfigurationRestorable(dbName, resourceWatcher);
}
}
throw new RuntimeException("not supported databasetype");
}
}
| 41.660377 | 107 | 0.75 |
b48d2c6873c448a1fd96c1a9898661c1f95d4825 | 680 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.javahippie.jax2020.checkout;
import javax.ws.rs.core.Response;
import org.eclipse.microprofile.faulttolerance.ExecutionContext;
import org.eclipse.microprofile.faulttolerance.FallbackHandler;
/**
*
* @author zoeller
*/
public class CheckoutFallbackHandler implements FallbackHandler<Response> {
@Override
public Response handle(ExecutionContext ec) {
return Response.status(500).entity("Could not complete Request. Please try again later").build();
}
}
| 28.333333 | 105 | 0.757353 |
4d91e698893b33948f1493af960f4e628b5a92d7 | 728 | package com.bakdata.conquery.models.concepts.conditions;
import java.util.HashSet;
import java.util.Map;
import org.hibernate.validator.constraints.NotEmpty;
import com.bakdata.conquery.io.cps.CPSType;
import com.bakdata.conquery.util.CalculatedValue;
import lombok.Getter;
import lombok.Setter;
/**
* This condition requires each value to be exactly as given in the list.
*/
@CPSType(id="EQUAL", base=CTCondition.class)
public class EqualCondition implements CTCondition {
private static final long serialVersionUID = 1L;
@Setter @Getter @NotEmpty
private HashSet<String> values;
@Override
public boolean matches(String value, CalculatedValue<Map<String, Object>> rowMap) {
return values.contains(value);
}
} | 25.103448 | 84 | 0.784341 |
974e3dcb4f0994feb463dc467d298530429407b6 | 673 | package com.dev.base.utils.bean;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.PropertyUtilsBean;
/**
*
* <p>Title: 重写,对枚举的支持,将枚举反射为string</p>
* <p>Description: 描述(简要描述类的职责、实现方式、使用注意事项等)</p>
* <p>CreateDate: 2015年8月21日下午2:44:52</p>
*/
public class CustPropertyUtilsBean extends PropertyUtilsBean{
@Override
public Object getSimpleProperty(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException{
Object object = super.getSimpleProperty(bean, name);
if (object instanceof Enum) {
object = object.toString();
}
return object;
}
}
| 25.884615 | 69 | 0.732541 |
07b84478560319d3481859d4744dcd3860404e72 | 910 | import java.util.Scanner;
public class Filepath {
public static void main(String[] args) {
String str, path, fileName, fileType;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter filepath to get the folder path, file name & extension.");
str = sc.next();
//storing the folder path in variable path
path = str.substring(0, str.lastIndexOf("\\"));
//storing the file name using substring(), indexOf() & lastIndexOf() fns on str
fileName = str.substring((char)(str.lastIndexOf("\\")+1), (str.indexOf(".")));
//storing the file type using indexOf() & length() fns on String str
fileType = str.substring((char)(str.indexOf(".")+1), str.length());
System.out.println("Path: "+path);
System.out.println("File name: "+fileName);
System.out.println("Extension: "+fileType);
}
}
| 45.5 | 99 | 0.615385 |
2239509990850b97002680ed7764d906999dd8c1 | 763 | package exnihilocreatio.client.models;
import exnihilocreatio.ModBlocks;
import exnihilocreatio.util.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.color.BlockColors;
import net.minecraft.client.renderer.color.IBlockColor;
public class ModColorManager {
private static final Minecraft MINECRAFT = Minecraft.getMinecraft();
public static void registerColorHandlers() {
registerBlockColorHandlers(MINECRAFT.getBlockColors());
}
private static void registerBlockColorHandlers(BlockColors blockColors) {
IBlockColor leafColorHandler = (state, worldIn, pos, tintIndex) -> Util.whiteColor.toInt();
blockColors.registerBlockColorHandler(leafColorHandler, ModBlocks.infestedLeaves);
}
}
| 34.681818 | 99 | 0.78768 |
123ccab12f1c6aa1bf2efb229548af64de164f47 | 4,481 | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.plugin.notification.http;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
import org.jooby.Result;
import org.jooby.Results;
import org.jooby.Status;
import org.killbill.billing.notification.plugin.api.ExtBusEventType;
import org.killbill.billing.plugin.notification.dao.gen.tables.pojos.EmailNotificationsConfiguration;
import org.killbill.billing.plugin.notification.dao.ConfigurationDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class EmailNotificationService
{
private static final Logger logger = LoggerFactory.getLogger(EmailNotificationService.class);
private EmailNotificationService(){}
public static Result getEventTypes(final ConfigurationDao dao, final List<UUID> kbAccountId, final UUID kbTenantId)
{
logger.debug(String.format("Enters get event types for %s accounts - %s",kbAccountId.size(),kbTenantId));
List<EmailNotificationsConfiguration> eventTypes = null;
try {
eventTypes = dao.getEventTypes(kbAccountId, kbTenantId);
} catch (SQLException e) {
logger.error(e.getMessage());
return Results.with(e.getMessage(), Status.SERVER_ERROR);
}
return eventTypes == null || eventTypes.size() == 0? Results.with(Status.NOT_FOUND) : Results.json(eventTypes);
}
public static Result getEventTypesPerAccount(final ConfigurationDao dao, final UUID kbAccountId, final UUID kbTenantId)
{
logger.debug(String.format("Enters get event types %s - %s",kbAccountId,kbTenantId));
List<EmailNotificationsConfiguration> eventTypes = null;
try {
eventTypes = dao.getEventTypesPerAccount(kbAccountId, kbTenantId);
} catch (SQLException e) {
logger.error(e.getMessage());
return Results.with(e.getMessage(), Status.SERVER_ERROR);
}
return eventTypes == null || eventTypes.size() == 0? Results.with(Status.NOT_FOUND) : Results.json(eventTypes);
}
public static Result getEventTypePerAccount(final ConfigurationDao dao, final UUID kbAccountId, final UUID kbTenantId, final ExtBusEventType eventType )
{
logger.debug(String.format("Enters get event type %s - %s",kbAccountId,kbTenantId));
EmailNotificationsConfiguration eventTypeRsp = null;
try {
eventTypeRsp = dao.getEventTypePerAccount(kbAccountId, kbTenantId, eventType);
} catch (SQLException e) {
logger.error(e.getMessage());
return Results.with(e.getMessage(), Status.SERVER_ERROR);
}
return eventTypeRsp == null ? Results.with(Status.NOT_FOUND) : Results.json(eventTypeRsp);
}
public static Result doUpdateEventTypePerAccount(final ConfigurationDao dao, final UUID kbAccountId,
final UUID kbTenantId, final List<ExtBusEventType> eventTypes,
final DateTime utcNow)
{
logger.debug(String.format("Enters update event types per account %s",kbAccountId));
if (kbTenantId == null)
{
return Results.with("No tenant specified",Status.NOT_FOUND);
}
if (kbAccountId == null)
{
return Results.with("No account specified",Status.NOT_FOUND);
}
try {
dao.updateConfigurationPerAccount(kbAccountId,kbTenantId,eventTypes,utcNow);
} catch (SQLException e) {
logger.error(e.getMessage());
return Results.with(e.getMessage(), Status.SERVER_ERROR);
}
return Results.with(Status.CREATED);
}
}
| 39.654867 | 156 | 0.686008 |
2b5e4903bf573354386459dd6a7b201bae80006c | 2,725 | package com.refinitiv.eta.json.converter;
import com.fasterxml.jackson.databind.JsonNode;
import com.refinitiv.eta.codec.*;
import com.refinitiv.eta.json.util.JsonFactory;
class JsonXmlConverter extends AbstractContainerTypeConverter {
JsonXmlConverter(JsonAbstractConverter converter) {
super(converter);
dataTypes = new int[] { DataTypes.XML };
}
@Override
Object getContainerObject() {
return JsonFactory.createBuffer();
}
@Override
void releaseContainer(Object type) {
JsonFactory.releaseBuffer((Buffer) type);
}
@Override
protected int decodeEntry(DecodeIterator decIter, Object entryObj) {
return CodecReturnCodes.FAILURE;
}
@Override
protected boolean writeContent(DecodeIterator decIter, JsonBuffer outBuffer, JsonConverterError error, Object container) {
return BasicPrimitiveConverter.writeAsciiString((Buffer) container, outBuffer, error);
}
@Override
protected int decodeContainer(DecodeIterator decIter, Object setDb, Object container) {
Buffer buff = (Buffer) container;
buff.clear();
return buff.decode(decIter);
}
@Override
protected boolean writeEntry(DecodeIterator decIterator, JsonBuffer outBuffer, Object localSetDb, JsonConverterError error, Object entryObj, Object container) {
return false;
}
@Override
void encodeRWF(JsonNode node, String key, EncodeIterator iter, JsonConverterError error) {
if (!node.isTextual()) {
error.setError(JsonConverterErrorCodes.JSON_ERROR_UNEXPECTED_VALUE, "Expected string value, found type " + node.getNodeType().toString());
return;
}
Buffer xmlBuf = JsonFactory.createBuffer();
Buffer dataBuf = JsonFactory.createBuffer();
try {
xmlBuf.clear();
dataBuf.clear();
converter.getPrimitiveHandler(DataTypes.ASCII_STRING).decodeJson(node, xmlBuf, error);
if (error.isFailed())
return;
if (iter.encodeNonRWFInit(dataBuf) < CodecReturnCodes.SUCCESS) {
error.setError(JsonConverterErrorCodes.JSON_ERROR, "Encoding failed");
return;
}
dataBuf.data().put(xmlBuf.data().array(), xmlBuf.position(), xmlBuf.length());
if (iter.encodeNonRWFComplete(dataBuf, true) < CodecReturnCodes.SUCCESS) {
error.setError(JsonConverterErrorCodes.JSON_ERROR, "Failed to complete XML encoding to RWF");
return;
}
} finally {
JsonFactory.releaseBuffer(xmlBuf);
JsonFactory.releaseBuffer(dataBuf);
}
return;
}
}
| 33.641975 | 164 | 0.66055 |
9144bd930344cb8246d7d2ba7ed2fa380356a906 | 1,333 | /**
* @authour Akhash Ramamurthy
*/
package modifiedBinarySearch;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* @author Akhash Ramamurthy
*
*/
public class PeakIndexInMountainArray_852 {
public int peakIndexInMountainArray(int[] a) {
int left=0, right=a.length-1;
while(left < right) {
int mid = left + (right-left)/2;
if (a[mid] > a[mid+1]) { //we are in descending side. peak can be mid or before mid.
right = mid;
}else { // we are in ascending side. Peak will be after mid only.
left = mid+1;
}
}
return a[left]; // at the end of the while loop, 'start == end'
}
@Test
public void test_01() {
int[] arr = new int[] {1, 3, 8, 12, 4, 2};
int res = 12;
assertEquals(res, peakIndexInMountainArray(arr));
}
}
/**
* Problem Statement #
Find the maximum value in a given Bitonic array. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1].
Example 1:
Input: [1, 3, 8, 12, 4, 2]
Output: 12
Explanation: The maximum number in the input bitonic array is '12'.
Example 2:
Input: [3, 8, 3, 1]
Output: 8
Example 3:
Input: [1, 3, 8, 12]
Output: 12
Example 4:
Input: [10, 9, 8]
Output: 10
Try it yourself #
*/ | 21.852459 | 247 | 0.668417 |
59b91eed3468afa0b7718e4c15dda1e839c48eed | 7,774 | /*
* Copyright 2019 Jonathan West
*
* 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.zhapimirror;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import com.zhapi.ZenHubClient;
/**
* Maintains a list of all of the repositories/issues that are currently waiting
* to be processed by a worker thread.
*
* The ZHWorkerThread thread may call an instance of this class, in order to:
* add additional work, query if work is available, and poll for new work by
* type.
*/
public class ZHWorkQueue {
private final Object lock = new Object();
private final List<ZHRepositoryContainer> repositories_synch_lock = new ArrayList<>();
private final List<ZHIssueContainer> issues_synch_lock = new ArrayList<>();
/** Whether a resource is in the work queue; the map value is not used. */
private final Map<String /* unique key for each resource */, Boolean> resourcesMap = new HashMap<>();
private final GitHub githubClient;
private final ZenHubClient zenhubClient;
private final ZHDatabase database;
private final ZHFilter filter;
private static final ZHLog log = ZHLog.getInstance();
ZHWorkQueue(ZenHubClient zenhubClient, GitHub githubClient, ZHDatabase database, ZHFilter filter) {
this.githubClient = githubClient;
this.zenhubClient = zenhubClient;
this.database = database;
this.filter = filter;
}
void addRepository(GHOwner owner, GHRepository repo, String repoName, long repoId) {
if (filter != null && !filter.processRepo(owner, repoName)) {
return;
}
ZHRepositoryContainer r = new ZHRepositoryContainer(owner, repo, repoName, repoId);
String key = r.getKey();
// Prevent duplicates in the work queue
if (resourcesMap.containsKey(key)) {
return;
}
log.logDebug("Adding repository: " + repoName);
synchronized (lock) {
resourcesMap.put(key, true);
repositories_synch_lock.add(r);
lock.notify();
}
}
void addRepositoryFromRetry(ZHRepositoryContainer container) {
String key = container.getKey();
// Prevent duplicates in the work queue
if (resourcesMap.containsKey(key)) {
return;
}
log.logDebug("Adding repository (from retry): " + container.getRepoName());
synchronized (lock) {
resourcesMap.put(key, true);
repositories_synch_lock.add(container);
lock.notify();
}
}
void addIssue(GHOwner owner, GHRepository repo, GHIssue issue) {
if (filter != null && !filter.processIssue(owner, repo.getName(), issue.getNumber())) {
return;
}
ZHIssueContainer c = new ZHIssueContainer(owner, repo, issue);
String key = c.getKey();
// Prevent duplicates in the work queue
if (resourcesMap.containsKey(key)) {
return;
}
log.logDebug("Adding issue: " + repo.getName() + " " + issue.getNumber());
synchronized (lock) {
issues_synch_lock.add(c);
resourcesMap.put(key, true);
lock.notify();
}
}
void addIssueFromRetry(ZHIssueContainer issue) {
String key = issue.getKey();
// Prevent duplicates in the work queue
if (resourcesMap.containsKey(key)) {
return;
}
log.logDebug("Adding issue (from retry): " + issue.getRepo().getName() + " " + issue.getIssue().getNumber());
synchronized (lock) {
issues_synch_lock.add(issue);
resourcesMap.put(key, true);
lock.notify();
}
}
void waitForAvailableWork() {
synchronized (lock) {
while (true) {
if (availableWork() > 0) {
return;
}
try {
lock.wait(20);
} catch (InterruptedException e) {
ZHUtil.throwAsUnchecked(e);
}
}
}
}
long availableWork() {
long workAvailable = 0;
synchronized (lock) {
workAvailable += repositories_synch_lock.size();
workAvailable += issues_synch_lock.size();
}
return workAvailable;
}
Optional<ZHRepositoryContainer> pollRepository() {
synchronized (repositories_synch_lock) {
if (repositories_synch_lock.isEmpty()) {
return Optional.empty();
}
ZHRepositoryContainer result = repositories_synch_lock.remove(0);
resourcesMap.remove(result.getKey());
return Optional.of(result);
}
}
Optional<ZHIssueContainer> pollIssue() {
synchronized (issues_synch_lock) {
if (issues_synch_lock.isEmpty()) {
return Optional.empty();
}
ZHIssueContainer result = issues_synch_lock.remove(0);
resourcesMap.remove(result.getKey());
return Optional.of(result);
}
}
GitHub getGithubClient() {
return githubClient;
}
ZenHubClient getZenhubClient() {
return zenhubClient;
}
ZHFilter getFilter() {
return filter;
}
/**
* A piece of a work in the work queue, specifically an issue, plus additional
* required fields.
*/
static class ZHIssueContainer {
private final GHOwner owner;
private final GHRepository repo;
private final GHIssue issue;
private final String hashKey;
public ZHIssueContainer(GHOwner owner, GHRepository repo, GHIssue issue) {
this.repo = repo;
this.issue = issue;
this.owner = owner;
this.hashKey = calculateKey();
}
public GHRepository getRepo() {
return repo;
}
public GHIssue getIssue() {
return issue;
}
public String getKey() {
return hashKey;
}
private String calculateKey() {
StringBuilder sb = new StringBuilder();
sb.append(owner.toString());
sb.append("-");
sb.append(repo.getName());
sb.append("-");
sb.append(issue);
return sb.toString();
}
@Override
public boolean equals(Object param) {
if (!(param instanceof ZHIssueContainer)) {
return false;
}
ZHIssueContainer other = (ZHIssueContainer) param;
return other.getIssue().getNumber() == this.getIssue().getNumber() && repo.getName().equals(other.repo.getName())
&& other.owner.equals(this.owner);
}
}
/**
* A piece of a work in the work queue, specifically a repository, plus
* additional required fields.
*/
static class ZHRepositoryContainer {
private final GHOwner owner;
private final GHRepository repo;
private final String repoName;
private final long repoId;
private final String hashKey;
public ZHRepositoryContainer(GHOwner owner, GHRepository repo, String repoName, long repoId) {
this.owner = owner;
this.repoName = repoName;
this.repo = repo;
this.repoId = repoId;
this.hashKey = calculateKey();
}
public GHOwner getOwner() {
return owner;
}
public String getRepoName() {
return repoName;
}
public long getRepoId() {
return repoId;
}
public GHRepository getRepo() {
return repo;
}
public String getKey() {
return hashKey;
}
private String calculateKey() {
StringBuilder sb = new StringBuilder();
sb.append(owner.toString());
sb.append("-");
sb.append(repoName);
sb.append("-");
sb.append(repoId);
return sb.toString();
}
@Override
public boolean equals(Object param) {
if (!(param instanceof ZHRepositoryContainer)) {
return false;
}
ZHRepositoryContainer other = (ZHRepositoryContainer) param;
return this.repoId == other.repoId && this.repoName.equals(other.repoName) && this.owner.equals(other.owner);
}
}
public ZHDatabase getDb() {
return database;
}
}
| 23.136905 | 116 | 0.699383 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.