code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.kusto.v2019_09_07.implementation;
import com.microsoft.azure.management.kusto.v2019_09_07.AttachedDatabaseConfiguration;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import com.microsoft.azure.management.kusto.v2019_09_07.ProvisioningState;
import java.util.List;
import com.microsoft.azure.management.kusto.v2019_09_07.DefaultPrincipalsModificationKind;
class AttachedDatabaseConfigurationImpl extends CreatableUpdatableImpl<AttachedDatabaseConfiguration, AttachedDatabaseConfigurationInner, AttachedDatabaseConfigurationImpl> implements AttachedDatabaseConfiguration, AttachedDatabaseConfiguration.Definition, AttachedDatabaseConfiguration.Update {
private final KustoManager manager;
private String resourceGroupName;
private String clusterName;
private String attachedDatabaseConfigurationName;
AttachedDatabaseConfigurationImpl(String name, KustoManager manager) {
super(name, new AttachedDatabaseConfigurationInner());
this.manager = manager;
// Set resource name
this.attachedDatabaseConfigurationName = name;
//
}
AttachedDatabaseConfigurationImpl(AttachedDatabaseConfigurationInner inner, KustoManager manager) {
super(inner.name(), inner);
this.manager = manager;
// Set resource name
this.attachedDatabaseConfigurationName = inner.name();
// set resource ancestor and positional variables
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
this.clusterName = IdParsingUtils.getValueFromIdByName(inner.id(), "clusters");
this.attachedDatabaseConfigurationName = IdParsingUtils.getValueFromIdByName(inner.id(), "attachedDatabaseConfigurations");
//
}
@Override
public KustoManager manager() {
return this.manager;
}
@Override
public Observable<AttachedDatabaseConfiguration> createResourceAsync() {
AttachedDatabaseConfigurationsInner client = this.manager().inner().attachedDatabaseConfigurations();
return client.createOrUpdateAsync(this.resourceGroupName, this.clusterName, this.attachedDatabaseConfigurationName, this.inner())
.map(innerToFluentMap(this));
}
@Override
public Observable<AttachedDatabaseConfiguration> updateResourceAsync() {
AttachedDatabaseConfigurationsInner client = this.manager().inner().attachedDatabaseConfigurations();
return client.createOrUpdateAsync(this.resourceGroupName, this.clusterName, this.attachedDatabaseConfigurationName, this.inner())
.map(innerToFluentMap(this));
}
@Override
protected Observable<AttachedDatabaseConfigurationInner> getInnerAsync() {
AttachedDatabaseConfigurationsInner client = this.manager().inner().attachedDatabaseConfigurations();
return client.getAsync(this.resourceGroupName, this.clusterName, this.attachedDatabaseConfigurationName);
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
@Override
public List<String> attachedDatabaseNames() {
return this.inner().attachedDatabaseNames();
}
@Override
public String clusterResourceId() {
return this.inner().clusterResourceId();
}
@Override
public String databaseName() {
return this.inner().databaseName();
}
@Override
public DefaultPrincipalsModificationKind defaultPrincipalsModificationKind() {
return this.inner().defaultPrincipalsModificationKind();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String location() {
return this.inner().location();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public ProvisioningState provisioningState() {
return this.inner().provisioningState();
}
@Override
public String type() {
return this.inner().type();
}
@Override
public AttachedDatabaseConfigurationImpl withExistingCluster(String resourceGroupName, String clusterName) {
this.resourceGroupName = resourceGroupName;
this.clusterName = clusterName;
return this;
}
@Override
public AttachedDatabaseConfigurationImpl withClusterResourceId(String clusterResourceId) {
this.inner().withClusterResourceId(clusterResourceId);
return this;
}
@Override
public AttachedDatabaseConfigurationImpl withDatabaseName(String databaseName) {
this.inner().withDatabaseName(databaseName);
return this;
}
@Override
public AttachedDatabaseConfigurationImpl withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind defaultPrincipalsModificationKind) {
this.inner().withDefaultPrincipalsModificationKind(defaultPrincipalsModificationKind);
return this;
}
@Override
public AttachedDatabaseConfigurationImpl withLocation(String location) {
this.inner().withLocation(location);
return this;
}
}
| selvasingh/azure-sdk-for-java | sdk/kusto/mgmt-v2019_09_07/src/main/java/com/microsoft/azure/management/kusto/v2019_09_07/implementation/AttachedDatabaseConfigurationImpl.java | Java | mit | 5,410 |
/*
* Encog(tm) Core v3.2 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2013 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.neural.networks.training.propagation.scg;
| ladygagapowerbot/bachelor-thesis-implementation | lib/Encog/src/main/java/org/encog/neural/networks/training/propagation/scg/package-info.java | Java | mit | 928 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.mysql.v2017_12_01_preview;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.mysql.v2017_12_01_preview.implementation.MySQLManager;
import com.microsoft.azure.management.mysql.v2017_12_01_preview.implementation.NameAvailabilityInner;
/**
* Type representing NameAvailability.
*/
public interface NameAvailability extends HasInner<NameAvailabilityInner>, HasManager<MySQLManager> {
/**
* @return the message value.
*/
String message();
/**
* @return the nameAvailable value.
*/
Boolean nameAvailable();
/**
* @return the reason value.
*/
String reason();
}
| selvasingh/azure-sdk-for-java | sdk/mysql/mgmt-v2017_12_01_preview/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01_preview/NameAvailability.java | Java | mit | 983 |
package org.fxapps.bpms.remote;
import java.net.MalformedURLException;
import java.net.URL;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.remote.client.api.RemoteRuntimeEngineFactory;
public abstract class RemoteAPITestBase {
protected static final String DEPLOYMENT_ID = "org.kie.example:project1:1.0";
protected static final String APP_URL = "http://localhost:8080/business-central";
protected static final String USER = "jesuino";
protected static final String PASSWORD = "redhat2014!";
protected static final int TIMEOUT = 2000;
protected RuntimeEngine engine;
public RemoteAPITestBase() {
long m = System.currentTimeMillis();
try {
engine = RemoteRuntimeEngineFactory.newRestBuilder()
.addUrl(new URL(APP_URL)).addUserName(USER)
.addProcessInstanceId(10l).addPassword(PASSWORD)
.addDeploymentId(DEPLOYMENT_ID).addTimeout(TIMEOUT).build();
} catch (MalformedURLException e) {
e.printStackTrace();
}
System.out.println("Time to create the remote engine :"
+ (System.currentTimeMillis() - m));
}
public abstract void doTest() throws Exception;
}
| jesuino/bpms6-examples | bpms63/bpms63-remote-api/src/test/java/org/fxapps/bpms/remote/RemoteAPITestBase.java | Java | mit | 1,118 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2018_07_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.Resource;
import com.microsoft.azure.arm.resources.models.GroupableResourceCore;
import com.microsoft.azure.arm.resources.models.HasResourceGroup;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.network.v2018_07_01.implementation.NetworkManager;
import java.util.List;
import com.microsoft.azure.management.network.v2018_07_01.implementation.BgpServiceCommunityInner;
/**
* Type representing BgpServiceCommunity.
*/
public interface BgpServiceCommunity extends HasInner<BgpServiceCommunityInner>, Resource, GroupableResourceCore<NetworkManager, BgpServiceCommunityInner>, HasResourceGroup, HasManager<NetworkManager> {
/**
* @return the bgpCommunities value.
*/
List<BGPCommunity> bgpCommunities();
/**
* @return the serviceName value.
*/
String serviceName();
}
| navalev/azure-sdk-for-java | sdk/network/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/BgpServiceCommunity.java | Java | mit | 1,242 |
package com.waylau.spring.boot.blog;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Test
public void contextLoads() {
}
}
| waylau/spring-boot-tutorial | samples/blog-user/src/test/java/com/waylau/spring/boot/blog/ApplicationTests.java | Java | mit | 338 |
package com.github.kostyasha.yad;
import hudson.slaves.OfflineCause;
/**
* @author Kanstantsin Shautsou
*/
public class DockerOfflineCause extends OfflineCause {
private String message;
public DockerOfflineCause(String message) {
this.message = message;
}
@Override
public String toString() {
return message;
}
}
| pronovic/yet-another-docker-plugin | yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerOfflineCause.java | Java | mit | 359 |
/* ====================================================================
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.poi.hslf.model;
import org.apache.poi.ddf.*;
import java.awt.*;
/**
* Represents a cell in a ppt table
*
* @author Yegor Kozlov
*/
public final class TableCell extends TextBox {
protected static final int DEFAULT_WIDTH = 100;
protected static final int DEFAULT_HEIGHT = 40;
private Line borderLeft;
private Line borderRight;
private Line borderTop;
private Line borderBottom;
/**
* Create a TableCell object and initialize it from the supplied Record container.
*
* @param escherRecord <code>EscherSpContainer</code> container which holds information about this shape
* @param parent the parent of the shape
*/
protected TableCell(EscherContainerRecord escherRecord, Shape parent){
super(escherRecord, parent);
}
/**
* Create a new TableCell. This constructor is used when a new shape is created.
*
* @param parent the parent of this Shape. For example, if this text box is a cell
* in a table then the parent is Table.
*/
public TableCell(Shape parent){
super(parent);
setShapeType(ShapeTypes.Rectangle);
//_txtrun.setRunType(TextHeaderAtom.HALF_BODY_TYPE);
//_txtrun.getRichTextRuns()[0].setFlag(false, 0, false);
}
protected EscherContainerRecord createSpContainer(boolean isChild){
_escherContainer = super.createSpContainer(isChild);
EscherOptRecord opt = (EscherOptRecord)getEscherChild(_escherContainer, EscherOptRecord.RECORD_ID);
setEscherProperty(opt, EscherProperties.TEXT__TEXTID, 0);
setEscherProperty(opt, EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 0x20000);
setEscherProperty(opt, EscherProperties.FILL__NOFILLHITTEST, 0x150001);
setEscherProperty(opt, EscherProperties.SHADOWSTYLE__SHADOWOBSURED, 0x20000);
setEscherProperty(opt, EscherProperties.PROTECTION__LOCKAGAINSTGROUPING, 0x40000);
return _escherContainer;
}
protected void anchorBorder(int type, Line line){
Rectangle cellAnchor = getAnchor();
Rectangle lineAnchor = new Rectangle();
switch(type){
case Table.BORDER_TOP:
lineAnchor.x = cellAnchor.x;
lineAnchor.y = cellAnchor.y;
lineAnchor.width = cellAnchor.width;
lineAnchor.height = 0;
break;
case Table.BORDER_RIGHT:
lineAnchor.x = cellAnchor.x + cellAnchor.width;
lineAnchor.y = cellAnchor.y;
lineAnchor.width = 0;
lineAnchor.height = cellAnchor.height;
break;
case Table.BORDER_BOTTOM:
lineAnchor.x = cellAnchor.x;
lineAnchor.y = cellAnchor.y + cellAnchor.height;
lineAnchor.width = cellAnchor.width;
lineAnchor.height = 0;
break;
case Table.BORDER_LEFT:
lineAnchor.x = cellAnchor.x;
lineAnchor.y = cellAnchor.y;
lineAnchor.width = 0;
lineAnchor.height = cellAnchor.height;
break;
default:
throw new IllegalArgumentException("Unknown border type: " + type);
}
line.setAnchor(lineAnchor);
}
public Line getBorderLeft() {
return borderLeft;
}
public void setBorderLeft(Line line) {
if(line != null) anchorBorder(Table.BORDER_LEFT, line);
this.borderLeft = line;
}
public Line getBorderRight() {
return borderRight;
}
public void setBorderRight(Line line) {
if(line != null) anchorBorder(Table.BORDER_RIGHT, line);
this.borderRight = line;
}
public Line getBorderTop() {
return borderTop;
}
public void setBorderTop(Line line) {
if(line != null) anchorBorder(Table.BORDER_TOP, line);
this.borderTop = line;
}
public Line getBorderBottom() {
return borderBottom;
}
public void setBorderBottom(Line line) {
if(line != null) anchorBorder(Table.BORDER_BOTTOM, line);
this.borderBottom = line;
}
public void setAnchor(Rectangle anchor){
super.setAnchor(anchor);
if(borderTop != null) anchorBorder(Table.BORDER_TOP, borderTop);
if(borderRight != null) anchorBorder(Table.BORDER_RIGHT, borderRight);
if(borderBottom != null) anchorBorder(Table.BORDER_BOTTOM, borderBottom);
if(borderLeft != null) anchorBorder(Table.BORDER_LEFT, borderLeft);
}
}
| tobyclemson/msci-project | vendor/poi-3.6/src/scratchpad/src/org/apache/poi/hslf/model/TableCell.java | Java | mit | 5,523 |
package com.vter.model;
import java.util.UUID;
public abstract class BaseEntityWithUuid extends BaseEntity<UUID> implements EntityWithUuid {
public BaseEntityWithUuid() {
super(UUID.randomUUID());
}
}
| agoodfriendalwayspayshisdebts/agoodfriendalwayspayshisdebts-api | src/main/java/com/vter/model/BaseEntityWithUuid.java | Java | mit | 212 |
package ch.heigvd.res.examples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class implements a multi-threaded TCP server. It is able to interact
* with several clients at the time, as well as to continue listening for
* connection requests.
*
* @author Olivier Liechti
*/
public class MultiThreadedServer {
final static Logger LOG = Logger.getLogger(MultiThreadedServer.class.getName());
int port;
/**
* Constructor
*
* @param port the port to listen on
*/
public MultiThreadedServer(int port) {
this.port = port;
}
/**
* This method initiates the process. The server creates a socket and binds it
* to the previously specified port. It then waits for clients in a infinite
* loop. When a client arrives, the server will read its input line by line
* and send back the data converted to uppercase. This will continue until the
* client sends the "BYE" command.
*/
public void serveClients() {
LOG.info("Starting the Receptionist Worker on a new thread...");
new Thread(new ReceptionistWorker()).start();
}
/**
* This inner class implements the behavior of the "receptionist", whose
* responsibility is to listen for incoming connection requests. As soon as a
* new client has arrived, the receptionist delegates the processing to a
* "servant" who will execute on its own thread.
*/
private class ReceptionistWorker implements Runnable {
@Override
public void run() {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(port);
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
return;
}
while (true) {
LOG.log(Level.INFO, "Waiting (blocking) for a new client on port {0}", port);
try {
Socket clientSocket = serverSocket.accept();
LOG.info("A new client has arrived. Starting a new thread and delegating work to a new servant...");
new Thread(new ServantWorker(clientSocket)).start();
} catch (IOException ex) {
Logger.getLogger(MultiThreadedServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* This inner class implements the behavior of the "servants", whose
* responsibility is to take care of clients once they have connected. This
* is where we implement the application protocol logic, i.e. where we read
* data sent by the client and where we generate the responses.
*/
private class ServantWorker implements Runnable {
Socket clientSocket;
BufferedReader in = null;
PrintWriter out = null;
public ServantWorker(Socket clientSocket) {
try {
this.clientSocket = clientSocket;
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(MultiThreadedServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
String line;
boolean shouldRun = true;
out.println("Welcome to the Multi-Threaded Server.\nSend me text lines and conclude with the BYE command.");
out.flush();
try {
LOG.info("Reading until client sends BYE or closes the connection...");
while ((shouldRun) && (line = in.readLine()) != null) {
if (line.equalsIgnoreCase("bye")) {
shouldRun = false;
}
out.println("> " + line.toUpperCase());
out.flush();
}
LOG.info("Cleaning up resources...");
clientSocket.close();
in.close();
out.close();
} catch (IOException ex) {
if (in != null) {
try {
in.close();
} catch (IOException ex1) {
LOG.log(Level.SEVERE, ex1.getMessage(), ex1);
}
}
if (out != null) {
out.close();
}
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException ex1) {
LOG.log(Level.SEVERE, ex1.getMessage(), ex1);
}
}
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
}
}
| wasadigi/Teaching-HEIGVD-RES | examples/07-TcpServers/TcpServers/src/ch/heigvd/res/examples/MultiThreadedServer.java | Java | mit | 4,170 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2018_12_01.implementation;
import com.microsoft.azure.management.network.v2018_12_01.SecurityGroupViewResult;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import java.util.List;
import com.microsoft.azure.management.network.v2018_12_01.SecurityGroupNetworkInterface;
class SecurityGroupViewResultImpl extends WrapperImpl<SecurityGroupViewResultInner> implements SecurityGroupViewResult {
private final NetworkManager manager;
SecurityGroupViewResultImpl(SecurityGroupViewResultInner inner, NetworkManager manager) {
super(inner);
this.manager = manager;
}
@Override
public NetworkManager manager() {
return this.manager;
}
@Override
public List<SecurityGroupNetworkInterface> networkInterfaces() {
return this.inner().networkInterfaces();
}
}
| selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2018_12_01/src/main/java/com/microsoft/azure/management/network/v2018_12_01/implementation/SecurityGroupViewResultImpl.java | Java | mit | 1,116 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.storage.blob.specialized;
import com.azure.core.annotation.ServiceClientBuilder;
import com.azure.core.http.HttpPipeline;
import com.azure.storage.blob.BlobAsyncClient;
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerAsyncClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceVersion;
import java.net.URL;
import java.util.Objects;
import java.util.UUID;
/**
* This class provides a fluent builder API to help aid the configuration and instantiation of Storage Lease
* clients. Lease clients are able to interact with both container and blob clients and act as a supplement client. A
* new instance of {@link BlobLeaseClient} and {@link BlobLeaseAsyncClient} are constructed every time
* {@link #buildClient() buildClient} and {@link #buildAsyncClient() buildAsyncClient} are called
* respectively.
*
* <p>When a client is instantiated and a {@link #leaseId(String) leaseId} hasn't been set a {@link UUID} will be used
* as the lease identifier.</p>
*
* <p><strong>Instantiating LeaseClients</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithBlobAndLeaseId}
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithContainerAndLeaseId}
*
* <p><strong>Instantiating LeaseAsyncClients</strong></p>
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlobAndLeaseId}
*
* {@codesnippet com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainerAndLeaseId}
*
* @see BlobLeaseClient
* @see BlobLeaseAsyncClient
*/
@ServiceClientBuilder(serviceClients = { BlobLeaseClient.class, BlobLeaseAsyncClient.class })
public final class BlobLeaseClientBuilder {
private HttpPipeline pipeline;
private String url;
private String leaseId;
private boolean isBlob;
private String accountName;
private BlobServiceVersion serviceVersion;
/**
* Creates a {@link BlobLeaseClient} based on the configurations set in the builder.
*
* @return a {@link BlobLeaseClient} based on the configurations in this builder.
*/
public BlobLeaseClient buildClient() {
return new BlobLeaseClient(buildAsyncClient());
}
/**
* Creates a {@link BlobLeaseAsyncClient} based on the configurations set in the builder.
*
* @return a {@link BlobLeaseAsyncClient} based on the configurations in this builder.
*/
public BlobLeaseAsyncClient buildAsyncClient() {
BlobServiceVersion version = (serviceVersion == null) ? BlobServiceVersion.getLatest() : serviceVersion;
return new BlobLeaseAsyncClient(pipeline, url, getLeaseId(), isBlob, accountName, version.getVersion());
}
/**
* Configures the builder based on the passed {@link BlobClient}. This will set the {@link HttpPipeline} and
* {@link URL} that are used to interact with the service.
*
* @param blobClient BlobClient used to configure the builder.
* @return the updated BlobLeaseClientBuilder object
* @throws NullPointerException If {@code blobClient} is {@code null}.
*/
public BlobLeaseClientBuilder blobClient(BlobClientBase blobClient) {
Objects.requireNonNull(blobClient);
this.pipeline = blobClient.getHttpPipeline();
this.url = blobClient.getBlobUrl();
this.isBlob = true;
this.accountName = blobClient.getAccountName();
this.serviceVersion = blobClient.getServiceVersion();
return this;
}
/**
* Configures the builder based on the passed {@link BlobAsyncClient}. This will set the {@link HttpPipeline} and
* {@link URL} that are used to interact with the service.
*
* @param blobAsyncClient BlobAsyncClient used to configure the builder.
* @return the updated BlobLeaseClientBuilder object
* @throws NullPointerException If {@code blobAsyncClient} is {@code null}.
*/
public BlobLeaseClientBuilder blobAsyncClient(BlobAsyncClientBase blobAsyncClient) {
Objects.requireNonNull(blobAsyncClient);
this.pipeline = blobAsyncClient.getHttpPipeline();
this.url = blobAsyncClient.getBlobUrl();
this.isBlob = true;
this.accountName = blobAsyncClient.getAccountName();
this.serviceVersion = blobAsyncClient.getServiceVersion();
return this;
}
/**
* Configures the builder based on the passed {@link BlobContainerClient}. This will set the {@link HttpPipeline}
* and {@link URL} that are used to interact with the service.
*
* @param blobContainerClient ContainerClient used to configure the builder.
* @return the updated BlobLeaseClientBuilder object
* @throws NullPointerException If {@code containerClient} is {@code null}.
*/
public BlobLeaseClientBuilder containerClient(BlobContainerClient blobContainerClient) {
Objects.requireNonNull(blobContainerClient);
this.pipeline = blobContainerClient.getHttpPipeline();
this.url = blobContainerClient.getBlobContainerUrl();
this.isBlob = false;
this.accountName = blobContainerClient.getAccountName();
this.serviceVersion = blobContainerClient.getServiceVersion();
return this;
}
/**
* Configures the builder based on the passed {@link BlobContainerAsyncClient}. This will set the {@link
* HttpPipeline} and {@link URL} that are used to interact with the service.
*
* @param blobContainerAsyncClient ContainerAsyncClient used to configure the builder.
* @return the updated BlobLeaseClientBuilder object
* @throws NullPointerException If {@code containerAsyncClient} is {@code null}.
*/
public BlobLeaseClientBuilder containerAsyncClient(BlobContainerAsyncClient blobContainerAsyncClient) {
Objects.requireNonNull(blobContainerAsyncClient);
this.pipeline = blobContainerAsyncClient.getHttpPipeline();
this.url = blobContainerAsyncClient.getBlobContainerUrl();
this.isBlob = false;
this.accountName = blobContainerAsyncClient.getAccountName();
this.serviceVersion = blobContainerAsyncClient.getServiceVersion();
return this;
}
/**
* Sets the identifier for the lease.
*
* <p>If a lease ID isn't set then a {@link UUID} will be used.</p>
*
* @param leaseId Identifier for the lease.
* @return the updated BlobLeaseClientBuilder object
*/
public BlobLeaseClientBuilder leaseId(String leaseId) {
this.leaseId = leaseId;
return this;
}
private String getLeaseId() {
return (leaseId == null) ? UUID.randomUUID().toString() : leaseId;
}
}
| selvasingh/azure-sdk-for-java | sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobLeaseClientBuilder.java | Java | mit | 6,903 |
/*
* 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 mathgame;
import mathgame.Menus.AbstractMenu;
/**
*
* @author devinbost
*/
public interface IDisplayCommand { // This is required for the Command design pattern.
void Execute();
AbstractMenu abstractMenu = null;
String GetContents();
}
| devinbost/CIT_Mathgame | src/mathgame/IDisplayCommand.java | Java | mit | 466 |
package geeksforgeeks;
/*
* http://www.geeksforgeeks.org/amazon-interview-set-21/
* A robot is there in 2D space, which can move to its left direction.
* You are given with an array which are moves of robot, which starts from origin(0,0).
* Find the rectangle covered by it.
* I/P: { 2,3,4,5,6,1,3,5,5} starts at (0,0)
* O/P: rectangle points: ( -4,4 ) to (4,-2)
*/;
public class _01AmazonInterview_21_04 {
public static void main(String[] args) {
int[] path={2,3,4,5,6,1,3,5,5};
int xCoOrd=0;
int yCoOrd=0;
findRectangle(xCoOrd,yCoOrd,path);
}
private static void findRectangle(int xCoOrd, int yCoOrd, int[] path) {
int direction=0;
//0 for left,1 for down,2 for right,3 for up
for (int i = 0; i < path.length; i++) {
switch (direction) {
case 0:
xCoOrd-=path[i];
break;
case 1:
yCoOrd-=path[i];
break;
case 2:
xCoOrd+=path[i];
break;
case 3:
yCoOrd+=path[i];
break;
default:
break;
}
System.out.println(xCoOrd+" "+yCoOrd);
direction++;
direction%=4;
}
}
} | darshanhs90/Java-Coding | src/geeksforgeeks/_01AmazonInterview_21_04.java | Java | mit | 1,147 |
/**
* Problem Link: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
*
* Iterate all of the possible solutions.
*/
public class Solution {
private HashMap<Integer, String> map;
private List<String> list;
public List<String> letterCombinations(String digits) {
map = new HashMap<Integer, String>();
map.put(0, "");
map.put(1, "");
map.put(2, "abc");
map.put(3, "def");
map.put(4, "ghi");
map.put(5, "jkl");
map.put(6, "mno");
map.put(7, "pqrs");
map.put(8, "tuv");
map.put(9, "wxyz");
list = new ArrayList<String>();
combine(digits, 0, "");
return list;
}
private void combine(String digit, int current, String ret) {
if(current == digit.length()) {
if(ret.length() > 0) list.add(ret);
return;
}
String s = map.get(digit.charAt(current) - '0');
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
combine(digit, current + 1, ret + c);
}
}
}
| antonio081014/LeeCode-CodeBase | Java/letter-combinations-of-a-phone-number.java | Java | mit | 1,099 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_02_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for ApplicationGatewaySslPolicyName.
*/
public final class ApplicationGatewaySslPolicyName extends ExpandableStringEnum<ApplicationGatewaySslPolicyName> {
/** Static value AppGwSslPolicy20150501 for ApplicationGatewaySslPolicyName. */
public static final ApplicationGatewaySslPolicyName APP_GW_SSL_POLICY20150501 = fromString("AppGwSslPolicy20150501");
/** Static value AppGwSslPolicy20170401 for ApplicationGatewaySslPolicyName. */
public static final ApplicationGatewaySslPolicyName APP_GW_SSL_POLICY20170401 = fromString("AppGwSslPolicy20170401");
/** Static value AppGwSslPolicy20170401S for ApplicationGatewaySslPolicyName. */
public static final ApplicationGatewaySslPolicyName APP_GW_SSL_POLICY20170401S = fromString("AppGwSslPolicy20170401S");
/**
* Creates or finds a ApplicationGatewaySslPolicyName from its string representation.
* @param name a name to look for
* @return the corresponding ApplicationGatewaySslPolicyName
*/
@JsonCreator
public static ApplicationGatewaySslPolicyName fromString(String name) {
return fromString(name, ApplicationGatewaySslPolicyName.class);
}
/**
* @return known ApplicationGatewaySslPolicyName values
*/
public static Collection<ApplicationGatewaySslPolicyName> values() {
return values(ApplicationGatewaySslPolicyName.class);
}
}
| selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_02_01/src/main/java/com/microsoft/azure/management/network/v2019_02_01/ApplicationGatewaySslPolicyName.java | Java | mit | 1,826 |
package reversi.movimento;
import reversi.movimento.Movimento;
import java.util.Comparator;
/**
* Created by arthur on 18/03/15.
*/
public class ConjuntoMovimentosComparator implements Comparator<ConjuntoMovimentos> {
@Override
public int compare(ConjuntoMovimentos o1, ConjuntoMovimentos o2) {
return o2.getValor() - o1.getValor();
}
}
| ArthurPBressan/TecJogosReversi | src/reversi/movimento/ConjuntoMovimentosComparator.java | Java | mit | 362 |
/*******************************************************************************
* This file is part of the Symfony eclipse plugin.
*
* (c) Robert Gruendler <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
******************************************************************************/
package com.dubture.symfony.ui.editor.hover;
import org.eclipse.jface.internal.text.html.BrowserInformationControlInput;
import com.dubture.symfony.index.model.Route;
import com.dubture.symfony.ui.utils.HTMLUtils;
/**
*
* Creates the HTML for the route documentation popup when hovering over routes.
*
*
* @author Robert Gruendler <[email protected]>
*
*/
@SuppressWarnings("restriction")
public class RouteBrowserInformationControlInput extends
BrowserInformationControlInput {
private Route route;
public RouteBrowserInformationControlInput(
BrowserInformationControlInput previous, Route route) {
super(previous);
this.route = route;
}
@Override
public String getHtml() {
return HTMLUtils.route2Html(route);
}
@Override
public int getLeadingImageWidth() {
return 16;
}
@Override
public Object getInputElement() {
return route;
}
@Override
public String getInputName() {
return route.name;
}
}
| pulse00/Symfony-2-Eclipse-Plugin | com.dubture.symfony.ui/src/com/dubture/symfony/ui/editor/hover/RouteBrowserInformationControlInput.java | Java | mit | 1,364 |
/*******************************************************************************
* Copyright (c) 2018 Microsoft Research. All rights reserved.
*
* The MIT License (MIT)
*
* 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.
*
* Contributors:
* Markus Alexander Kuppe - initial API and implementation
******************************************************************************/
package tlc2.util.statistics;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.BooleanSupplier;
public abstract class CounterStatistic {
public static CounterStatistic getInstance(final BooleanSupplier s) {
if (s.getAsBoolean()) {
return new LongAdderCounterStatistic();
} else {
return new NoopCounterStatistic();
}
}
public abstract void increment();
public abstract void add(final long evalCount);
public abstract long getCount();
private CounterStatistic() {
// private ctor
}
private static class NoopCounterStatistic extends CounterStatistic {
@Override
public final long getCount() {
return 0;
}
@Override
public final void increment() {
// noop
}
@Override
public void add(long evalCount) {
// noop
}
}
private static class LongAdderCounterStatistic extends CounterStatistic {
private final LongAdder adder = new LongAdder();
@Override
public final long getCount() {
return this.adder.sum();
}
@Override
public final void increment() {
adder.increment();
}
@Override
public void add(long evalCount) {
adder.add(evalCount);
}
@Override
public String toString() {
return adder.toString();
}
}
}
| tlaplus/tlaplus | tlatools/org.lamport.tlatools/src/tlc2/util/statistics/CounterStatistic.java | Java | mit | 2,652 |
package controllers2;
import play.mvc.Controller;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Hello1111111111111111111111111 extends Controller {
public static void hello() {
// System.out.println("tere");
render("Application/hello.html", debug());
}
private static Object debug() {return util.Util.get();}
private static void sort(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort2(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort3(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort4(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort5(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort6(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort7(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort8(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort9(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort10(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort11(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort12(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort13(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort14(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort15(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort16(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort17(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort18(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort19(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort20(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
} | asolntsev/big-app.play | app/controllers2/Hello1111111111111111111111111.java | Java | mit | 4,756 |
/**
* handywedgeのコンテキスト情報に関連するクラスを提供します。
*/
package com.handywedge.context;
| cstudioteam/handywedge | handywedge-master/handywedge-api/src/main/java/com/handywedge/context/package-info.java | Java | mit | 126 |
/*
* Copyright (C) 2017, Ulrich Wolffgang <[email protected]>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package io.proleap.cobol.asg.metamodel.procedure.initialize;
import java.util.List;
import io.proleap.cobol.CobolParser.InitializeReplacingByContext;
import io.proleap.cobol.asg.metamodel.CobolDivisionElement;
public interface ReplacingPhrase extends CobolDivisionElement {
By addBy(InitializeReplacingByContext ctx);
List<By> getBys();
}
| uwol/cobol85parser | src/main/java/io/proleap/cobol/asg/metamodel/procedure/initialize/ReplacingPhrase.java | Java | mit | 573 |
package com.awesometickets.web.controller;
import com.awesometickets.business.entities.Seat;
import com.awesometickets.business.services.SeatService;
import com.awesometickets.web.controller.response.CollectionResponse;
import com.awesometickets.web.controller.response.RestResponse;
import com.awesometickets.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;
/**
* RESTFul API of seat resources.
*/
@RestController
@RequestMapping("/resource/seat")
public class SeatController {
private static final Logger Log = LoggerFactory.getLogger(SeatController.class);
@Autowired
private SeatService seatService;
public SeatController() {
super();
}
@RequestMapping(path = "/unavailable",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public RestResponse getUnavailableSeat(@RequestParam("movieOnShowId") Integer movieOnShowId,
HttpServletRequest request, HttpServletResponse response) {
LogUtil.logReq(Log, request);
List<Integer[]> dataList = new LinkedList<Integer[]>();
List<Seat> seats = seatService.getUnavailable(movieOnShowId);
for (Seat seat : seats) {
dataList.add(new Integer[] {seat.getRow(), seat.getCol()});
}
return new CollectionResponse(dataList);
}
} | AwesomeTickets/Tickets-Server | src/main/java/com/awesometickets/web/controller/SeatController.java | Java | mit | 1,908 |
package Jan2021Leetcode;
public class _0206ReverseLinkedList {
static public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void main(String[] args) {
ListNode ln = new ListNode(1);
ln.next = new ListNode(2);
ln.next.next = new ListNode(3);
ln.next.next.next = new ListNode(4);
ln.next.next.next.next = new ListNode(5);
ln.next.next.next.next.next = new ListNode(6);
ln.next.next.next.next.next.next = new ListNode(7);
ln = reverseList(ln);
printElements(ln);
}
public static void printElements(ListNode head) {
while (head != null) {
System.out.print(head.val + "->");
head = head.next;
}
System.out.println();
}
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode nextNode = head.next;
ListNode reverse = reverseList(head.next);
head.next = null;
nextNode.next = head;
return reverse;
}
}
| darshanhs90/Java-InterviewPrep | src/Jan2021Leetcode/_0206ReverseLinkedList.java | Java | mit | 1,073 |
package me.calebjones.spacelaunchnow.data.models.main.astronaut;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class AstronautRole extends RealmObject {
@PrimaryKey
@SerializedName("id")
@Expose
public Integer id;
@SerializedName("role")
@Expose
public String role;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| caman9119/SpaceLaunchNow | data/src/main/java/me/calebjones/spacelaunchnow/data/models/main/astronaut/AstronautRole.java | Java | mit | 554 |
/**
* Copyright (c) 2014 MNCC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @author http://www.mncc.fr
*/
package fr.mncc.gwttoolbox.appengine.server.nextgen.interfaces;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import java.util.List;
import java.util.Map;
public interface GaeDatastore {
Key create(Entity entity);
Entity read(String kind, long key);
Key update(Entity entity);
void delete(String kind, long key);
Entity read(Key key);
void delete(Key key);
List<Key> create(Iterable<Entity> entities);
List<Key> update(Iterable<Entity> entities);
Map<Key, Entity> read(Iterable<Key> keys);
void delete(Iterable<Key> keys);
Iterable<com.google.appengine.api.datastore.Entity> read(Query query);
}
| kerbymart/gwt-appengine | src/fr/mncc/gwttoolbox/appengine/server/nextgen/interfaces/GaeDatastore.java | Java | mit | 1,870 |
package org.ominidi.facebook.mapper;
public interface FromType<T, E> {
E fromType(T toMap);
}
| ominidi/ominidi-web | src/main/java/org/ominidi/facebook/mapper/FromType.java | Java | mit | 104 |
package com.bbn.bue.common.collections;
import com.bbn.bue.common.TextGroupImmutable;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
import org.immutables.value.Value;
import java.util.Collection;
import java.util.Set;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A Multitable that cannot hold duplicate key-key-value triples. Adding a key-key-value triple
* that is already in the multitable has no effect.
*
* @see Multitable
* @see ImmutableMultitable
*
* @author Chester Palen-Michel, Constantine Lignos, Ryan Gabbard
*/
public final class ImmutableSetMultitable<R, C, V> extends ImmutableMultitable<R, C, V>
implements SetMultitable<R, C, V> {
private final ImmutableTable<R, C, Collection<V>> table;
private final int size;
private final ImmutableMap<R, Multimap<C, V>> rowMap;
private final ImmutableMap<C, Multimap<R, V>> columnMap;
private final ImmutableSet<Multicell<R, C, V>> cellSet;
private final ImmutableMultiset<V> allValues;
private ImmutableSetMultitable(final ImmutableTable<R, C, Collection<V>> table,
final int size, ImmutableSet<R> rowIterationOrder, ImmutableSet<C> columnIterationOrder) {
this.table = checkNotNull(table);
this.size = size; //all available construction methods ensure size matches table
//This is more than we generally want in constructor, but we are only caching to return views.
//cache rowMap
final ImmutableMap.Builder<R, Multimap<C, V>> rowMapBuilder = ImmutableMap.builder();
for (final R rowKey : rowIterationOrder) {
final ImmutableSetMultimap.Builder<C, V> colMultiBuilder = ImmutableSetMultimap.builder();
for (final C columnKey : columnIterationOrder) {
final Collection<V> value = table.get(rowKey, columnKey);
if (value != null) {
colMultiBuilder.putAll(columnKey, value);
}
}
rowMapBuilder.put(rowKey, colMultiBuilder.build());
}
this.rowMap = rowMapBuilder.build();
//cache columnMap
final ImmutableMap.Builder<C, Multimap<R, V>> columnMapBuilder = ImmutableMap.builder();
for (final C columnKey : columnIterationOrder) {
final ImmutableSetMultimap.Builder<R, V> rowMultiBuilder = ImmutableSetMultimap.builder();
for (final R rowKey : rowIterationOrder) {
final Collection<V> value = table.get(rowKey, columnKey);
if (value != null) {
rowMultiBuilder.putAll(rowKey, value);
}
}
columnMapBuilder.put(columnKey, rowMultiBuilder.build());
}
this.columnMap = columnMapBuilder.build();
//cache cellSet and allValues
final ImmutableMultiset.Builder<V> valuesBuilder = ImmutableMultiset.builder();
final ImmutableSet.Builder<Multicell<R, C, V>> cellSetBuilder = ImmutableSet.builder();
for (final R rowKey : rowIterationOrder) {
for (final C columnKey : columnIterationOrder) {
final Collection<V> values = table.get(rowKey, columnKey);
if (values != null) {
final ImmutableSetMulticell.Builder<R, C, V> multicellBuilder =
new ImmutableSetMultitable.SetMulticell.Builder<R, C, V>()
.rowKey(rowKey)
.columnKey(columnKey);
multicellBuilder.values(values);
valuesBuilder.addAll(values);
cellSetBuilder.add(multicellBuilder.build());
}
}
}
this.cellSet = cellSetBuilder.build();
this.allValues = valuesBuilder.build();
}
@Override
protected Table<R, C, Collection<V>> table() {
return table;
}
/**
* Returns the set of values corresponding to the given row and column keys, or
* an empty set if no such mapping exists. This exists in addition to {@code get} as a type-safe
* way of returning a set of values at a specified cell.
*
* @param rowKey key of row to search for
* @param columnKey key of column to search for
*/
@Override
@SuppressWarnings("unchecked")
public ImmutableSet<V> getAsSet(@Nullable final Object rowKey, @Nullable final Object columnKey) {
final Collection<V> ret = table.get(rowKey, columnKey);
if (ret != null) {
return (ImmutableSet<V>) ret; //cast guaranteed to succeed because table made of sets
} else {
return ImmutableSet.of();
}
}
@Override
public ImmutableMap<R, Multimap<C, V>> rowMap() {
return rowMap;
}
@Override
public ImmutableMap<C, Multimap<R, V>> columnMap() {
return columnMap;
}
@Override
public Set<Multicell<R, C, V>> cellSet() {
return cellSet;
}
/**
* Returns {@code true} if the table contains a mapping with the specified
* value. Runs in O(1) time.
* @param value value to search for
*/
@Override
public boolean containsValue(@Nullable final Object value) {
return allValues.contains(value);
}
@Override
public Collection<V> get(@Nullable final Object rowKey, @Nullable final Object columnKey) {
final Collection<V> ret = table.get(rowKey, columnKey);
if (ret != null) {
return ret;
} else {
return ImmutableSet.of();
}
}
@Override
public ImmutableMultiset<V> values() {
return allValues;
}
@Override
public int size() {
return size;
}
public static <R, C, V> ImmutableSetMultitable.Builder<R, C, V> builder() {
return new Builder<>();
}
public static class Builder<R, C, V> implements ImmutableMultitable.Builder<R,C,V> {
// we use the two tables because we both need to maintain insertion order and
// be able to do lookups during building. The values of both sets are
// the same identical objects
private final HashBasedTable<R, C, ImmutableSet.Builder<V>> tableWeCanLookUpIn =
HashBasedTable.create();
private final ImmutableSet.Builder<RowKeyColumnKeyPair<R, C>> rowInsertionOrder =
ImmutableSet.builder();
private Builder() {
}
private ImmutableSet.Builder<V> setForKey(final R rowKey, final C columnKey) {
ImmutableSet.Builder<V> values = tableWeCanLookUpIn.get(rowKey, columnKey);
if (values == null) {
values = ImmutableSet.builder();
tableWeCanLookUpIn.put(rowKey, columnKey, values);
rowInsertionOrder.add(RowKeyColumnKeyPair.of(rowKey, columnKey));
}
return values;
}
@Override
public Builder<R, C, V> put(R rowKey, C columnKey, V value) {
setForKey(rowKey, columnKey).add(value);
return this;
}
@Override
public Builder<R, C, V> putAll(final R rowKey, final C columnKey,
final Iterable<? extends V> values) {
setForKey(rowKey, columnKey).addAll(values);
return this;
}
public ImmutableSetMultitable<R, C, V> build() {
final ImmutableTable.Builder<R, C, Collection<V>> immutableTable =
ImmutableTable.builder();
int size = 0;
ImmutableSet.Builder<R> rowIterationBuilder = ImmutableSet.builder();
ImmutableSet.Builder<C> columnIterationBuilder = ImmutableSet.builder();
for (final RowKeyColumnKeyPair<R, C> rowKeyColKey : rowInsertionOrder.build()) {
final ImmutableSet<V> valuesForPair =
tableWeCanLookUpIn.get(rowKeyColKey.row(), rowKeyColKey.column()).build();
size += valuesForPair.size();
immutableTable.put(rowKeyColKey.row(), rowKeyColKey.column(),
valuesForPair);
rowIterationBuilder.add(rowKeyColKey.row());
columnIterationBuilder.add(rowKeyColKey.column());
}
return new ImmutableSetMultitable<>(immutableTable.build(), size, rowIterationBuilder.build(),
columnIterationBuilder.build());
}
}
@TextGroupImmutable
@Value.Immutable
static abstract class SetMulticell<R, C, V>
implements SetMultitable.SetMulticell<R, C, V> {
@Override
public abstract R getRowKey();
@Override
public abstract C getColumnKey();
@Override
public abstract Set<V> getValues();
public static class Builder<R, C, V> extends ImmutableSetMulticell.Builder<R, C, V> {
}
}
}
| rgabbard-bbn/bue-common-open | common-core-open/src/main/java/com/bbn/bue/common/collections/ImmutableSetMultitable.java | Java | mit | 8,378 |
package com.github.dcapwell.java.file.operations;
public interface Chmod {
// needs to be boolean, because different impls have different meanings in the return code
public boolean chmod(String filename, int mode);
}
| dcapwell/java-file-operations | src/main/java/com/github/dcapwell/java/file/operations/Chmod.java | Java | mit | 222 |
package com.aspose.maven.utils;
/**
* @author Adeel Ilyas <[email protected]>
*/
public class AsposeJavaAPI {
private String _name;
private boolean _selected;
private String _mavenRepositoryURL;
public AsposeJavaAPI() {
_selected = false;
}
/**
* @return the _name
*/
public String get_name() {
return _name;
}
/**
* @param _name the _name to set
*/
public void set_name(String _name) {
this._name = _name;
}
/**
* @return the _selected
*/
public boolean is_selected() {
return _selected;
}
/**
* @param _selected the _selected to set
*/
public void set_selected(boolean _selected) {
this._selected = _selected;
}
public String get_mavenRepositoryURL() {
return _mavenRepositoryURL;
}
/**
* @param _mavenRepositoryURL the _downloadFileName to set
*/
public void set_mavenRepositoryURL(String _mavenRepositoryURL) {
this._mavenRepositoryURL = _mavenRepositoryURL;
}
}
| asposemarketplace/Aspose_Maven_for_NetBeans | src/com/aspose/maven/utils/AsposeJavaAPI.java | Java | mit | 1,078 |
/*
* 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.myfaces.flow.cdi;
import java.io.Serializable;
/**
* This class is a wrapper used to deal with concurrency issues when accessing the inner LRUMap.
*/
class FacesFlowClientWindowCollection implements Serializable
{
private ClientWindowFacesFlowLRUMap lruMap;
public FacesFlowClientWindowCollection(ClientWindowFacesFlowLRUMap lruMap)
{
this.lruMap = lruMap;
}
public FacesFlowClientWindowCollection()
{
}
public synchronized void put(String key, String value)
{
lruMap.put(key, value);
}
public synchronized String get(String key)
{
return (String) lruMap.get(key);
}
public synchronized void remove(String key)
{
lruMap.remove(key);
}
public synchronized boolean isEmpty()
{
return lruMap.isEmpty();
}
public void setFlowScopeBeanHolder(FlowScopeBeanHolder holder)
{
lruMap.setFlowScopeBeanHolder(holder);
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/flow/cdi/FacesFlowClientWindowCollection.java | Java | epl-1.0 | 1,809 |
/*******************************************************************************
* Copyright (c) 1997, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jsp.taglib;
import java.util.HashMap;
import javax.servlet.jsp.tagext.TagAttributeInfo;
import javax.servlet.jsp.tagext.TagInfo;
import com.ibm.ws.jsp.JspCoreException;
import com.ibm.wsspi.jsp.context.JspCoreContext;
public class TagFileClassInfo extends TagClassInfo {
private TagInfo ti = null;
public TagFileClassInfo(TagInfo ti) {
super();
this.ti = ti;
implementsIterationTag = false;
implementsBodyTag = false;
implementsTryCatchFinally = false;
implementsSimpleTag = true;
implementsDynamicAttributes = ti.hasDynamicAttributes();
}
public String getTagClassName() {
return ti.getTagClassName();
}
public String getSetterMethodName(String attributeName) throws JspCoreException {
String setterMethodName = null;
if (setterMethodNameMap == null) {
setterMethodNameMap = new HashMap();
}
setterMethodName = (String)setterMethodNameMap.get(attributeName);
if (setterMethodName == null) {
char chars[] = attributeName.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
setterMethodName = new String(chars);
setterMethodName = "set" + setterMethodName;
setterMethodNameMap.put(attributeName, setterMethodName);
}
return (setterMethodName);
}
public String getPropertyEditorClassName(String attributeName) throws JspCoreException {
return (null);
}
//PK36246 && 417178 override method in TagClassInfo, but since we aren't loading a class right now, we don't have to worry about the classpath in the context
public String getParameterClassName(String attributeName, JspCoreContext context) throws JspCoreException {
String parameterClassName = null;
if (parameterClassNameMap == null) {
parameterClassNameMap = new HashMap();
}
parameterClassName = (String)parameterClassNameMap.get(attributeName);
if (parameterClassName == null) {
TagAttributeInfo[] attributeInfos = ti.getAttributes();
for (int i = 0; i < attributeInfos.length; i++) {
if (attributeInfos[i].getName().equals(attributeName)) {
//PK69319
if(attributeInfos[i].isFragment()){
parameterClassName = "javax.servlet.jsp.tagext.JspFragment";
} else{
parameterClassName = attributeInfos[i].getTypeName();
}
parameterClassNameMap.put(attributeName, parameterClassName);
break;
}
}
}
return (parameterClassName);
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/taglib/TagFileClassInfo.java | Java | epl-1.0 | 3,358 |
/*******************************************************************************
* Copyright (c) 2014 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.apache.bval.jsr303.resolver;
/**
* This is a no-op extender so that we maintain compatibility with bean validation
* 1.0 apps that explicitly listed this apache traversable resolver class
* in the <traversable-resolver> element in validation.xml.
*
* <p>
* Apache Bean Validation changed the package name in their 1.1 implementation,
* so we provide this class with the original package name to allow 1.0 applications
* to move up without needing to change their application.
*/
public class JPATraversableResolver extends org.apache.bval.jsr.resolver.JPATraversableResolver {
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.org.apache.bval.1.1.0/src/org/apache/bval/jsr303/resolver/JPATraversableResolver.java | Java | epl-1.0 | 1,138 |
//-----BEGIN DISCLAIMER-----
/*******************************************************************************
* Copyright (c) 2012, 2021 JCrypTool Team and Contributors
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
//-----END DISCLAIMER-----
package org.jcryptool.crypto.ui.textblockloader;
import java.util.List;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.jcryptool.crypto.ui.textblockloader.conversion.ConversionStringToBlocks;
import org.jcryptool.crypto.ui.textsource.TextInputWithSource;
public class TextAsNumbersLoaderWizard extends Wizard {
protected TANLOriginChooserPage pageInputMethod;
protected TANLTextPage pageTextToNumbersPage;
protected TANLBlockConversionPage pageBlockParams;
protected TANLNumberLoaderPage pageNumbersOnly;
protected int maxNumber;
private boolean numbersOnlyInput;
public static final String METHOD_TEXT_BASED = "METHOD_TEXT_BASED"; //$NON-NLS-1$
public static final String METHOD_NUMERIC = "METHOD_NUMERIC"; //$NON-NLS-1$
public TextAsNumbersLoaderWizard(int maxNumber, boolean numbersOnlyInput) {
this.maxNumber = maxNumber;
this.numbersOnlyInput = numbersOnlyInput;
setWindowTitle(Messages.TextAsNumbersLoaderWizard_wtitle_overall);
pageInputMethod = new TANLOriginChooserPage();
pageTextToNumbersPage = new TANLTextPage(this.maxNumber);
pageBlockParams = new TANLBlockConversionPage(this.maxNumber);
pageNumbersOnly = new TANLNumberLoaderPage(this.maxNumber);
}
@Override
public void addPages() {
addPage(getPageInputMethod());
addPage(getPageNumbersOnly());
addPage(getPageTextToNumbersPage());
addPage(getPageBlockParams());
}
@Override
public boolean performFinish() {
//TODO:
return true;
}
@Override
public IWizardPage getStartingPage() {
if(this.numbersOnlyInput) {
return getPageNumbersOnly();
} else {
return getPageInputMethod();
}
}
@Override
public IWizardPage getPreviousPage(IWizardPage page) {
if(this.numbersOnlyInput) {
if(page == getPageNumbersOnly()) return null;
return super.getPreviousPage(page);
} else {
return super.getPreviousPage(page);
}
}
@Override
public IWizardPage getNextPage(IWizardPage page) {
if(page == getPageInputMethod()) {
if(getDataInputMethod().equals(TextAsNumbersLoaderWizard.METHOD_NUMERIC)) {
return getPageNumbersOnly();
} else {
return getPageTextToNumbersPage();
}
} else if(page == getPageTextToNumbersPage()) {
return getPageBlockParams();
} else if(page == getPageBlockParams()) {
return null;
} else if(page == getPageNumbersOnly()) {
return null;
}
return null;
}
@Override
public boolean canFinish() {
boolean numbersOnly = getDataInputMethod().equals(METHOD_NUMERIC);
boolean byAlpha = getDataInputMethod().equals(METHOD_TEXT_BASED);
boolean numbersOnlyComplete = isByNumbersOnlyDataSufficient();
boolean byAlphaComplete = isByAlphaDataSufficient();
boolean canFinish = (numbersOnly && numbersOnlyComplete) || (byAlpha && byAlphaComplete);
return canFinish;
}
private boolean isByAlphaDataSufficient() {
return isNumbersDataComplete(getDataBlocksByText());
}
private boolean isByNumbersOnlyDataSufficient() {
return isNumbersDataComplete(getDataBlocksByNumericInput());
}
private boolean isNumbersDataComplete(List<Integer> data) {
return data.size() > 0;
}
public TANLOriginChooserPage getPageInputMethod() {
return pageInputMethod;
}
public TANLTextPage getPageTextToNumbersPage() {
return pageTextToNumbersPage;
}
public TANLBlockConversionPage getPageBlockParams() {
return pageBlockParams;
}
public TANLNumberLoaderPage getPageNumbersOnly() {
return pageNumbersOnly;
}
public ConversionCharsToNumbers getCTN() {
return getPageTextToNumbersPage().getCharsToNumbersConversionInput().getContent();
}
public ConversionStringToBlocks getSTBConversion() {
ConversionCharsToNumbers ctn = getCTN();
ConversionNumbersToBlocks ntb = getPageBlockParams().getBlockMethodInput().getContent();
ConversionStringToBlocks conversion = new ConversionStringToBlocks(ctn, ntb);
return conversion;
}
public String getDataInputMethod() {
if(this.numbersOnlyInput) return METHOD_NUMERIC;
return getPageInputMethod().getMethod();
}
public TextInputWithSource getText() {
return getPageTextToNumbersPage().getTextInput().getContent();
}
public List<Integer> getDataBlocksByText() {
String stringData = getText().getText();
List<Integer> blocks = getSTBConversion().convert(stringData);
return blocks;
}
public List<Integer> getDataBlocksByNumericInput() {
return getPageNumbersOnly().getNumbers();
}
public List<Integer> getDataBlocks() {
if(getDataInputMethod().equals(METHOD_NUMERIC)) {
return getDataBlocksByNumericInput();
} else {
return getDataBlocksByText();
}
}
}
| jcryptool/crypto | org.jcryptool.crypto.ui/src/org/jcryptool/crypto/ui/textblockloader/TextAsNumbersLoaderWizard.java | Java | epl-1.0 | 5,142 |
package org.python.pydev.shared_core.partitioner;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
/**
* An implementation of {@link IRule} capable of detecting words. A word rule also allows to
* associate a token to a word. That is, not only can the rule be used to provide tokens for exact
* matches, but also for the generalized notion of a word in the context in which it is used. A word
* rule uses a word detector to determine what a word is.
*
* @see IWordDetector
*/
public class WordRule implements IRule {
/** Internal setting for the un-initialized column constraint. */
protected static final int UNDEFINED = -1;
/** The word detector used by this rule. */
protected IWordDetector fDetector;
/** The default token to be returned on success and if nothing else has been specified. */
protected IToken fDefaultToken;
/** The column constraint. */
protected int fColumn = UNDEFINED;
/** The table of predefined words and token for this rule. */
protected Map<String, IToken> fWords = new HashMap<>();
/** Buffer used for pattern detection. */
private StringBuffer fBuffer = new StringBuffer();
/**
* Tells whether this rule is case sensitive.
* @since 3.3
*/
private boolean fIgnoreCase = false;
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the scanner
* will be rolled back and an undefined token will be returned in order to allow
* any subsequent rules to analyze the characters.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
* @see #addWord(String, IToken)
*/
public WordRule(IWordDetector detector) {
this(detector, Token.UNDEFINED, false);
}
/**
* Creates a rule which, with the help of a word detector, will return the token
* associated with the detected word. If no token has been associated, the
* specified default token will be returned.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
* @param defaultToken the default token to be returned on success
* if nothing else is specified, may not be <code>null</code>
* @see #addWord(String, IToken)
*/
public WordRule(IWordDetector detector, IToken defaultToken) {
this(detector, defaultToken, false);
}
/**
* Creates a rule which, with the help of a word detector, will return the token
* associated with the detected word. If no token has been associated, the
* specified default token will be returned.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
* @param defaultToken the default token to be returned on success
* if nothing else is specified, may not be <code>null</code>
* @param ignoreCase the case sensitivity associated with this rule
* @see #addWord(String, IToken)
* @since 3.3
*/
public WordRule(IWordDetector detector, IToken defaultToken, boolean ignoreCase) {
Assert.isNotNull(detector);
Assert.isNotNull(defaultToken);
fDetector = detector;
fDefaultToken = defaultToken;
fIgnoreCase = ignoreCase;
}
/**
* Adds a word and the token to be returned if it is detected.
*
* @param word the word this rule will search for, may not be <code>null</code>
* @param token the token to be returned if the word has been found, may not be <code>null</code>
*/
public void addWord(String word, IToken token) {
Assert.isNotNull(word);
Assert.isNotNull(token);
// If case-insensitive, convert to lower case before adding to the map
if (fIgnoreCase) {
word = word.toLowerCase();
}
fWords.put(word, token);
}
/**
* Sets a column constraint for this rule. If set, the rule's token
* will only be returned if the pattern is detected starting at the
* specified column. If the column is smaller then 0, the column
* constraint is considered removed.
*
* @param column the column in which the pattern starts
*/
public void setColumnConstraint(int column) {
if (column < 0) {
column = UNDEFINED;
}
fColumn = column;
}
@Override
public IToken evaluate(ICharacterScanner scanner) {
int c = scanner.read();
if (c != ICharacterScanner.EOF && fDetector.isWordStart((char) c)) {
if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) {
fBuffer.setLength(0);
do {
fBuffer.append((char) c);
c = scanner.read();
} while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c));
scanner.unread();
String buffer = fBuffer.toString();
// If case-insensitive, convert to lower case before accessing the map
if (fIgnoreCase) {
buffer = buffer.toLowerCase();
}
IToken token = fWords.get(buffer);
if (token != null) {
return token;
}
if (fDefaultToken.isUndefined()) {
unreadBuffer(scanner);
}
return fDefaultToken;
}
}
scanner.unread();
return Token.UNDEFINED;
}
/**
* Returns the characters in the buffer to the scanner.
*
* @param scanner the scanner to be used
*/
protected void unreadBuffer(ICharacterScanner scanner) {
for (int i = fBuffer.length() - 1; i >= 0; i--) {
scanner.unread();
}
}
}
| fabioz/Pydev | plugins/org.python.pydev.shared_core/src/org/python/pydev/shared_core/partitioner/WordRule.java | Java | epl-1.0 | 5,923 |
/*******************************************************************************
* Copyright (c) 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.microprofile.faulttolerance20.state.impl;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import com.ibm.ws.microprofile.faulttolerance20.state.AsyncBulkheadState;
/**
* An implementation of {@link AsyncBulkheadState} which does not implement any bulkhead logic
* <p>
* Although it does not implement any bulkhead logic, it will schedule any tasks passed to {@link #submit(AsyncBulkheadTask, ExceptionHandler)} to be run asynchronously.
*/
public class AsyncBulkheadStateNullImpl implements AsyncBulkheadState {
private final ScheduledExecutorService executorService;
private static final BulkheadReservationNullImpl NULL_RESERVATION = new BulkheadReservationNullImpl();
public AsyncBulkheadStateNullImpl(ScheduledExecutorService executorService) {
this.executorService = executorService;
}
@Override
public ExecutionReference submit(AsyncBulkheadTask task, ExceptionHandler exceptionHandler) {
Future<?> future = executorService.submit(() -> task.run(NULL_RESERVATION));
return new ExecutionReferenceNullImpl(future);
}
private static class ExecutionReferenceNullImpl implements ExecutionReference {
private final Future<?> future;
public ExecutionReferenceNullImpl(Future<?> future) {
this.future = future;
}
@Override
public void abort(boolean mayInterrupt) {
future.cancel(mayInterrupt);
}
@Override
public boolean wasAccepted() {
return true;
}
}
private static class BulkheadReservationNullImpl implements BulkheadReservation {
@Override
public void release() {
// Do nothing
}
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.faulttolerance.2.0/src/com/ibm/ws/microprofile/faulttolerance20/state/impl/AsyncBulkheadStateNullImpl.java | Java | epl-1.0 | 2,317 |
//$
package org.hibernate.test.annotations.idmanytoone.alphabetical;
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
@Embeddable
public class BId implements Serializable {
@ManyToOne
@JoinColumns( {
@JoinColumn( name = "aId", nullable = false ),
@JoinColumn( name = "bSequenceNumber", nullable = false )
} )
private C parent;
private int sequenceNumber;
public BId() {
}
public C getParent() {
return parent;
}
public void setParent(C parent) {
this.parent = parent;
}
public int getSequenceNumber() {
return sequenceNumber;
}
public void setSequenceNumber(int sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ( ( parent == null ) ? 0 : parent.hashCode() );
result = prime * result + sequenceNumber;
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj )
return true;
if ( obj == null )
return false;
if ( getClass() != obj.getClass() )
return false;
final BId other = (BId) obj;
if ( parent == null ) {
if ( other.parent != null )
return false;
}
else if ( !parent.equals( other.parent ) )
return false;
if ( sequenceNumber != other.sequenceNumber )
return false;
return true;
}
}
| ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/annotations/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/BId.java | Java | epl-1.0 | 1,439 |
//-----BEGIN DISCLAIMER-----
/*******************************************************************************
* Copyright (c) 2011, 2021 JCrypTool Team and Contributors
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
//-----END DISCLAIMER-----
package org.jcryptool.analysis.friedman.views;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.jcryptool.analysis.friedman.IFriedmanAccess;
import org.jcryptool.analysis.friedman.ui.FriedmanGraphUI;
public class FriedmanView extends ViewPart implements IFriedmanAccess {
@Override
public void execute(boolean executeCalc) {
myUI.execute(executeCalc);
}
public String getCachedResult() {
return myUI.getCachedResult();
}
private FriedmanGraphUI myUI;
/**
* This is a callback that will allow us to create the viewer and initialize it.
*/
@Override
public void createPartControl(Composite parent) {
myUI = new FriedmanGraphUI(parent, SWT.NONE);
PlatformUI.getWorkbench().getHelpSystem().setHelp(parent,
"org.jcryptool.analysis.friedman.friedman"); //$NON-NLS-1$
hookActionBar();
}
private void hookActionBar() {
IToolBarManager mgr = getViewSite().getActionBars().getToolBarManager();
mgr.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
getViewSite().getActionBars().updateActionBars();
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
myUI.setFocus();
}
} | jcryptool/crypto | org.jcryptool.analysis.friedman/src/org/jcryptool/analysis/friedman/views/FriedmanView.java | Java | epl-1.0 | 2,051 |
/*******************************************************************************
* Copyright (c) 2017 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@org.osgi.annotation.versioning.Version("1.0.16")
package com.ibm.ws.sib.processor.test;
| OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/processor/test/package-info.java | Java | epl-1.0 | 624 |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.sal.binding.model.api;
import java.util.List;
/**
* The Method Signature interface contains simplified meta model for java method
* definition. Each method MUST be defined by name, return type, parameters and
* access modifier. <br>
* Additionally method MAY contain associated annotations and comment. By
* contract if method does not contain any comments or annotation definitions
* the {@link #getComment()} SHOULD rather return empty string and
* {@link #getAnnotations()} SHOULD rather return empty list than
* <code>null</code> values. <br>
* The defining Type contains the reference to Generated Type that declares
* Method Signature.
*/
public interface MethodSignature extends TypeMember {
/**
* Returns <code>true</code> if the method signature is defined as abstract. <br>
* By default in java all method declarations in interface are defined as
* abstract, but the user don't need necessary to declare abstract keyword
* in front of each method. <br>
* The abstract methods are allowed in Class definitions but only when the
* class is declared as abstract.
*
* @return <code>true</code> if the method signature is defined as abstract.
*/
boolean isAbstract();
/**
* Returns the List of parameters that method declare. If the method does
* not contain any parameters, the method will return empty List.
*
* @return the List of parameters that method declare.
*/
List<Parameter> getParameters();
/**
* The Parameter interface is designed to hold the information of method
* Parameter(s). The parameter is defined by his Name which MUST be unique
* as java does not allow multiple parameters with same names for one method
* and Type that is associated with parameter.
*/
interface Parameter {
/**
* Returns the parameter name.
*
* @return the parameter name.
*/
String getName();
/**
* Returns Type that is bounded to parameter name.
*
* @return Type that is bounded to parameter name.
*/
Type getType();
}
}
| 522986491/yangtools | code-generator/binding-model-api/src/main/java/org/opendaylight/yangtools/sal/binding/model/api/MethodSignature.java | Java | epl-1.0 | 2,512 |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.sal.binding.generator.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
public class GenTypesSubSetTest {
@Test
public void genTypesFromSubsetOfTwoModulesTest() throws Exception {
File abstractTopology = new File(getClass().getResource(
"/leafref-test-models/[email protected]").toURI());
File ietfInterfaces = new File(getClass().getResource("/ietf/ietf-interfaces.yang").toURI());
File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
File ietfYangTypes = new File(getClass().getResource("/ietf/ietf-yang-types.yang").toURI());
final SchemaContext context = new YangParserImpl().parseFiles(Arrays.asList(abstractTopology, ietfInterfaces,
ietfInetTypes, ietfYangTypes));
Set<Module> modules = context.getModules();
final Set<Module> toGenModules = new HashSet<>();
for (final Module module : modules) {
if (module.getName().equals("abstract-topology")) {
toGenModules.add(module);
} else if (module.getName().equals("ietf-interfaces")) {
toGenModules.add(module);
}
}
assertEquals("Set of to Generate Modules must contain 2 modules", 2, toGenModules.size());
assertNotNull("Schema Context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
final List<Type> genTypes = bindingGen.generateTypes(context, toGenModules);
assertNotNull("genTypes is null", genTypes);
assertFalse("genTypes is empty", genTypes.isEmpty());
assertEquals("Expected Generated Types from provided sub set of " + "modules should be 23!", 23,
genTypes.size());
}
@Test
public void genTypesFromSubsetOfThreeModulesTest() throws Exception {
File abstractTopology = new File(getClass().getResource(
"/leafref-test-models/[email protected]").toURI());
File ietfInterfaces = new File(getClass().getResource("/ietf/ietf-interfaces.yang").toURI());
File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
File ietfYangTypes = new File(getClass().getResource("/ietf/ietf-yang-types.yang").toURI());
File ianaIfType = new File(getClass().getResource("/ietf/iana-if-type.yang").toURI());
final SchemaContext context = new YangParserImpl().parseFiles(Arrays.asList(abstractTopology, ietfInterfaces,
ietfInetTypes, ietfYangTypes, ianaIfType));
assertNotNull("Schema Context is null", context);
final Set<Module> modules = context.getModules();
final Set<Module> toGenModules = new HashSet<>();
for (final Module module : modules) {
if (module.getName().equals("abstract-topology")) {
toGenModules.add(module);
} else if (module.getName().equals("ietf-interfaces")) {
toGenModules.add(module);
} else if (module.getName().equals("iana-if-type")) {
toGenModules.add(module);
}
}
assertEquals("Set of to Generate Modules must contain 3 modules", 3, toGenModules.size());
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
final List<Type> genTypes = bindingGen.generateTypes(context, toGenModules);
assertNotNull("genTypes is null", genTypes);
assertFalse("genTypes is empty", genTypes.isEmpty());
assertEquals("Expected Generated Types", 24, genTypes.size());
}
}
| 522986491/yangtools | code-generator/binding-generator-impl/src/test/java/org/opendaylight/yangtools/sal/binding/generator/impl/GenTypesSubSetTest.java | Java | epl-1.0 | 4,529 |
/*******************************************************************************
* Copyright (c) 2013, 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.ejbcontainer.fat.rar.message;
import java.util.Timer;
import javax.resource.ResourceException;
import javax.resource.spi.UnavailableException;
import javax.resource.spi.XATerminator;
import javax.resource.spi.work.Work;
import javax.resource.spi.work.WorkException;
import javax.resource.spi.work.WorkManager;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import com.ibm.ws.ejbcontainer.fat.rar.work.FVTWorkImpl;
/**
* <p>This interface defines the methods to send messages to the endpoint applications
* via testing resource adapter. The work manager from the application server will be
* involved in sending the messages. An implementation of this interface serves as a
* message provider. </p>
*
* <p>The target user of this interface is J2C FVT.</p>
*/
public interface FVTMessageProvider extends FVTBaseMessageProvider {
static int DO_WORK = 1;
static int START_WORK = DO_WORK + 1;
static int SCHEDULE_WORK = DO_WORK + 2;
static int NO_WORK = DO_WORK + 3;
/**
* <p>This method sends a message to a particular endpoint application via work
* manager and waits until the message is delivered. </p>
*
* <p>This method call blocks until the message delivery is completed.</p>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this message delivery. If you don't provide deliveryId,
* you won't be able to retreive the information.
* @param beanName the message endpoint name
* @param message the message going to be delivered to the message endpoint
* @param xaResource the XAResource object used for getting transaction notifications. Set
* to null if you don't want to get transaction notifications.
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
*
* @exception ResourceException
*/
void sendMessage(String deliveryId, String beanName, String message, XAResource xaResource, Xid xid) throws ResourceException;
/**
* <p>This method sends one or more messages to one or more endpoint applications
* via work manager and waits until all the message are delivered. </p>
*
* <p>This call blocks until all the message deliveries are completed.</p>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and work object. If you don't provide deliveryId, you won't be able to retrieve
* the information.
* @param message the FVT message object.
* @param xid the XID which represents the imported transaction. Set this parameter to
* null if no imported transaction exists.
*
* @exception ResourceException
*
* @see FVTMessage
*/
void sendMessage(String deliveryId, FVTMessage message, Xid xid) throws ResourceException;
/**
* <p>This method asynchronously sends a message to a particular endpoint
* application via work manager. </p>
*
* <p>This method call won't block the execution. It returns once the message
* is accepted by the application server to deliver. </p>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this message delivery. If you don't provide deliveryId,
* you won't be able to retrieve the information.
* @param beanName the message endpoint name
* @param message the message going to be delivered to the message endpoint
* @param xaResource the XAResource object used for getting transaction notifications. Set
* to null if you don't want to get transaction notifications.
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
*
* @exception ResourceException
*/
void sendMessageNoWait(String deliveryId, String beanName, String message, XAResource xaResource, Xid xid) throws ResourceException;
/**
* <p>This method asynchronously sends one or more messages to one or more endpoint
* applications via work manager.</p>
*
* <p>This method call won't block the execution. It returns once the message is
* accepted by the application server to deliver. </p>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and work object. If you don't provide deliveryId, you won't be able to retrieve
* the information.
* @param message the FVT message object.
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
*
* @exception ResourceException
*
* @see FVTMessage
*/
void sendMessageNoWait(String deliveryId, FVTMessage message, Xid xid) throws ResourceException;
/**
* <p>This method sends a message to a particular endpoint application via work
* manager and returns once a certain state is reached.</p>
*
* <p> This method call will block the execution until the work, which
* delivers the message, reaches certain state.</p>
*
* <p>There are four possible states:<br>
* <UL>
* <LI>WORK_ACCEPTED</LI>
* <LI>WORK_REJECTED</LI>
* <LI>WORK_STARTED</LI>
* <LI>Work_COMPLETED</LI>
* </UL></P>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this message delivery. If you don't provide deliveryId,
* you won't be able to retrieve the information.
* @param beanName the message endpoint name
* @param message the message going to be delivered to the message endpoint
* @param state the state which the work instance has reached when the method call returns.
* @param xaResource the XAResource object used for getting transaction notifications. Set
* to null if you don't want to get transaction notifications.
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
*
* @exception ResourceException
*/
void sendMessageWait(String deliveryId, String beanName, String message, int state, XAResource xaResource, Xid xid) throws ResourceException;
/**
* <p>This method sends one or more messages to one or more endpoint applications
* via work manager and returns once a certain satus is reached. </p>
*
* <p> This method call will block the execution until the work, which
* delivers the message, reaches certain state.</p>
*
* <p>There are four possible states:<br>
* <UL>
* <LI>WORK_ACCEPTED</LI>
* <LI>WORK_REJECTED</LI>
* <LI>WORK_STARTED</LI>
* <LI>Work_COMPLETED</LI>
* </UL></P>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this message delivery. If you don't provide deliveryId,
* you won't be able to retrieve the information.
* @param message the FVT message object.
* @param state the state which the work instance has reached when the method call returns.
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
*
* @exception ResourceException
*
* @see FVTMessage
*/
void sendMessageWait(String deliveryId, FVTMessage message, int state, Xid xid) throws ResourceException;
/**
* <p>This method sends a message to a particular endpoint application and returns once a
* certain state is reached.</p>
*
* <p>This method call will block the execution until the work, which
* delivers the message, reaches certain state.</p>
*
* <p>The maximum waiting time is waitTime millisecond. Once the waitTime is reached, the
* method will return even if the work instance hasn't reach the specified state yet</p>
*
* <p>There are four possible state:<br>
* <UL>
* <LI>WORK_ACCEPTED</LI>
* <LI>WORK_REJECTED</LI>
* <LI>WORK_STARTED</LI>
* <LI>Work_COMPLETED</LI>
* </UL></P>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this message delivery. If you don't provide deliveryId,
* you won't be able to retrieve these information.
* @param beanName the message endpoint name
* @param message the message going to be delivered to the message endpoint
* @param state the state which the work instance has reached when the method call returns.
* @param waitTime This parameter specifies the maximum waiting time. Once the waitTime
* is reached, the method will return even if the work instance hasn't reach the specified
* state yet</p>
* @param xaResource the XAResource object used for getting transaction notifications. Set
* to null if you don't want to get transaction notifications.
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
*
* @exception ResourceException
*/
void sendMessageWait(String deliveryId, String beanName, String message, int state, int waitTime, XAResource xaResource, Xid xid) throws ResourceException;
/**
* <p>This method sends one or more messages to one or more endpoint applications and
* returns once a certain status is reached.
*
* <p> This method call will block the execution until the work, which
* delivers the message, reaches certain state.</p>
*
* <p>The maximum waiting time is waitTime millisecond. Once the waitTime is reached, the
* method will return even if the work instance hasn't reach the specified state yet</p>
*
* <p>There are four possible state:<br>
* <UL>
* <LI>WORK_ACCEPTED</LI>
* <LI>WORK_REJECTED</LI>
* <LI>WORK_STARTED</LI>
* <LI>Work_COMPLETED</LI>
* </UL></P>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this message delivery. If you don't provide deliveryId,
* you won't be able to retrieve these information.
* @param message the FVT message object.
* @param state the state which the work instance has reached when the method call returns.
* @param waitTime This parameter specifies the maximum waiting time. Once the waitTime
* is reached, the method will return even if the work instance hasn't reach the specified
* state yet</p>
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
*
* @exception ResourceException
*
* @see FVTMessage
*/
void sendMessageWait(String deliveryId, FVTMessage message, int state, int waitTime, Xid xid) throws ResourceException;
/**
* <p>This method sends one or more messages to one or more endpoint applications and
* returns once a certain status is reached. You can specify how to submit the work
* to the work manager.</P>
*
* <p> This method call will block the execution until the work, which
* delivers the message, reaches certain state.</p>
*
* <p>The maximum waiting time is waitTime millisecond. Once the waitTime is reached, the
* method will return even if the work instance hasn't reach the specified state yet</p>
*
* <p>There are four possible state:<br>
* <UL>
* <LI>WORK_ACCEPTED</LI>
* <LI>WORK_REJECTED</LI>
* <LI>WORK_STARTED</LI>
* <LI>Work_COMPLETED</LI>
* </UL></P>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this message delivery. If you don't provide deliveryId,
* you won't be able to retrieve these information.
* @param message the FVT message object.
* @param state the state which the work instance has reached when the method call returns.
* @param waitTime This parameter specifies the maximum waiting time. Once the waitTime
* is reached, the method will return even if the work instance hasn't reach the specified
* state yet</p>
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
* @param doWorkType how to submit the work the work manager. It could be any of the
* following: DO_WORK, START_WORK or SCHEDULE_WORK
*
* @exception ResourceException
*
* @see FVTMessage
*/
void sendMessageWait(String deliveryId, FVTMessage message, int state, int waitTime, Xid xid, int doWorkType) throws ResourceException;
/**
* <p>This method sends one or more messages to one or more endpoint applications and
* returns once a certain status is reached. You can specify how to submit the work
* to the work manager.</P>
*
* <p> This method call will block the execution until the work, which
* delivers the message, reaches certain state.</p>
*
* <p>The maximum waiting time is waitTime millisecond. Once the waitTime is reached, the
* method will return even if the work instance hasn't reach the specified state yet</p>
*
* <p>There are four possible state:<br>
* <UL>
* <LI>WORK_ACCEPTED</LI>
* <LI>WORK_REJECTED</LI>
* <LI>WORK_STARTED</LI>
* <LI>Work_COMPLETED</LI>
* </UL></P>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this message delivery. If you don't provide deliveryId,
* you won't be able to retrieve these information.
* @param message the FVT message object.
* @param state the state which the work instance has reached when the method call returns.
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
* @param doWorkType how to submit the work the work manager. It could be any of the
* following: DO_WORK, START_WORK or SCHEDULE_WORK
*
* @exception ResourceException
*
* @see FVTMessage
*/
void sendMessageWait(String deliveryId, FVTMessage message, int state, Xid xid, int doWorkType) throws ResourceException;
/**
* <p>This method call executes two or more works concurrently. This method is mainly
* used to test associating two or more works concurrently within a source managed
* transaction (EIS imported transaction). The caller will receive a WorkCompletedException
* set to the error code WorkException.TX_CONCURRENT_WORK_DISALLOWED</p>
*
* <p>This method cannot be called concurrently in several threads. That is, you can
* not initiate two threads, and have both of them call this method. This usage will lead to
* unexpected behavior. </p>
*
* <p>This method only guarantees executing these works concurrently. It doesn't guarantee
* delivering messages to endpoints concurrently.</p>
*
* @param works an array of Work instance. Currently, we only support executing the
* work instances which type or super type is FVTConcurrentWorkImpl.
* @param xid the XID which represents the imported transaction. If there is no
* import transaction, set xid to null.
* @param doWorkType how to submit the work the work manager. It could be any of the
* following: DO_WORK, START_WORK or SCHEDULE_WORK
* @param state the state which the work instance has reached when the method call returns.
* @param waitTime This parameter specifies the maximum time for waiting the work to
* reach the specified state. Once the waitTime is reached, the method will return
* even if the work instance hasn't reach the specified state yet.
*
* @exception WorkException Any WorkException. A WorkCompletedException set to the error code
* WorkException.TX_CONCURRENT_WORK_DISALLOWED is expected.
* @exception ResourceException
*/
void executeConcurrentWork(Work[] works, Xid xid, int doWorkType, int state) throws WorkException, ResourceException;
/**
* <p>This method call executes two or more works concurrently. This method is mainly
* used to test associating two or more works concurrently within different source managed
* transaction (EIS imported transaction). If these Xids are different, the call should
* be executed successfully.</p>
*
* <p>This method cannot be called concurrently in several threads. That is, you can
* not initiate two threads, and have both of them call this method. This usage will lead to
* unexpected behavior. </p>
*
* <p>This method only guarantees executing these works concurrently. It doesn't guarantee
* delivering messages to endpoints concurrently.</p>
*
* @param works an array of Work instance. Currently, we only support executing the
* work instances which type or super type is FVTConcurrentWorkImpl.
* @param xid an array of XIDs which represent different imported transaction.
* @param doWorkType how to submit the work the work manager. It could be any of the
* following: DO_WORK, START_WORK or SCHEDULE_WORK
* @param state the state which the work instance has reached when the method call returns.
* @param waitTime This parameter specifies the maximum time for waiting the work to
* reach the specified state. Once the waitTime is reached, the method will return
* even if the work instance hasn't reach the specified state yet.
*
* @exception WorkException Any WorkException. A WorkCompletedException set to the error code
* WorkException.TX_CONCURRENT_WORK_DISALLOWED is expected.
* @exception ResourceException
*/
void executeConcurrentWork(Work[] works, Xid[] xids, int doWorkType, int state) throws WorkException, ResourceException;
/**
* <p>This method returns the work instance associated with the message delivery id.</p>
*
* <p>After getting the work instance, the test application can call methods
* isWorkAccepted()/isWorkStarted()/isWorkCompleted/isWorkRejected of the work
* instance to test whether the work has been accepted/started/completed/rejected .</p>
*
* @param deliveryId the ID related to this message delivery. This message delivery ID
* is used to retrieve the work instance.
*
* @return an FVT work object.
*/
public FVTWorkImpl getWork(String deliveryId);
/**
* <p>Get the XATerminator from the application server to manage the imported
* transaction.</p>
*
* @return the XATerminator object
*/
XATerminator getXATerminator();
/**
* <p>Provides a handle to a WorkManager instance. The WorkManager instance could
* be used by the test case to do its work by submitting Work instances for
* execution. </p>
*
* @return a WorkManager instance
*/
WorkManager getWorkManager();
/**
* <p>Creates a new java.util.Timer instance. The Timer instance could be used
* to perform periodic Work executions or other tasks. </p>
*
* @return a new Timer instance.
*
* @exception UnavailableException indicates that a Timer instance is not
* available. The request may be retried later.
*/
Timer createTimer() throws UnavailableException;
/**
* <p>Create a work instance based on the passed-in FVTMessage object. </p>
*
* <p>This method is mainly used for work manager testing. FVT test case can
* call this method to get a work instance and submit this work instance
* to the work manager. </p>
*
* @param message an FVTMessage object
*
* @return a work instance
*/
Work createWork(FVTMessage message);
// d174256: Added by swai for Work that doesn't send through sendMessagexxx
// can still get the test results.
/**
* <p>This method returns an array of test results associated with a particular
* endpoint instance (identified by endpoint name and instance ID) in a specific
* delivery.
*
* @param inputWork this work instance is used to retrieve the endpoint
* wrapper instances if the Work is submitted by user instead of by sendMessagexxx
*
* @return an array of test results associated with a particular endpoint instance.
*/
MessageEndpointTestResults[] getTestResults(Work inputWork, String endpointName, int instanceId);
// d174256: Added by swai for Work that doesn't send through sendMessagexxx
// can still get the test results.
/**
* <p>This method returns the test result associated with the message delivery id. </p>
*
* <p>This method is only useful when there is only one test result added in this
* message delivery. If there is more than one test results added in the delivery,
* there is no guarantee which test result will be returned. Method callers should
* be aware of this.</p>
*
* @param inputWork this work instance is used to retrieve the endpoint
* wrapper instances if the Work is submitted by user instead of by sendMessagexxx
*
* @return a message endpoint test result object.
*/
MessageEndpointTestResults getTestResult(Work inputWork);
// d174256: Added by swai for Work that doesn't send through sendMessagexxx
// can still get the endpoints to cleanup the test results.
/**
* <p>This method hints the testing resource adapter to release all the information
* related to this Work instance. TRA will unset the test results of the endpoint
* instance. After calling this method, users cannot get any endpoint
* information from this Work instance any more. </p>
*
* @param inputWork this work instance is used to retrieve the endpoint
* wrapper instances if the Work is submitted by user instead of by sendMessagexxx.
* It should be created through FVTMessageProvider.createWork().
*/
// d174592
void releaseWork(Work inputWork);
/**
* <p>Deliver a nested work message represented by an FVTMessage object using doWork,
* scheduleWork, or startWork. If the doWorkType is DO_WORK, the method blocks until
* the message delivery is completed. If the doWorkType is SCHEDULE_WORK or START_WORK,
* the method blocks until the work instance has reached the specified state.</p>
*
* <p>This method is called by sendMessageWaitNestedWork method in the FVTMessageProviderImpl class.</p>
*
* <p>The work instance can be in the following four states:</p>
* <ul>
* <li>WORK_ACCEPTED</li>
* <li>WORK_REJECTED</li>
* <li>WORK_STARTED</li>
* <li>WORK_COMPLETED</li>
* </ul>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this delivery. If you don't provide deliveryId, you
* won't be able to retrieve these information.
* @param message an FVTMessage object
* @param state the state which the work instance has reached when the method call returns.
* @param waitTime This parameter specifies the maximum time for waiting the work to
* reach the specified state. Once the waitTime is reached, the method will return
* even if the work instance hasn't reach the specified state yet.
* @param doWorkType the work type of the parent nested work.
* It can be doWork, scheduleWork, or startWork
* @param nestedDoWorkType the work type of the child nested work.
* It can be doWork, scheduleWork, or startWork
* @param xid the XID which represents the imported transaction
*
* @exception ResourceException
*/
public void sendMessageWaitNestedWork(String deliveryId, FVTMessage message, int state, Xid xid, int doWorkType, int nestedDoWorkType) throws ResourceException;
/**
* <p>Deliver a nested work message represented by an FVTMessage object using doWork,
* scheduleWork, or startWork. If the doWorkType is DO_WORK, the method blocks until
* the message delivery is completed. If the doWorkType is SCHEDULE_WORK or START_WORK,
* the method blocks until the work instance has reached the specified state.</p>
*
* <p>This method is called by sendMessageWaitNestedWork method in the FVTMessageProviderImpl class.</p>
*
* <p>The work instace can be in the following four states:</p>
* <ul>
* <li>WORK_ACCEPTED</li>
* <li>WORK_REJECTED</li>
* <li>WORK_STARTED</li>
* <li>WORK_COMPLETED</li>
* </ul>
*
* @param deliveryId the ID related to this message delivery. You can use this message
* delivery ID to retrieve delivery-related information, such as endpoint instances
* and the work object used for this delivery. If you don't provide deliveryId, you
* won't be able to retrieve these information.
* @param message an FVTMessage object
* @param state the state which the work instance has reached when the method call returns.
* @param waitTime This parameter specifies the maximum time for waiting the work to
* reach the specified state. Once the waitTime is reached, the method will return
* even if the work instance hasn't reach the specified state yet.
* @param doWorkType the work type of the parent nested work.
* It can be doWork, scheduleWork, or startWork
* @param nestedDoWorkType the work type of the child nested work.
* It can be doWork, scheduleWork, or startWork
* @param xid the XID which represents the imported transaction
*
* @exception ResourceException
*/
public void sendMessageWaitNestedWork(String deliveryId, FVTMessage message, int state, Xid parentXid, Xid childXid, int doWorkType,
int nestedDoWorkType) throws ResourceException;
// @alvinso.1
String getProperty_a();
String getProperty_m();
void setProperty_a(String string);
void setProperty_m(String string);
public String getActivationName(String name);
} | kgibm/open-liberty | dev/com.ibm.ws.ejbcontainer.fat_tools_rar/src/com/ibm/ws/ejbcontainer/fat/rar/message/FVTMessageProvider.java | Java | epl-1.0 | 28,856 |
///////////////////////////////////////////////////////////////////////////////
//
// JTOpen (IBM Toolbox for Java - OSS version)
//
// Filename: CCSID37.java
//
// The source code contained herein is licensed under the IBM Public License
// Version 1.0, which has been approved by the Open Source Initiative.
// Copyright (C) 2011-2012 International Business Machines Corporation and
// others. All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////
package com.ibm.jtopenlite.ccsidConversion;
public class CCSID37 implements SingleByteConversion{
static CCSID37 singleton = new CCSID37();
public static SingleByteConversion getInstance() {
return singleton;
}
public int getCcsid() {
return 37;
}
public byte[] returnFromUnicode() {
return fromUnicode_;
}
public char[] returnToUnicode() {
return toUnicode_;
}
private static final char[] toUnicode_ = {
/* 0 */ '\u0000','\u0001','\u0002','\u0003','\u009C','\u0009','\u0086','\u007F','\u0097','\u008D','\u008E','\u000B','\u000C',(char)0xD,'\u000E','\u000F',
/* 10 */ '\u0010','\u0011','\u0012','\u0013','\u009D','\u0085','\u0008','\u0087','\u0018','\u0019','\u0092','\u008F','\u001C','\u001D','\u001E','\u001F',
/* 20 */ '\u0080','\u0081','\u0082','\u0083','\u0084',(char)0xA,'\u0017','\u001B','\u0088','\u0089','\u008A','\u008B','\u008C','\u0005','\u0006','\u0007',
/* 30 */ '\u0090','\u0091','\u0016','\u0093','\u0094','\u0095','\u0096','\u0004','\u0098','\u0099','\u009A','\u009B','\u0014','\u0015','\u009E','\u001A',
/* 40 */ '\u0020','\u00A0','\u00E2','\u00E4','\u00E0','\u00E1','\u00E3','\u00E5','\u00E7','\u00F1','\u00A2','\u002E','\u003C','\u0028','\u002B','\u007C',
/* 50 */ '\u0026','\u00E9','\u00EA','\u00EB','\u00E8','\u00ED','\u00EE','\u00EF','\u00EC','\u00DF','\u0021','\u0024','\u002A','\u0029','\u003B','\u00AC',
/* 60 */ '\u002D','\u002F','\u00C2','\u00C4','\u00C0','\u00C1','\u00C3','\u00C5','\u00C7','\u00D1','\u00A6','\u002C','\u0025','\u005F','\u003E','\u003F',
/* 70 */ '\u00F8','\u00C9','\u00CA','\u00CB','\u00C8','\u00CD','\u00CE','\u00CF','\u00CC','\u0060','\u003A','\u0023','\u0040',(char)0x27,'\u003D','\u0022',
/* 80 */ '\u00D8','\u0061','\u0062','\u0063','\u0064','\u0065','\u0066','\u0067','\u0068','\u0069','\u00AB','\u00BB','\u00F0','\u00FD','\u00FE','\u00B1',
/* 90 */ '\u00B0','\u006A','\u006B','\u006C','\u006D','\u006E','\u006F','\u0070','\u0071','\u0072','\u00AA','\u00BA','\u00E6','\u00B8','\u00C6','\u00A4',
/* a0 */ '\u00B5','\u007E','\u0073','\u0074','\u0075','\u0076','\u0077','\u0078','\u0079','\u007A','\u00A1','\u00BF','\u00D0','\u00DD','\u00DE','\u00AE',
/* b0 */ '\u005E','\u00A3','\u00A5','\u00B7','\u00A9','\u00A7','\u00B6','\u00BC','\u00BD','\u00BE','\u005B','\u005D','\u00AF','\u00A8','\u00B4','\u00D7',
/* c0 */ '\u007B','\u0041','\u0042','\u0043','\u0044','\u0045','\u0046','\u0047','\u0048','\u0049','\u00AD','\u00F4','\u00F6','\u00F2','\u00F3','\u00F5',
/* d0 */ '\u007D','\u004A','\u004B','\u004C','\u004D','\u004E','\u004F','\u0050','\u0051','\u0052','\u00B9','\u00FB','\u00FC','\u00F9','\u00FA','\u00FF',
/* e0 */ (char)0x5C,'\u00F7','\u0053','\u0054','\u0055','\u0056','\u0057','\u0058','\u0059','\u005A','\u00B2','\u00D4','\u00D6','\u00D2','\u00D3','\u00D5',
/* f0 */ '\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039','\u00B3','\u00DB','\u00DC','\u00D9','\u00DA','\u009F',};
private static byte[] fromUnicode_ = null;
/* dynamically generate the inverse table */
static {
fromUnicode_ = SingleByteConversionTable.generateFromUnicode(toUnicode_);
}
}
| devjunix/libjt400-java | jtopenlite/com/ibm/jtopenlite/ccsidConversion/CCSID37.java | Java | epl-1.0 | 3,625 |
/*******************************************************************************
* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Arnold Lankamp - interfaces and implementation
*******************************************************************************/
package org.eclipse.imp.pdb.facts.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.impl.util.collections.ShareableValuesHashSet;
/**
* This map is similar to the ShareableHashMap, but is indexed by a value (check with isEqual).
*
* @author Arnold Lankamp
*
* @param <V>
* The value type
*/
public final class ValueIndexedHashMap<V> implements Map<IValue, V>{
private final static int INITIAL_LOG_SIZE = 4;
private int modSize;
private int hashMask;
private Entry<V>[] data;
private int threshold;
private int load;
/**
* Constructor.
*/
public ValueIndexedHashMap(){
super();
modSize = INITIAL_LOG_SIZE;
int tableSize = 1 << modSize;
hashMask = tableSize - 1;
data = (Entry<V>[]) new Entry[tableSize];
threshold = tableSize;
load = 0;
}
/**
* Copy constructor
*
* @param valueIndexedHashMap
* The map to copy.
*/
public ValueIndexedHashMap(ValueIndexedHashMap<V> valueIndexedHashMap){
super();
modSize = valueIndexedHashMap.modSize;
int tableSize = 1 << modSize;
hashMask = tableSize - 1;
data = valueIndexedHashMap.data.clone();
threshold = tableSize;
load = valueIndexedHashMap.load;
}
/**
* Removes all the entries from this map.
*/
public void clear(){
modSize = INITIAL_LOG_SIZE;
int tableSize = 1 << modSize;
hashMask = tableSize - 1;
data = (Entry<V>[]) new Entry[tableSize];
threshold = tableSize;
load = 0;
}
/**
* Rehashes this map.
*/
private void rehash(){
modSize++;
int tableSize = 1 << modSize;
hashMask = tableSize - 1;
Entry<V>[] newData = (Entry<V>[]) new Entry[tableSize];
threshold = tableSize;
Entry<V>[] oldData = data;
for(int i = oldData.length - 1; i >= 0; i--){
Entry<V> entry = oldData[i];
if(entry != null){
// Determine the last unchanged entry chain.
Entry<V> lastUnchangedEntryChain = entry;
int newLastUnchangedEntryChainIndex = entry.hash & hashMask;
Entry<V> e = entry.next;
while(e != null){
int newIndex = e.hash & hashMask;
if(newIndex != newLastUnchangedEntryChainIndex){
lastUnchangedEntryChain = e;
newLastUnchangedEntryChainIndex = newIndex;
}
e = e.next;
}
newData[newLastUnchangedEntryChainIndex] = lastUnchangedEntryChain;
// Reconstruct the other entries (if necessary).
while(entry != lastUnchangedEntryChain){
int hash = entry.hash;
int position = hash & hashMask;
newData[position] = new Entry<>(hash, entry.key, entry.value, newData[position]);
entry = entry.next;
}
}
}
data = newData;
}
/**
* Makes sure the size of the entry array and the load of the map stay in proper relation to
* eachother.
*/
private void ensureCapacity(){
if(load > threshold){
rehash();
}
}
/**
* Replaces the value in the entry by the given value.
*
* @param position
* The position in the entry array where the entry is located.
* @param entry
* The entry in which the value must be replaced.
* @param newValue
* The value.
*/
private void replaceValue(int position, Entry<V> entry, V newValue){
Entry<V> e = data[position];
// Reconstruct the updated entry.
data[position] = new Entry<>(entry.hash, entry.key, newValue, entry.next);
// Reconstruct the other entries (if necessary).
while(e != entry){
data[position] = new Entry<>(e.hash, e.key, e.value, data[position]);
e = e.next;
}
}
/**
* Inserts the given key-value pair into this map. In case there already is a value associated
* with the given key, the value will be updated and the previous value returned.
*
* @param key
* The key
* @param value
* The value
* @return The previous value that was associated with the key (if any); null otherwise.
*/
public V put(IValue key, V value){
ensureCapacity();
int hash = key.hashCode();
int position = hash & hashMask;
Entry<V> currentStartEntry = data[position];
// Check if the key is already in here.
if(currentStartEntry != null){
Entry<V> entry = currentStartEntry;
do{
if(hash == entry.hash && entry.key.isEqual(key)){ // Replace if present.
replaceValue(position, entry, value);
return entry.value; // Return the old value.
}
entry = entry.next;
}while(entry != null);
}
data[position] = new Entry<>(hash, key, value, currentStartEntry); // Insert the new entry.
load++;
return null;
}
/**
* Removes the entry from this map that is identified by the given key (if present).
*
* @param key
* The key that identifies the entry to remove.
* @return The value that was associated with the given key; null if the key was not present in
* the map.
*/
public V remove(Object object){
IValue key = (IValue) object;
int hash = key.hashCode();
int position = hash & hashMask;
Entry<V> currentStartEntry = data[position];
if(currentStartEntry != null){
Entry<V> entry = currentStartEntry;
do{
if(hash == entry.hash && entry.key.isEqual(key)){
Entry<V> e = data[position];
data[position] = entry.next;
// Reconstruct the other entries (if necessary).
while(e != entry){
data[position] = new Entry<>(e.hash, e.key, e.value, data[position]);
e = e.next;
}
load--;
return entry.value; // Return the value.
}
entry = entry.next;
}while(entry != null);
}
return null; // Not found.
}
/**
* Retrieves the value from the entry in this map which is identified by the given key
* (if present).
*
* @param key
* The key that identifies the entry that contains the value.
* @return The retrieved value; null if not present.
*/
public V get(Object object){
IValue key = (IValue) object;
int hash = key.hashCode();
int position = hash & hashMask;
Entry<V> entry = data[position];
while(entry != null){
if(hash == entry.hash && key.isEqual(entry.key)) return entry.value;
entry = entry.next;
}
return null;
}
/**
* Checks if there is an entry present in this map, which is identified by the given key.
*
* @param key
* The key that identifies the entry.
* @return True if this map contains an entry which is identified by the given key;
* false otherwise.
*/
public boolean contains(IValue key){
return (get(key) != null);
}
/**
* Returns the number of entries this map contains.
*
* @return The number of entries this map contains.
*/
public int size(){
return load;
}
/**
* Checks whether or not this map is empty.
*
* @return True if this map was empty; false otherwise.
*/
public boolean isEmpty(){
return (load == 0);
}
/**
* Constructs an iterator for the entries in this map.
*
* @return An iterator for the entries in this map.
*/
public Iterator<Map.Entry<IValue, V>> entryIterator(){
return new EntryIterator<>(data);
}
/**
* Constructs an iterator for the keys in this map.
*
* @return An iterator for the keys in this map.
*/
public Iterator<IValue> keysIterator(){
return new KeysIterator<>(data);
}
/**
* Constructs an iterator for the values in this map.
*
* @return An iterator for the values in this map.
*/
public Iterator<V> valuesIterator(){
return new ValuesIterator<>(data);
}
/**
* Copies over all entries from the given map, to this map.
*/
public void putAll(Map<? extends IValue, ? extends V> otherMap){
Set<Map.Entry<IValue, V>> entrySet = (Set<Map.Entry<IValue, V>>) (Set<?>) otherMap.entrySet(); // Generics stink.
Iterator<Map.Entry<IValue, V>> entrySetIterator = entrySet.iterator();
while(entrySetIterator.hasNext()){
Map.Entry<IValue, V> next = entrySetIterator.next();
put(next.getKey(), next.getValue());
}
}
/**
* Checks if this map contains an entry with the given key.
*/
public boolean containsKey(Object object){
IValue key = (IValue) object;
int hash = key.hashCode();
int position = hash & hashMask;
Entry<V> entry = data[position];
while(entry != null){
if(hash == entry.hash && key.isEqual(entry.key)) return true;
entry = entry.next;
}
return false;
}
/**
* Checks if this map contains an entry with the given value.
*/
public boolean containsValue(Object value){
Iterator<V> valuesIterator = valuesIterator();
while(valuesIterator.hasNext()){
V nextValue = valuesIterator.next();
if(nextValue == value || (nextValue != null && nextValue.equals(value))){
return true;
}
}
return false;
}
/**
* Constructs a set containing all entries from this map.
*/
public Set<Map.Entry<IValue, V>> entrySet(){
ShareableHashSet<Map.Entry<IValue, V>> entrySet = new ShareableHashSet<>();
Iterator<Map.Entry<IValue, V>> entriesIterator = entryIterator();
while(entriesIterator.hasNext()){
entrySet.add(entriesIterator.next());
}
return entrySet;
}
/**
* Constructs a set containing all keys from this map.
*/
public Set<IValue> keySet(){
ShareableValuesHashSet keysSet = new ShareableValuesHashSet();
Iterator<IValue> keysIterator = keysIterator();
while(keysIterator.hasNext()){
keysSet.add(keysIterator.next());
}
return keysSet;
}
/**
* Constructs a collection containing all values from this map.
*/
public Collection<V> values(){
ShareableHashSet<V> valuesSet = new ShareableHashSet<>();
Iterator<V> valuesIterator = valuesIterator();
while(valuesIterator.hasNext()){
valuesSet.add(valuesIterator.next());
}
return valuesSet;
}
/**
* Prints the internal representation of this map to a string.
*
* @see java.lang.Object#toString()
*/
public String toString(){
StringBuilder buffer = new StringBuilder();
buffer.append('{');
for(int i = 0; i < data.length; i++){
buffer.append('[');
Entry<V> e = data[i];
if(e != null){
buffer.append(e);
e = e.next;
while(e != null){
buffer.append(',');
buffer.append(e);
e = e.next;
}
}
buffer.append(']');
}
buffer.append('}');
return buffer.toString();
}
/**
* Returns the current hash code of this map.
*
* @return The current hash code of this map.
*
* @see java.lang.Object#hashCode()
*/
public int hashCode(){
int hash = 0;
Iterator<IValue> keysIterator = keysIterator();
while(keysIterator.hasNext()){
hash ^= keysIterator.next().hashCode();
}
return hash;
}
/**
* Check whether or not the current content of this set is equal to that of the given object / map.
*
* @return True if the content of this set is equal to the given object / map.
*
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object o){
if(o == null) return false;
if(o.getClass() == getClass()){
ValueIndexedHashMap<V> other = (ValueIndexedHashMap<V>) o;
if(other.size() != size()) return false;
if(isEmpty()) return true; // No need to check if the maps are empty.
Iterator<Map.Entry<IValue, V>> otherIterator = other.entryIterator();
while(otherIterator.hasNext()){
Map.Entry<IValue, V> entry = otherIterator.next();
V otherValue = entry.getValue();
V thisValue = get(entry.getKey());
if(otherValue != thisValue && thisValue != null && !thisValue.equals(entry.getValue())) return false;
}
return true;
}
return false;
}
/**
* Entry, used for containing key-value pairs and constructing buckets.
*
* @author Arnold Lankamp
*
* @param <K>
* The key type
* @param <V>
* The value type
*/
private static class Entry<V> implements Map.Entry<IValue, V>{
public final int hash;
public final IValue key;
public final V value;
public final Entry<V> next;
/**
* Constructor
*
* @param hash
* The hash code of the key
* @param key
* The key
* @param value
* The value
* @param next
* A reference to the next entry in the bucket (if any).
*/
public Entry(int hash, IValue key, V value, Entry<V> next){
super();
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
/**
* Returns a reference to the key.
*
* @return A reference to the key.
*/
public IValue getKey(){
return key;
}
/**
* Returns a reference to the value.
*
* @return A reference to the value.
*/
public V getValue(){
return value;
}
/**
* Unsupported operation.
*
* @param value
* The value which we will not set.
* @return Null.
* @throws java.lang.UnsupportedOperationException
*
* @see java.util.Map.Entry#setValue(Object)
*/
public V setValue(V value){
throw new UnsupportedOperationException("The setting of values is not supported by this map implementation.");
}
/**
* Prints the internal representation of this entry to a string.
*
* @see java.lang.Object#toString()
*/
public String toString(){
StringBuilder buffer = new StringBuilder();
buffer.append('<');
buffer.append(key);
buffer.append(':');
buffer.append(value);
buffer.append('>');
return buffer.toString();
}
}
/**
* Iterator for entries.
*
* @author Arnold Lankamp
*
* @param <K>
* The key type.
* @param <V>
* The value type.
*/
private static class EntryIterator<V> implements Iterator<Map.Entry<IValue, V>>{
private final Entry<V>[] data;
private Entry<V> current;
private int index;
/**
* Constructor.
*
* @param entries
* The entries to iterator over.
*/
public EntryIterator(Entry<V>[] entries){
super();
data = entries;
index = data.length - 1;
current = new Entry<>(0, null, null, data[index]);
locateNext();
}
/**
* Locates the next entry in the map.
*/
private void locateNext(){
Entry<V> next = current.next;
if(next != null){
current = next;
return;
}
for(int i = index - 1; i >= 0 ; i--){
Entry<V> entry = data[i];
if(entry != null){
current = entry;
index = i;
return;
}
}
current = null;
index = 0;
}
/**
* Check if there are more elements in this iteration.
*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext(){
return (current != null);
}
/**
* Returns the next element in this iteration.
*
* @return The next element in this iteration.
* @throws NoSuchElementException
* Thrown if there are no more elements in this iteration when calling this
* method.
*
* @see java.util.Iterator#next()
*/
public Entry<V> next(){
if(!hasNext()) throw new UnsupportedOperationException("There are no more elements in this iterator.");
Entry<V> entry = current;
locateNext();
return entry;
}
/**
* Removal is not supported by this iterator.
*
* @throws java.lang.UnsupportedOperationException
*
* @see java.util.Iterator#remove()
*/
public void remove(){
throw new UnsupportedOperationException("This iterator doesn't support removal.");
}
}
/**
* Iterator for keys.
*
* @author Arnold Lankamp
*
* @param <K>
* The key type.
* @param <V>
* The value type.
*/
private static class KeysIterator<V> implements Iterator<IValue>{
private final EntryIterator<V> entryIterator;
/**
* Constructor.
*
* @param entries
* The entries to iterate over.
*/
public KeysIterator(Entry<V>[] entries){
super();
entryIterator = new EntryIterator<>(entries);
}
/**
* Check if there are more elements in this iteration.
*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext(){
return entryIterator.hasNext();
}
/**
* Returns the next element in this iteration.
*
* @return The next element in this iteration.
* @throws NoSuchElementException
* Thrown if there are no more elements in this iteration when calling this
* method.
*
* @see java.util.Iterator#next()
*/
public IValue next(){
return entryIterator.next().key;
}
/**
* Removal is not supported by this iterator.
*
* @throws java.lang.UnsupportedOperationException
*
* @see java.util.Iterator#remove()
*/
public void remove(){
throw new UnsupportedOperationException("This iterator doesn't support removal.");
}
}
/**
* Iterator for values.
*
* @author Arnold Lankamp
*
* @param <K>
* The key type.
* @param <V>
* The value type.
*/
private static class ValuesIterator<V> implements Iterator<V>{
private final EntryIterator<V> entryIterator;
/**
* Constructor.
*
* @param entries
* The entries to iterate over.
*/
public ValuesIterator(Entry<V>[] entries){
super();
entryIterator = new EntryIterator<>(entries);
}
/**
* Check if there are more elements in this iteration.
*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext(){
return entryIterator.hasNext();
}
/**
* Returns the next element in this iteration.
*
* @return The next element in this iteration.
* @throws NoSuchElementException
* Thrown if there are no more elements in this iteration when calling this
* method.
*
* @see java.util.Iterator#next()
*/
public V next(){
return entryIterator.next().value;
}
/**
* Removal is not supported by this iterator.
*
* @throws java.lang.UnsupportedOperationException
*
* @see java.util.Iterator#remove()
*/
public void remove(){
throw new UnsupportedOperationException("This iterator doesn't support removal.");
}
}
}
| cwi-swat/pdb.values | src/org/eclipse/imp/pdb/facts/util/ValueIndexedHashMap.java | Java | epl-1.0 | 18,738 |
package org.brainwy.liclipsetext.editor.partitioning;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.Token;
public class LiClipseTm4ePartitionScanner extends AbstractLiClipseRuleBasedScanner {
@Override
public void nextToken(ScannerRange range) {
boolean resume = (range.fPartitionOffset > -1 && range.fPartitionOffset < range.fOffset);
range.fTokenOffset = resume ? range.fPartitionOffset : range.fOffset;
if (range.read() == ICharacterScanner.EOF) {
range.setToken(Token.EOF);
return;
} else {
range.setMark(range.getRangeEndOffset());
range.setToken(fDefaultReturnToken);
}
}
}
| css-iter/org.csstudio.iter | plugins/org.brainwy.liclipsetext.editor/src/org/brainwy/liclipsetext/editor/partitioning/LiClipseTm4ePartitionScanner.java | Java | epl-1.0 | 729 |
/*******************************************************************************
* Copyright (c) 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jpa.fvt.relationships.manyXone.entities.bi.xml;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.ibm.ws.jpa.fvt.relationships.manyXone.entities.IEntityA;
import com.ibm.ws.jpa.fvt.relationships.manyXone.entities.IEntityBBi;
//@Entity
public class XMLMOBiEntB_CP implements IEntityBBi {
/**
* Entity primary key, an integer id number.
*/
// @Id
private int id;
/**
* Simple data payload for the entity.
*/
private String name;
// @ManyToMany(mappedBy="cascadePersist")
private Collection<XMLMOBiEntA> entityA;
public XMLMOBiEntB_CP() {
entityA = new ArrayList<XMLMOBiEntA>();
}
@Override
public int getId() {
return id;
}
@Override
public void setId(int id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
public Collection<XMLMOBiEntA> getEntityA() {
return entityA;
}
public void setEntityA(Collection<XMLMOBiEntA> entityA) {
this.entityA = entityA;
}
@Override
public Collection getEntityACollection() {
return getEntityA();
}
@Override
public void insertEntityAField(IEntityA iEntityA) {
XMLMOBiEntA entity = (XMLMOBiEntA) iEntityA;
Collection<XMLMOBiEntA> collection = getEntityA();
collection.add(entity);
}
@Override
public boolean isMemberOfEntityAField(IEntityA iEntityA) {
XMLMOBiEntA entity = (XMLMOBiEntA) iEntityA;
Collection<XMLMOBiEntA> collection = getEntityA();
return (collection.contains(entity));
}
@Override
public void removeEntityAField(IEntityA iEntityA) {
XMLMOBiEntA entity = (XMLMOBiEntA) iEntityA;
Collection<XMLMOBiEntA> collection = getEntityA();
collection.remove(entity);
}
@Override
public void setEntityACollectionField(Collection iEntityACollection) {
Collection<XMLMOBiEntA> collection = new ArrayList<XMLMOBiEntA>();
Iterator i = iEntityACollection.iterator();
while (i.hasNext()) {
XMLMOBiEntA entity = (XMLMOBiEntA) i.next();
collection.add(entity);
}
setEntityA(collection);
}
@Override
public String toString() {
return "XMLMOBiEntB_CP [id=" + id + ", name=" + name + "]";
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.jpa.tests.spec10.relationships.manyXone_fat.common/test-applications/jpa10/relationships/manyXone/src/com/ibm/ws/jpa/fvt/relationships/manyXone/entities/bi/xml/XMLMOBiEntB_CP.java | Java | epl-1.0 | 3,028 |
/**
* 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.cxf.frontend;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import javax.wsdl.Definition;
import javax.wsdl.Import;
import javax.wsdl.Port;
import javax.wsdl.Service;
import javax.wsdl.Types;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.wsdl.extensions.schema.Schema;
import javax.wsdl.extensions.schema.SchemaImport;
import javax.wsdl.extensions.schema.SchemaReference;
import javax.wsdl.extensions.soap.SOAPAddress;
import javax.wsdl.extensions.soap12.SOAP12Address;
import javax.wsdl.xml.WSDLWriter;
import javax.xml.namespace.QName;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.apache.cxf.Bus;
import org.apache.cxf.catalog.OASISCatalogManager;
import org.apache.cxf.catalog.OASISCatalogManagerHelper;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageUtils;
import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.service.model.SchemaInfo;
import org.apache.cxf.staxutils.StaxUtils;
import org.apache.cxf.wsdl.WSDLManager;
import org.apache.cxf.wsdl11.ResourceManagerWSDLLocator;
import org.apache.cxf.wsdl11.ServiceWSDLBuilder;
/**
*
*/
public class WSDLGetUtils {
public static final String AUTO_REWRITE_ADDRESS = "autoRewriteSoapAddress";
public static final String AUTO_REWRITE_ADDRESS_ALL = "autoRewriteSoapAddressForAllServices";
public static final String PUBLISHED_ENDPOINT_URL = "publishedEndpointUrl";
public static final String WSDL_CREATE_IMPORTS = "org.apache.cxf.wsdl.create.imports";
private static final String WSDLS_KEY = WSDLGetUtils.class.getName() + ".WSDLs";
private static final String SCHEMAS_KEY = WSDLGetUtils.class.getName() + ".Schemas";
private static final Logger LOG = LogUtils.getL7dLogger(WSDLGetInterceptor.class);
public WSDLGetUtils() {
//never constructed
}
public Set<String> getWSDLIds(Message message,
String base,
String ctxUri,
EndpointInfo endpointInfo) {
Map<String, String> params = new HashMap<String, String>();
params.put("wsdl", "");
new WSDLGetUtils().getDocument(message, base,
params, ctxUri,
endpointInfo);
Map<String, Definition> mp = CastUtils.cast((Map<?, ?>)endpointInfo.getService()
.getProperty(WSDLS_KEY));
return mp.keySet();
}
private String buildUrl(String base, String ctxUri, String s) {
return base + ctxUri + "?" + s;
}
public Map<String, String> getSchemaLocations(Message message,
String base,
String ctxUri,
EndpointInfo endpointInfo) {
Map<String, String> params = new HashMap<String, String>();
params.put("wsdl", "");
new WSDLGetUtils().getDocument(message, base,
params, ctxUri,
endpointInfo);
Map<String, SchemaReference> mp = CastUtils.cast((Map<?, ?>)endpointInfo.getService()
.getProperty(SCHEMAS_KEY));
Map<String, String> schemas = new HashMap<String, String>();
for (Map.Entry<String, SchemaReference> ent : mp.entrySet()) {
params.clear();
params.put("xsd", ent.getKey());
Document doc = getDocument(message, base, params, ctxUri, endpointInfo);
schemas.put(doc.getDocumentElement().getAttribute("targetNamespace"),
buildUrl(base, ctxUri, "xsd=" + ent.getKey()));
}
return schemas;
}
public Document getDocument(Message message,
String base,
Map<String, String> params,
String ctxUri,
EndpointInfo endpointInfo) {
try {
Bus bus = message.getExchange().getBus();
Object prop = message.getContextualProperty(PUBLISHED_ENDPOINT_URL);
if (prop == null) {
prop = endpointInfo.getProperty(PUBLISHED_ENDPOINT_URL);
}
if (prop != null) {
base = String.valueOf(prop);
}
String wsdl = params.get("wsdl");
if (wsdl != null) {
// Always use the URL decoded version to ensure that we have a
// canonical representation of the import URL for lookup.
wsdl = URLDecoder.decode(wsdl, "utf-8");
}
String xsd = params.get("xsd");
if (xsd != null) {
// Always use the URL decoded version to ensure that we have a
// canonical representation of the import URL for lookup.
xsd = URLDecoder.decode(xsd, "utf-8");
}
Map<String, Definition> mp = CastUtils.cast((Map<?, ?>)endpointInfo.getService()
.getProperty(WSDLS_KEY));
Map<String, SchemaReference> smp = CastUtils.cast((Map<?, ?>)endpointInfo.getService()
.getProperty(SCHEMAS_KEY));
if (mp == null) {
endpointInfo.getService().setProperty(WSDLS_KEY,
new ConcurrentHashMap<String, Definition>(8, 0.75f, 4));
mp = CastUtils.cast((Map<?, ?>)endpointInfo.getService()
.getProperty(WSDLS_KEY));
}
if (smp == null) {
endpointInfo.getService().setProperty(SCHEMAS_KEY,
new ConcurrentHashMap<String, SchemaReference>(8, 0.75f, 4));
smp = CastUtils.cast((Map<?, ?>)endpointInfo.getService()
.getProperty(SCHEMAS_KEY));
}
if (!mp.containsKey("")) {
ServiceWSDLBuilder builder =
new ServiceWSDLBuilder(bus, endpointInfo.getService());
builder.setUseSchemaImports(
MessageUtils.getContextualBoolean(message, WSDL_CREATE_IMPORTS, false));
// base file name is ignored if createSchemaImports == false!
builder.setBaseFileName(endpointInfo.getService().getName().getLocalPart());
Definition def = builder.build(new HashMap<String, SchemaInfo>());
mp.put("", def);
updateDefinition(bus, def, mp, smp, base, endpointInfo);
}
Document doc;
if (xsd == null) {
Definition def = mp.get(wsdl);
if (def == null) {
String wsdl2 = resolveWithCatalogs(OASISCatalogManager.getCatalogManager(bus),
wsdl,
base);
if (wsdl2 != null) {
def = mp.get(wsdl2);
}
}
if (def == null) {
throw new WSDLQueryException(new org.apache.cxf.common.i18n.Message("WSDL_NOT_FOUND",
LOG, wsdl), null);
}
synchronized (def) {
//writing a def is not threadsafe. Sync on it to make sure
//we don't get any ConcurrentModificationExceptions
if (endpointInfo.getProperty(PUBLISHED_ENDPOINT_URL) != null) {
String epurl =
String.valueOf(endpointInfo.getProperty(PUBLISHED_ENDPOINT_URL));
updatePublishedEndpointUrl(epurl, def, endpointInfo.getName());
base = epurl;
}
WSDLWriter wsdlWriter = bus.getExtension(WSDLManager.class)
.getWSDLFactory().newWSDLWriter();
def.setExtensionRegistry(bus.getExtension(WSDLManager.class).getExtensionRegistry());
doc = wsdlWriter.getDocument(def);
}
} else {
SchemaReference si = smp.get(xsd);
if (si == null) {
String xsd2 = resolveWithCatalogs(OASISCatalogManager.getCatalogManager(bus),
xsd,
base);
if (xsd2 != null) {
si = smp.get(xsd2);
}
}
if (si == null) {
throw new WSDLQueryException(new org.apache.cxf.common.i18n.Message("SCHEMA_NOT_FOUND",
LOG, wsdl), null);
}
String uri = si.getReferencedSchema().getDocumentBaseURI();
uri = resolveWithCatalogs(OASISCatalogManager.getCatalogManager(bus),
uri,
si.getReferencedSchema().getDocumentBaseURI());
if (uri == null) {
uri = si.getReferencedSchema().getDocumentBaseURI();
}
ResourceManagerWSDLLocator rml = new ResourceManagerWSDLLocator(uri,
bus);
InputSource src = rml.getBaseInputSource();
if (src.getByteStream() != null || src.getCharacterStream() != null) {
doc = StaxUtils.read(src);
} else { // last resort lets try for the referenced schema itself.
// its not thread safe if we use the same document
doc = StaxUtils.read(
new DOMSource(si.getReferencedSchema().getElement().getOwnerDocument()));
}
}
updateDoc(doc, base, mp, smp, message);
return doc;
} catch (WSDLQueryException wex) {
throw wex;
} catch (Exception wex) {
throw new WSDLQueryException(new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL",
LOG,
base), wex);
}
}
protected String mapUri(String base, Map<String, SchemaReference> smp, String loc)
throws UnsupportedEncodingException {
SchemaReference ref = smp.get(URLDecoder.decode(loc, "utf-8"));
if (ref != null) {
return base + "?xsd=" + ref.getSchemaLocationURI().replace(" ", "%20");
}
return null;
}
protected void updateDoc(Document doc,
String base,
Map<String, Definition> mp,
Map<String, SchemaReference> smp,
Message message) {
List<Element> elementList = null;
try {
elementList = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
"http://www.w3.org/2001/XMLSchema",
"import");
for (Element el : elementList) {
String sl = el.getAttribute("schemaLocation");
sl = mapUri(base, smp, sl);
if (sl != null) {
el.setAttribute("schemaLocation", sl);
}
}
elementList = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
"http://www.w3.org/2001/XMLSchema",
"include");
for (Element el : elementList) {
String sl = el.getAttribute("schemaLocation");
if (smp.containsKey(URLDecoder.decode(sl, "utf-8"))) {
el.setAttribute("schemaLocation", base + "?xsd=" + sl.replace(" ", "%20"));
}
}
elementList = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
"http://www.w3.org/2001/XMLSchema",
"redefine");
for (Element el : elementList) {
String sl = el.getAttribute("schemaLocation");
if (smp.containsKey(URLDecoder.decode(sl, "utf-8"))) {
el.setAttribute("schemaLocation", base + "?xsd=" + sl.replace(" ", "%20"));
}
}
elementList = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
"http://schemas.xmlsoap.org/wsdl/",
"import");
for (Element el : elementList) {
String sl = el.getAttribute("location");
if (mp.containsKey(URLDecoder.decode(sl, "utf-8"))) {
el.setAttribute("location", base + "?wsdl=" + sl.replace(" ", "%20"));
}
}
} catch (UnsupportedEncodingException e) {
throw new WSDLQueryException(new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL",
LOG,
base), e);
}
boolean rewriteAllSoapAddress = MessageUtils.isTrue(message.getContextualProperty(AUTO_REWRITE_ADDRESS_ALL));
if (rewriteAllSoapAddress) {
List<Element> portList = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
"http://schemas.xmlsoap.org/wsdl/",
"port");
String basePath = (String) message.get("http.base.path");
for (Element el : portList) {
rewriteAddressProtocolHostPort(base, el, basePath, "http://schemas.xmlsoap.org/wsdl/soap/");
rewriteAddressProtocolHostPort(base, el, basePath, "http://schemas.xmlsoap.org/wsdl/soap12/");
}
}
Object rewriteSoapAddress = message.getContextualProperty(AUTO_REWRITE_ADDRESS);
if (rewriteSoapAddress == null || MessageUtils.isTrue(rewriteSoapAddress) || rewriteAllSoapAddress) {
List<Element> serviceList = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
"http://schemas.xmlsoap.org/wsdl/",
"service");
for (Element serviceEl : serviceList) {
String serviceName = serviceEl.getAttribute("name");
if (serviceName.equals(message.getExchange().getService().getName().getLocalPart())) {
elementList = DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),
"http://schemas.xmlsoap.org/wsdl/",
"port");
for (Element el : elementList) {
String name = el.getAttribute("name");
if (name.equals(message.getExchange().getEndpoint().getEndpointInfo()
.getName().getLocalPart())) {
rewriteAddress(base, el, "http://schemas.xmlsoap.org/wsdl/soap/");
rewriteAddress(base, el, "http://schemas.xmlsoap.org/wsdl/soap12/");
}
}
}
}
}
try {
doc.setXmlStandalone(true);
} catch (Exception ex) {
//likely not DOM level 3
}
}
protected void rewriteAddress(String base, Element el, String soapNS) {
List<Element> sadEls = DOMUtils.findAllElementsByTagNameNS(el,
soapNS,
"address");
for (Element soapAddress : sadEls) {
soapAddress.setAttribute("location", base);
}
}
protected void rewriteAddressProtocolHostPort(String base, Element el, String httpBasePathProp, String soapNS) {
List<Element> sadEls = DOMUtils.findAllElementsByTagNameNS(el,
soapNS,
"address");
for (Element soapAddress : sadEls) {
String location = soapAddress.getAttribute("location").trim();
try {
URI locUri = new URI(location);
if (locUri.isAbsolute()) {
URL baseUrl = new URL(base);
StringBuilder sb = new StringBuilder(baseUrl.getProtocol());
sb.append("://").append(baseUrl.getHost()).append(":").append(baseUrl.getPort())
.append(locUri.getPath());
soapAddress.setAttribute("location", sb.toString());
} else if (httpBasePathProp != null) {
soapAddress.setAttribute("location", httpBasePathProp + location);
}
} catch (Exception e) {
//ignore
}
}
}
protected String resolveWithCatalogs(OASISCatalogManager catalogs, String start, String base) {
try {
return new OASISCatalogManagerHelper().resolve(catalogs, start, base);
} catch (Exception ex) {
//ignore
}
return null;
}
protected void updateDefinition(Bus bus,
Definition def, Map<String, Definition> done,
Map<String, SchemaReference> doneSchemas,
String base, EndpointInfo ei) {
OASISCatalogManager catalogs = OASISCatalogManager.getCatalogManager(bus);
Collection<List<?>> imports = CastUtils.cast((Collection<?>)def.getImports().values());
for (List<?> lst : imports) {
List<Import> impLst = CastUtils.cast(lst);
for (Import imp : impLst) {
String start = imp.getLocationURI();
String decodedStart = null;
// Always use the URL decoded version to ensure that we have a
// canonical representation of the import URL for lookup.
try {
decodedStart = URLDecoder.decode(start, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new WSDLQueryException(
new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL",
LOG,
start), e);
}
String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base);
if (resolvedSchemaLocation == null) {
try {
//check to see if it's already in a URL format. If so, leave it.
new URL(start);
} catch (MalformedURLException e) {
if (done.put(decodedStart, imp.getDefinition()) == null) {
updateDefinition(bus, imp.getDefinition(), done, doneSchemas, base, ei);
}
}
} else {
if (done.put(decodedStart, imp.getDefinition()) == null) {
done.put(resolvedSchemaLocation, imp.getDefinition());
updateDefinition(bus, imp.getDefinition(), done, doneSchemas, base, ei);
}
}
}
}
/* This doesn't actually work. Setting setSchemaLocationURI on the import
* for some reason doesn't actually result in the new URI being written
* */
Types types = def.getTypes();
if (types != null) {
for (ExtensibilityElement el
: CastUtils.cast(types.getExtensibilityElements(), ExtensibilityElement.class)) {
if (el instanceof Schema) {
Schema see = (Schema)el;
updateSchemaImports(bus, see, doneSchemas, base);
}
}
}
}
public void updateWSDLPublishedEndpointAddress(Definition def, EndpointInfo endpointInfo) {
synchronized (def) {
//writing a def is not threadsafe. Sync on it to make sure
//we don't get any ConcurrentModificationExceptions
if (endpointInfo.getProperty(PUBLISHED_ENDPOINT_URL) != null) {
String epurl = String.valueOf(endpointInfo.getProperty(PUBLISHED_ENDPOINT_URL));
updatePublishedEndpointUrl(epurl, def, endpointInfo.getName());
}
}
}
protected void updatePublishedEndpointUrl(String publishingUrl, Definition def, QName name) {
Collection<Service> services = CastUtils.cast(def.getAllServices().values());
for (Service service : services) {
Collection<Port> ports = CastUtils.cast(service.getPorts().values());
if (ports.isEmpty()) {
continue;
}
if (name == null) {
setSoapAddressLocationOn(ports.iterator().next(), publishingUrl);
break; // only update the first port since we don't target any specific port
} else {
for (Port port : ports) {
if (name.getLocalPart().equals(port.getName())) {
setSoapAddressLocationOn(port, publishingUrl);
}
}
}
}
}
protected void setSoapAddressLocationOn(Port port, String url) {
List<?> extensions = port.getExtensibilityElements();
for (Object extension : extensions) {
if (extension instanceof SOAP12Address) {
((SOAP12Address)extension).setLocationURI(url);
} else if (extension instanceof SOAPAddress) {
((SOAPAddress)extension).setLocationURI(url);
}
}
}
protected void updateSchemaImports(Bus bus,
Schema schema,
Map<String, SchemaReference> doneSchemas,
String base) {
OASISCatalogManager catalogs = OASISCatalogManager.getCatalogManager(bus);
Collection<List<?>> imports = CastUtils.cast((Collection<?>)schema.getImports().values());
for (List<?> lst : imports) {
List<SchemaImport> impLst = CastUtils.cast(lst);
for (SchemaImport imp : impLst) {
String start = findSchemaLocation(doneSchemas, imp);
if (start != null) {
String decodedStart = null;
// Always use the URL decoded version to ensure that we have a
// canonical representation of the import URL for lookup.
try {
decodedStart = URLDecoder.decode(start, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new WSDLQueryException(
new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL",
LOG,
start), e);
}
if (!doneSchemas.containsKey(decodedStart)) {
String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base);
if (resolvedSchemaLocation == null) {
try {
//check to see if it's already in a URL format. If so, leave it.
new URL(start);
} catch (MalformedURLException e) {
if (doneSchemas.put(decodedStart, imp) == null) {
updateSchemaImports(bus, imp.getReferencedSchema(), doneSchemas, base);
}
}
} else {
if (doneSchemas.put(decodedStart, imp) == null) {
doneSchemas.put(resolvedSchemaLocation, imp);
updateSchemaImports(bus, imp.getReferencedSchema(), doneSchemas, base);
}
}
}
}
}
}
List<SchemaReference> includes = CastUtils.cast(schema.getIncludes());
for (SchemaReference included : includes) {
String start = findSchemaLocation(doneSchemas, included);
if (start != null) {
String decodedStart = null;
// Always use the URL decoded version to ensure that we have a
// canonical representation of the import URL for lookup.
try {
decodedStart = URLDecoder.decode(start, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new WSDLQueryException(
new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL",
LOG,
start), e);
}
String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base);
if (resolvedSchemaLocation == null) {
if (!doneSchemas.containsKey(decodedStart)) {
try {
//check to see if it's aleady in a URL format. If so, leave it.
new URL(start);
} catch (MalformedURLException e) {
if (doneSchemas.put(decodedStart, included) == null) {
updateSchemaImports(bus, included.getReferencedSchema(), doneSchemas, base);
}
}
}
} else if (!doneSchemas.containsKey(decodedStart)
|| !doneSchemas.containsKey(resolvedSchemaLocation)) {
doneSchemas.put(decodedStart, included);
doneSchemas.put(resolvedSchemaLocation, included);
updateSchemaImports(bus, included.getReferencedSchema(), doneSchemas, base);
}
}
}
List<SchemaReference> redefines = CastUtils.cast(schema.getRedefines());
for (SchemaReference included : redefines) {
String start = findSchemaLocation(doneSchemas, included);
if (start != null) {
String decodedStart = null;
// Always use the URL decoded version to ensure that we have a
// canonical representation of the import URL for lookup.
try {
decodedStart = URLDecoder.decode(start, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new WSDLQueryException(
new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL",
LOG,
start), e);
}
String resolvedSchemaLocation = resolveWithCatalogs(catalogs, start, base);
if (resolvedSchemaLocation == null) {
if (!doneSchemas.containsKey(decodedStart)) {
try {
//check to see if it's aleady in a URL format. If so, leave it.
new URL(start);
} catch (MalformedURLException e) {
if (doneSchemas.put(decodedStart, included) == null) {
updateSchemaImports(bus, included.getReferencedSchema(), doneSchemas, base);
}
}
}
} else if (!doneSchemas.containsKey(decodedStart)
|| !doneSchemas.containsKey(resolvedSchemaLocation)) {
doneSchemas.put(decodedStart, included);
doneSchemas.put(resolvedSchemaLocation, included);
updateSchemaImports(bus, included.getReferencedSchema(), doneSchemas, base);
}
}
}
}
private String findSchemaLocation(Map<String, SchemaReference> doneSchemas, SchemaReference imp) {
if (imp.getReferencedSchema() != null) {
for (Map.Entry<String, SchemaReference> e : doneSchemas.entrySet()) {
if (e.getValue().getReferencedSchema().getElement()
== imp.getReferencedSchema().getElement()) {
doneSchemas.put(imp.getSchemaLocationURI(), imp);
imp.setSchemaLocationURI(e.getKey());
return e.getKey();
}
}
}
return imp.getSchemaLocationURI();
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.simple.2.6.2/src/org/apache/cxf/frontend/WSDLGetUtils.java | Java | epl-1.0 | 31,448 |
/*******************************************************************************
* Copyright (c) 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
//
// Generated By:JAX-WS RI IBM 2.1.1 in JDK 6 (JAXB RI IBM JAXB 2.1.3 in JDK 1.6)
//
package com.ibm.was.wssample.sei.async;
import java.util.concurrent.Future;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.AsyncHandler;
import javax.xml.ws.Response;
import com.ibm.was.wssample.sei.echo.EchoStringInput;
import com.ibm.was.wssample.sei.echo.EchoStringResponse;
@WebService(name = "EchoService12PortType", targetNamespace = "http://com/ibm/was/wssample/sei/echo/")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
ObjectFactory.class
})
public interface EchoService12PortType {
/**
*
* @param parameter
* @return
* returns javax.xml.ws.Response<com.ibm.was.wssample.async.EchoStringResponse>
*/
@WebMethod(operationName = "echoOperation", action = "echoOperation")
public Response<EchoStringResponse> echoOperationAsync(
@WebParam(name = "echoStringInput", targetNamespace = "http://com/ibm/was/wssample/sei/echo/",
partName = "parameter") EchoStringInput parameter);
/**
*
* @param parameter
* @param asyncHandler
* @return
* returns java.util.concurrent.Future<? extends java.lang.Object>
*/
@WebMethod(operationName = "echoOperation", action = "echoOperation")
public Future<?> echoOperationAsync(
@WebParam(name = "echoStringInput", targetNamespace = "http://com/ibm/was/wssample/sei/echo/",
partName = "parameter") EchoStringInput parameter,
@WebParam(name = "echoOperationResponse", targetNamespace = "", partName = "asyncHandler") AsyncHandler<EchoStringResponse> asyncHandler);
/**
*
* @param parameter
* @return
* returns com.ibm.was.wssample.async.EchoStringResponse
*/
@WebMethod(action = "echoOperation")
@WebResult(name = "echoStringResponse", targetNamespace = "http://com/ibm/was/wssample/sei/echo/", partName = "parameter")
public EchoStringResponse echoOperation(
@WebParam(name = "echoStringInput", targetNamespace = "http://com/ibm/was/wssample/sei/echo/",
partName = "parameter") EchoStringInput parameter);
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.wssecurity_fat.wsscxf/test-applications/WSSampleSeiClient/src/com/ibm/was/wssample/sei/async/EchoService12PortType.java | Java | epl-1.0 | 3,185 |
package org.jboss.windup.graph.typedgraph;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.Dependencies;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.furnace.repositories.AddonDependencyEntry;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.GraphContextFactory;
import org.jboss.windup.graph.model.WindupVertexFrame;
import org.jboss.windup.graph.service.GraphService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.tinkerpop.blueprints.Vertex;
@RunWith(Arquillian.class)
public class WindupPropertyMethodHandlerTest
{
@Deployment
@Dependencies({
@AddonDependency(name = "org.jboss.windup.graph:windup-graph"),
@AddonDependency(name = "org.jboss.forge.furnace.container:cdi")
})
public static ForgeArchive getDeployment()
{
ForgeArchive archive = ShrinkWrap.create(ForgeArchive.class)
.addBeansXML()
.addClasses(TestFooModel.class, TestFooSubModel.class)
.addAsAddonDependencies(
AddonDependencyEntry.create("org.jboss.windup.graph:windup-graph"),
AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi")
);
return archive;
}
@Inject
private GraphContextFactory factory;
@Test
public void testInMemoryFrame() throws Exception
{
try (GraphContext context = factory.create())
{
Assert.assertNotNull(context);
GraphService<TestFooModel> fooModelService = new GraphService<>(context, TestFooModel.class);
TestFooModel inMemoryModel = fooModelService.create();
inMemoryModel.setProp1("prop1").setProp2("prop2").setProp3("prop3");
Iterable<Vertex> vertices = context.getQuery().type(TestFooModel.class).vertices();
int numberFound = 0;
for (Vertex v : vertices)
{
numberFound++;
TestFooModel framed = (TestFooModel) context.getFramed().frame(v, WindupVertexFrame.class);
Assert.assertTrue(framed instanceof TestFooModel);
Assert.assertEquals("prop1", framed.getProp1());
Assert.assertEquals("prop2", framed.getProp2());
Assert.assertEquals("prop3", framed.getProp3());
}
Assert.assertEquals(1, numberFound);
}
}
}
| bradsdavis/windup | graph/tests/src/test/java/org/jboss/windup/graph/typedgraph/WindupPropertyMethodHandlerTest.java | Java | epl-1.0 | 2,731 |
package name.abuchen.portfolio.datatransfer.csv;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVStrategy;
import name.abuchen.portfolio.Messages;
import name.abuchen.portfolio.model.Account;
import name.abuchen.portfolio.model.AccountTransaction;
import name.abuchen.portfolio.model.Portfolio;
import name.abuchen.portfolio.model.PortfolioTransaction;
import name.abuchen.portfolio.model.Security;
import name.abuchen.portfolio.model.SecurityPrice;
import name.abuchen.portfolio.model.Transaction;
import name.abuchen.portfolio.model.Transaction.Unit;
import name.abuchen.portfolio.money.Money;
import name.abuchen.portfolio.money.Values;
/* not thread safe */
public class CSVExporter
{
/* package */static final CSVStrategy STRATEGY = new CSVStrategy(';', '"', CSVStrategy.COMMENTS_DISABLED,
CSVStrategy.ESCAPE_DISABLED, false, false, false, false);
public void exportAccountTransactions(File file, Account account) throws IOException
{
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))
{
CSVPrinter printer = new CSVPrinter(writer);
printer.setStrategy(STRATEGY);
printer.println(new String[] { Messages.CSVColumn_Date, //
Messages.CSVColumn_Type, //
Messages.CSVColumn_Value, //
Messages.CSVColumn_TransactionCurrency, //
Messages.CSVColumn_Shares, //
Messages.CSVColumn_ISIN, //
Messages.CSVColumn_WKN, //
Messages.CSVColumn_TickerSymbol, //
Messages.CSVColumn_SecurityName, //
Messages.CSVColumn_Note });
for (AccountTransaction t : account.getTransactions())
{
printer.print(t.getDate().toString());
printer.print(t.getType().toString());
printer.print(Values.Amount.format(t.getAmount()));
printer.print(t.getCurrencyCode());
printer.print(t.getShares() != 0 ? Values.Share.format(t.getShares()) : ""); //$NON-NLS-1$
printSecurityInfo(printer, t);
printer.print(escapeNull(t.getNote()));
printer.println();
}
}
}
public void exportAccountTransactions(File directory, List<Account> accounts) throws IOException
{
for (Account account : accounts)
exportAccountTransactions(new File(directory, account.getName() + ".csv"), account); //$NON-NLS-1$
}
public void exportPortfolioTransactions(File file, Portfolio portfolio) throws IOException
{
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))
{
CSVPrinter printer = new CSVPrinter(writer);
printer.setStrategy(STRATEGY);
printer.println(new String[] { Messages.CSVColumn_Date, //
Messages.CSVColumn_Type, //
Messages.CSVColumn_Value, //
Messages.CSVColumn_TransactionCurrency, //
Messages.CSVColumn_GrossAmount, //
Messages.CSVColumn_CurrencyGrossAmount, //
Messages.CSVColumn_ExchangeRate, //
Messages.CSVColumn_Fees, //
Messages.CSVColumn_Taxes, //
Messages.CSVColumn_Shares, //
Messages.CSVColumn_ISIN, //
Messages.CSVColumn_WKN, //
Messages.CSVColumn_TickerSymbol, //
Messages.CSVColumn_SecurityName, //
Messages.CSVColumn_Note });
for (PortfolioTransaction t : portfolio.getTransactions())
{
printer.print(t.getDate().toString());
printer.print(t.getType().toString());
printer.print(Values.Amount.format(t.getAmount()));
printer.print(t.getCurrencyCode());
// gross amount
Optional<Unit> grossAmount = t.getUnit(Unit.Type.GROSS_VALUE);
if (grossAmount.isPresent())
{
Money forex = grossAmount.get().getForex();
printer.print(Values.Amount.format(forex.getAmount()));
printer.print(forex.getCurrencyCode());
printer.print(Values.ExchangeRate.format(grossAmount.get().getExchangeRate()));
}
else
{
printer.print(""); //$NON-NLS-1$
printer.print(""); //$NON-NLS-1$
printer.print(""); //$NON-NLS-1$
}
printer.print(Values.Amount.format(t.getUnitSum(Unit.Type.FEE).getAmount()));
printer.print(Values.Amount.format(t.getUnitSum(Unit.Type.TAX).getAmount()));
printer.print(Values.Share.format(t.getShares()));
printSecurityInfo(printer, t);
printer.print(escapeNull(t.getNote()));
printer.println();
}
}
}
private void printSecurityInfo(CSVPrinter printer, Transaction t)
{
Security security = t.getSecurity();
if (security != null)
{
printer.print(escapeNull(security.getIsin()));
printer.print(escapeNull(security.getWkn()));
printer.print(escapeNull(security.getTickerSymbol()));
printer.print(escapeNull(security.getName()));
}
else
{
printer.print(""); //$NON-NLS-1$
printer.print(""); //$NON-NLS-1$
printer.print(""); //$NON-NLS-1$
printer.print(""); //$NON-NLS-1$
}
}
public void exportPortfolioTransactions(File directory, List<Portfolio> portfolios) throws IOException
{
for (Portfolio portfolio : portfolios)
exportPortfolioTransactions(new File(directory, portfolio.getName() + ".csv"), portfolio); //$NON-NLS-1$
}
public void exportSecurityMasterData(File file, List<Security> securities) throws IOException
{
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))
{
CSVPrinter printer = new CSVPrinter(writer);
printer.setStrategy(STRATEGY);
printer.println(new String[] { Messages.CSVColumn_ISIN, //
Messages.CSVColumn_WKN, //
Messages.CSVColumn_TickerSymbol, //
Messages.CSVColumn_SecurityName, //
Messages.CSVColumn_Currency, Messages.CSVColumn_Note });
for (Security s : securities)
{
printer.print(escapeNull(s.getIsin()));
printer.print(escapeNull(s.getWkn()));
printer.print(escapeNull(s.getTickerSymbol()));
printer.print(escapeNull(s.getName()));
printer.print(escapeNull(s.getCurrencyCode()));
printer.print(escapeNull(s.getNote()));
printer.println();
}
}
}
public void exportSecurityPrices(File file, Security security) throws IOException
{
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))
{
CSVPrinter printer = new CSVPrinter(writer);
printer.setStrategy(STRATEGY);
printer.println(new String[] { Messages.CSVColumn_Date, Messages.CSVColumn_Quote });
for (SecurityPrice p : security.getPrices())
{
printer.print(p.getTime().toString());
printer.print(Values.Quote.format(p.getValue()));
printer.println();
}
}
}
public void exportSecurityPrices(File directory, List<Security> securities) throws IOException
{
for (Security security : securities)
exportSecurityPrices(new File(directory, security.getIsin() + ".csv"), security); //$NON-NLS-1$
}
public void exportMergedSecurityPrices(File file, List<Security> securities) throws IOException
{
// prepare: (a) find earliest date (b) ignore securities w/o quotes
LocalDate earliestDate = null;
List<Security> export = new ArrayList<Security>(securities.size());
for (Security s : securities)
{
List<SecurityPrice> prices = s.getPrices();
if (!prices.isEmpty())
{
export.add(s);
LocalDate quoteDate = prices.get(0).getTime();
if (earliestDate == null)
earliestDate = quoteDate;
else
earliestDate = earliestDate.isAfter(quoteDate) ? quoteDate : earliestDate;
}
}
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))
{
CSVPrinter printer = new CSVPrinter(writer);
printer.setStrategy(STRATEGY);
// write header
printer.print(Messages.CSVColumn_Date);
for (Security security : export)
printer.print(security.getExternalIdentifier());
printer.println();
// stop if no securities exist
if (earliestDate == null)
return;
// write quotes
LocalDate pointer = earliestDate;
LocalDate today = LocalDate.now();
while (pointer.compareTo(today) <= 0)
{
// check if any quotes exist for that day at all
int[] indices = new int[export.size()];
int ii = 0;
for (Security security : export)
{
SecurityPrice p = new SecurityPrice(pointer, 0);
indices[ii] = Collections.binarySearch(security.getPrices(), p);
ii++;
}
boolean hasValues = false;
for (ii = 0; ii < indices.length && !hasValues; ii++)
hasValues = indices[ii] >= 0;
if (hasValues)
{
printer.print(pointer.toString());
for (ii = 0; ii < indices.length; ii++)
{
if (indices[ii] < 0)
printer.print(""); //$NON-NLS-1$
else
printer.print(Values.Quote.format(export.get(ii).getPrices().get(indices[ii]).getValue()));
}
printer.println();
}
pointer = pointer.plusDays(1);
}
}
}
/* package */static String escapeNull(String value)
{
return value != null ? value : ""; //$NON-NLS-1$
}
}
| Beluk/portfolio | name.abuchen.portfolio/src/name/abuchen/portfolio/datatransfer/csv/CSVExporter.java | Java | epl-1.0 | 11,485 |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.dx.rop.code;
import com.android.dx.rop.cst.CstInteger;
import com.android.dx.rop.type.Type;
/**
* Implementation of {@link TranslationAdvice} which represents what
* the dex format will be able to represent.
*/
public final class DexTranslationAdvice
implements TranslationAdvice {
/** {@code non-null;} standard instance of this class */
public static final DexTranslationAdvice THE_ONE =
new DexTranslationAdvice();
/** debug advice for disabling invoke-range optimization */
public static final DexTranslationAdvice NO_SOURCES_IN_ORDER =
new DexTranslationAdvice(true);
/**
* The minimum source width, in register units, for an invoke
* instruction that requires its sources to be in order and contiguous.
*/
private static final int MIN_INVOKE_IN_ORDER = 6;
/** when true: always returns false for requiresSourcesInOrder */
private final boolean disableSourcesInOrder;
/**
* This class is not publicly instantiable. Use {@link #THE_ONE}.
*/
private DexTranslationAdvice() {
disableSourcesInOrder = false;
}
private DexTranslationAdvice(boolean disableInvokeRange) {
this.disableSourcesInOrder = disableInvokeRange;
}
/** {@inheritDoc} */
public boolean hasConstantOperation(Rop opcode,
RegisterSpec sourceA, RegisterSpec sourceB) {
if (sourceA.getType() != Type.INT) {
return false;
}
if (! (sourceB.getTypeBearer() instanceof CstInteger)) {
return false;
}
CstInteger cst = (CstInteger) sourceB.getTypeBearer();
// TODO handle rsub
switch (opcode.getOpcode()) {
// These have 8 and 16 bit cst representations
case RegOps.REM:
case RegOps.ADD:
case RegOps.MUL:
case RegOps.DIV:
case RegOps.AND:
case RegOps.OR:
case RegOps.XOR:
return cst.fitsIn16Bits();
// These only have 8 bit cst reps
case RegOps.SHL:
case RegOps.SHR:
case RegOps.USHR:
return cst.fitsIn8Bits();
default:
return false;
}
}
/** {@inheritDoc} */
public boolean requiresSourcesInOrder(Rop opcode,
RegisterSpecList sources) {
return !disableSourcesInOrder && opcode.isCallLike()
&& totalRopWidth(sources) >= MIN_INVOKE_IN_ORDER;
}
/**
* Calculates the total rop width of the list of SSA registers
*
* @param sources {@code non-null;} list of SSA registers
* @return {@code >= 0;} rop-form width in register units
*/
private int totalRopWidth(RegisterSpecList sources) {
int sz = sources.size();
int total = 0;
for (int i = 0; i < sz; i++) {
total += sources.get(i).getCategory();
}
return total;
}
/** {@inheritDoc} */
public int getMaxOptimalRegisterCount() {
return 16;
}
}
| MoSync/MoSync | tools/android/dx/src/com/android/dx/rop/code/DexTranslationAdvice.java | Java | gpl-2.0 | 3,698 |
/*
* Copyright (c) 2014 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.
*
* 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 org.openjdk.bench.java.lang;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import java.util.concurrent.TimeUnit;
/**
* Test to launch and gather threads. Measure time for different parts.
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
public class ThreadStartJoin {
private static final int THREADS = Runtime.getRuntime().availableProcessors();
private Thread[] ts;
@Benchmark
public void test() throws InterruptedException {
ts = new TestThread[THREADS];
for (int i = 0; i < THREADS; i++) {
ts[i] = new TestThread();
}
for (int i = 0; i < THREADS; i++) {
ts[i].start();
}
for (Thread mythread : ts) {
mythread.join();
if (mythread.isAlive()) {
throw new IllegalStateException("Couldn't join in time in LPHhello.");
}
}
}
@TearDown
public final void cleanup() {
if (ts != null) {
for (Thread t : ts) {
if (t != null) {
t.interrupt();
}
}
ts = null;
}
}
static final class TestThread extends Thread {
private static int num = 0;
public TestThread() {
super(TestThread.name());
}
private synchronized static String name() {
return "TestThread-" + num++;
}
public void run() {
// do nothing
}
}
}
| md-5/jdk10 | test/micro/org/openjdk/bench/java/lang/ThreadStartJoin.java | Java | gpl-2.0 | 2,862 |
// --------------------------------------------------------------------------------------------------
// Copyright (c) 2016 Microsoft Corporation
//
// 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.microsoft.Malmo;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.client.IModGuiFactory;
import net.minecraftforge.fml.client.config.GuiButtonExt;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.IConfigElement;
import com.microsoft.Malmo.Utils.AddressHelper;
public class MalmoModGuiOptions implements IModGuiFactory
{
public static class MalmoModGuiScreen extends GuiConfig
{
public MalmoModGuiScreen(GuiScreen parentScreen)
{
super(parentScreen, getConfigElements(), MalmoMod.MODID, MalmoMod.SOCKET_CONFIGS, false, false, "Malmo Platform Settings", MalmoMod.instance.getModPermanentConfigFile().getConfigFile().getParent());
}
static private List<IConfigElement> getConfigElements()
{
ConfigCategory cat = MalmoMod.instance.getModSessionConfigFile().getCategory(MalmoMod.SOCKET_CONFIGS);
List<IConfigElement> list = new ArrayList<IConfigElement>();
for (Property prop : cat.getOrderedValues())
{
list.add(new ConfigElement(prop));
}
ConfigCategory catDiags = MalmoMod.instance.getModPermanentConfigFile().getCategory(MalmoMod.DIAGNOSTIC_CONFIGS);
for (Property prop : catDiags.getOrderedValues())
{
list.add(new ConfigElement(prop));
}
return list;
}
@SuppressWarnings("unchecked") // Needed for the buttonList.add call - Minecraft code declares buttonList as unparameterised.
@Override
public void initGui()
{
// You can add buttons and initialize fields here
super.initGui();
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
super.drawScreen(mouseX, mouseY, partialTicks);
if (AddressHelper.getMissionControlPort() != -1)
this.drawCenteredString(this.fontRendererObj, "Mission Control Port: " + AddressHelper.getMissionControlPort(), this.width / 2, this.height / 2, 0x44ff44);
else
{
this.drawCenteredString(this.fontRendererObj, "NO MISSION CONTROL SOCKET - is there a port collision?", this.width / 2, this.height / 2, 0xff0000);
this.drawCenteredString(this.fontRendererObj, "Set the portOverride to 0 to let the system allocate a free port dynamically.", this.width / 2, this.height / 2 + this.fontRendererObj.FONT_HEIGHT, 0xffffff);
}
}
@Override
protected void actionPerformed(GuiButton button)
{
// You can process any additional buttons you may have added here
super.actionPerformed(button);
}
public GuiButtonExt getDoneButton()
{
for (Object butobj : this.buttonList)
{
if (butobj instanceof GuiButtonExt)
{
GuiButtonExt button = (GuiButtonExt)butobj;
if (button.id == 2000)
return button;
}
}
return null;
}
@Override
public void onGuiClosed()
{
super.onGuiClosed();
// Save any changes to our configuration:
MalmoMod.instance.getModPermanentConfigFile().save();
MalmoMod.instance.getModSessionConfigFile().save();
}
}
@Override
public void initialize(Minecraft minecraftInstance)
{
}
@Override
public Class<? extends GuiScreen> mainConfigGuiClass()
{
return MalmoModGuiScreen.class;
}
@Override
public Set<RuntimeOptionCategoryElement> runtimeGuiCategories()
{
return null;
}
@Override
public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element)
{
return null;
}
}
| Yarichi/Proyecto-DASI | Malmo/Minecraft/src/main/java/com/microsoft/Malmo/MalmoModGuiOptions.java | Java | gpl-2.0 | 5,762 |
/*
* Copyright (C) 2013-2016 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.n52.series.db.dao;
import static org.hibernate.criterion.Restrictions.eq;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.n52.series.db.DataAccessException;
import org.n52.series.db.beans.I18nProcedureEntity;
import org.n52.series.db.beans.ProcedureEntity;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class ProcedureDao extends AbstractDao<ProcedureEntity> {
private static final String SERIES_PROPERTY = "procedure";
private static final String COLUMN_REFERENCE = "reference";
public ProcedureDao(Session session) {
super(session);
}
@Override
@SuppressWarnings("unchecked")
public List<ProcedureEntity> find(DbQuery query) {
Criteria criteria = translate(I18nProcedureEntity.class, getDefaultCriteria(), query)
.add(Restrictions.ilike("name", "%" + query.getSearchTerm() + "%"));
return addFilters(criteria, query).list();
}
@Override
@SuppressWarnings("unchecked")
public List<ProcedureEntity> getAllInstances(DbQuery query) throws DataAccessException {
Criteria criteria = translate(I18nProcedureEntity.class, getDefaultCriteria(), query);
return (List<ProcedureEntity>) addFilters(criteria, query).list();
}
@Override
protected Criteria getDefaultCriteria() {
return super.getDefaultCriteria()
.add(eq(COLUMN_REFERENCE, Boolean.FALSE));
}
@Override
protected String getSeriesProperty() {
return SERIES_PROPERTY;
}
@Override
protected Class<ProcedureEntity> getEntityClass() {
return ProcedureEntity.class;
}
}
| ridoo/sensorweb-rest-api | spi-impl/series/series-dao/src/main/java/org/n52/series/db/dao/ProcedureDao.java | Java | gpl-2.0 | 3,059 |
/*
* ValidationElement.java
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the BSD license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* LICENSE.txt file for more details.
*
* Copyright (c) 2003-2015 Per Cederberg. All rights reserved.
*/
package net.percederberg.grammatica.ant;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import net.percederberg.grammatica.Grammar;
import net.percederberg.grammatica.GrammarException;
import net.percederberg.grammatica.TreePrinter;
import net.percederberg.grammatica.parser.Analyzer;
import net.percederberg.grammatica.parser.Node;
import net.percederberg.grammatica.parser.ParseException;
import net.percederberg.grammatica.parser.Parser;
import net.percederberg.grammatica.parser.ParserCreationException;
import net.percederberg.grammatica.parser.ParserLogException;
import net.percederberg.grammatica.parser.Token;
import net.percederberg.grammatica.parser.Tokenizer;
/**
* A grammar validation element. This element validates or tests the
* grammar in various ways.
*
* @author Per Cederberg
* @version 1.4
* @since 1.4
*/
public class ValidationElement implements ProcessingElement {
/**
* The validation type.
*/
private String type = null;
/**
* The input test file.
*/
private File file = null;
/**
* The quiet output flag.
*/
private boolean quiet = false;
/**
* Creates a new validation element.
*/
public ValidationElement() {
// Nothing to do here
}
/**
* Sets the validation type. The type must be one of "debug",
* "tokenize", "parse", or "profile".
*
* @param type the validation type
*/
public void setType(String type) {
this.type = type;
}
/**
* Sets the input test file. The test file is not needed for the
* debug validation type.
*
* @param file the input test file
*/
public void setInputfile(File file) {
this.file = file;
}
/**
* Sets the quiet output flag.
*
* @param quiet the quiet output flag
*/
public void setQuiet(boolean quiet) {
this.quiet = quiet;
}
/**
* Validates all attributes in the element.
*
* @throws RuntimeException if some attribute was missing or had an
* invalid value
*/
public void validate() throws RuntimeException {
if (type == null) {
throw new RuntimeException(
"missing 'type' attribute in <validate>");
}
if (!type.equals("debug")
&& !type.equals("tokenize")
&& !type.equals("parse")
&& !type.equals("profile")) {
throw new RuntimeException(
"value of 'type' attribute in <validate> must be one " +
"of 'debug', 'tokenize', 'parse', or 'profile'");
}
if (file == null && !type.equals("debug")) {
throw new RuntimeException(
"missing 'inputfile' attribute in <validate>");
}
}
/**
* Proceses the specified grammar.
*
* @param grammar the grammar to process
*
* @throws RuntimeException if the grammar couldn't be processed
* correctly
*/
public void process(Grammar grammar) throws RuntimeException {
if (type.equals("debug")) {
debug(grammar);
} else if (type.equals("tokenize")) {
tokenize(grammar);
} else if (type.equals("parse")) {
parse(grammar);
} else if (type.equals("profile")) {
profile(grammar);
} else {
throw new RuntimeException("unknown <validation> type: " + type);
}
}
/**
* Debugs a grammar by printing the internal representation.
*
* @param grammar the grammar to use
*
* @throws RuntimeException if a parser couldn't be created
*/
private void debug(Grammar grammar) throws RuntimeException {
Tokenizer tokenizer = null;
Parser parser = null;
// Create tokenizer and parser
try {
tokenizer = grammar.createTokenizer(null);
parser = grammar.createParser(tokenizer);
} catch (GrammarException e) {
throw new RuntimeException("in grammar " + grammar.getFileName() +
": " + e.getMessage());
}
// Print tokenizer and parser
if (!quiet) {
System.out.println("Contents of " + grammar.getFileName() + ":");
System.out.println();
System.out.println("Token Declarations:");
System.out.println("-------------------");
System.out.print(tokenizer);
System.out.println("Production Declarations:");
System.out.println("------------------------");
System.out.print(parser);
}
}
/**
* Tokenizes the input file with the token patterns from the
* grammar.
*
* @param grammar the grammar to use
*
* @throws RuntimeException if the input file couldn't be tokenized
* correctly
*/
private void tokenize(Grammar grammar) throws RuntimeException {
Tokenizer tokenizer;
Token token;
try {
tokenizer = grammar.createTokenizer(new FileReader(file));
if (!quiet) {
System.out.println("Tokens from " + file + ":");
}
while ((token = tokenizer.next()) != null) {
if (!quiet) {
System.out.println(token);
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage());
} catch (GrammarException e) {
throw new RuntimeException("in grammar " + grammar.getFileName() +
": " + e.getMessage());
} catch (ParseException e) {
throw new RuntimeException("in file " + file + ": " +
e.getMessage());
}
}
/**
* Parses the input file with the grammar.
*
* @param grammar the grammar to use
*
* @throws RuntimeException if the input file couldn't be parsed
* correctly
*/
private void parse(Grammar grammar) throws RuntimeException {
Tokenizer tokenizer;
Analyzer analyzer;
Parser parser;
try {
tokenizer = grammar.createTokenizer(new FileReader(file));
if (quiet) {
analyzer = null;
} else {
analyzer = new TreePrinter(System.out);
}
parser = grammar.createParser(tokenizer, analyzer);
if (!quiet) {
System.out.println("Parse tree from " + file + ":");
}
parser.parse();
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage());
} catch (GrammarException e) {
throw new RuntimeException("in grammar " + grammar.getFileName() +
": " + e.getMessage());
} catch (ParserCreationException e) {
throw new RuntimeException("in grammar " + grammar.getFileName() +
": " + e.getMessage());
} catch (ParserLogException e) {
throw new RuntimeException("in file " + file + ": " +
e.getMessage());
}
}
/**
* Parses the input file with the grammar and prints profiling
* information.
*
* @param grammar the grammar to use
*
* @throws RuntimeException if the input file couldn't be profiled
* correctly
*/
private void profile(Grammar grammar) throws RuntimeException {
Tokenizer tokenizer;
Parser parser;
Node node;
long time;
int counter;
// Profile tokenizer
try {
tokenizer = grammar.createTokenizer(new FileReader(file));
System.out.println("Tokenizing " + file);
time = System.currentTimeMillis();
counter = 0;
while (tokenizer.next() != null) {
counter++;
}
time = System.currentTimeMillis() - time;
System.out.println(" Time elapsed: " + time + " millisec");
System.out.println(" Tokens found: " + counter);
System.out.println(" Average speed: " + (counter / time) +
" tokens/millisec");
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage());
} catch (GrammarException e) {
throw new RuntimeException("in grammar " + grammar.getFileName() +
": " + e.getMessage());
} catch (ParseException e) {
throw new RuntimeException("in file " + file + ": " +
e.getMessage());
}
// Profile parser
try {
tokenizer = grammar.createTokenizer(new FileReader(file));
parser = grammar.createParser(tokenizer);
System.out.println("Parsing " + file);
time = System.currentTimeMillis();
node = parser.parse();
time = System.currentTimeMillis() - time;
counter = 1 + node.getDescendantCount();
System.out.println(" Time elapsed: " + time + " millisec");
System.out.println(" Nodes found: " + counter);
System.out.println(" Average speed: " + (counter / time) +
" nodes/millisec");
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage());
} catch (GrammarException e) {
throw new RuntimeException("in grammar " + grammar.getFileName() +
": " + e.getMessage());
} catch (ParserCreationException e) {
throw new RuntimeException("in grammar " + grammar.getFileName() +
": " + e.getMessage());
} catch (ParserLogException e) {
throw new RuntimeException("in file " + file + ": " +
e.getMessage());
}
}
}
| runner-mei/mibble | src/main/java/net/percederberg/grammatica/ant/ValidationElement.java | Java | gpl-2.0 | 10,739 |
package freenet.support;
import com.db4o.ObjectContainer;
import freenet.client.async.ClientContext;
/**
* Like RandomGrabArray, but there is an equal chance of any given client's requests being
* returned.
*/
public class SectoredRandomGrabArray implements RemoveRandom, RemoveRandomParent {
private static volatile boolean logMINOR;
static {
Logger.registerLogThresholdCallback(new LogThresholdCallback() {
@Override
public void shouldUpdate() {
logMINOR = Logger.shouldLog(Logger.MINOR, this);
}
});
}
/*
* Yes, this is O(n). No, I don't care.
*
* Using a Db4oMap results in stuff getting reactivated during the commit
* phase, and not deactivated. This makes keeping stuff that shouldn't be
* activated deactivated impossible, resulting in more memory usage. more
* Full GC's, more object churn, and hence more CPU usage. Also Db4oMap is
* deprecated.
*
* Using a HashMap populated in objectOnActivate() doesn't work either,
* because it ends up comparing deactivated clients with activated ones.
* This will result in NPEs, and unnecessary code complexity to fix them.
*
* IMHO it's not worth bothering with a hashtable if it's less than 1000
* or so items anyway. If size does become a problem we will need to
* implement our own activation aware hashtable class, which stores the
* full hashCode, and matches on == object identity, so that we don't need
* to activate on comparison.
*/
private RemoveRandomWithObject[] grabArrays;
private Object[] grabClients;
private final boolean persistent;
private final RemoveRandomParent parent;
public SectoredRandomGrabArray(boolean persistent, ObjectContainer container, RemoveRandomParent parent) {
this.persistent = persistent;
grabClients = new Object[0];
grabArrays = new RemoveRandomWithObject[0];
this.parent = parent;
}
/**
* Add directly to a RandomGrabArrayWithClient under us. */
public synchronized void add(Object client, RandomGrabArrayItem item, ObjectContainer container) {
if(item.persistent() != persistent) throw new IllegalArgumentException("item.persistent()="+item.persistent()+" but array.persistent="+persistent+" item="+item+" array="+this);
RandomGrabArrayWithClient rga;
int clientIndex = haveClient(client);
if(clientIndex == -1) {
if(logMINOR)
Logger.minor(this, "Adding new RGAWithClient for "+client+" on "+this+" for "+item);
rga = new RandomGrabArrayWithClient(client, persistent, container, this);
addElement(client, rga);
if(persistent) {
container.store(rga);
container.store(this);
}
} else {
rga = (RandomGrabArrayWithClient) grabArrays[clientIndex];
if(persistent)
container.activate(rga, 1);
}
if(logMINOR)
Logger.minor(this, "Adding "+item+" to RGA "+rga+" for "+client);
rga.add(item, container);
if(persistent)
container.deactivate(rga, 1);
if(logMINOR)
Logger.minor(this, "Size now "+grabArrays.length+" on "+this);
}
private void addElement(Object client, RemoveRandomWithObject rga) {
int len = grabArrays.length;
RemoveRandomWithObject[] newArrays = new RemoveRandomWithObject[len+1];
System.arraycopy(grabArrays, 0, newArrays, 0, len);
newArrays[len] = rga;
grabArrays = newArrays;
Object[] newClients = new Object[len+1];
System.arraycopy(grabClients, 0, newClients, 0, len);
newClients[len] = client;
grabClients = newClients;
}
private synchronized int haveClient(Object client) {
for(int i=0;i<grabClients.length;i++) {
if(grabClients[i] == client) return i;
}
return -1;
}
/**
* Get a grabber. This lets us use things other than RandomGrabArrayWithClient's, so don't mix calls
* to add() with calls to getGrabber/addGrabber!
*/
public synchronized RemoveRandomWithObject getGrabber(Object client) {
int idx = haveClient(client);
if(idx == -1) return null;
else return grabArrays[idx];
}
public synchronized Object getClient(int x) {
return grabClients[x];
}
/**
* Put a grabber. This lets us use things other than RandomGrabArrayWithClient's, so don't mix calls
* to add() with calls to getGrabber/addGrabber!
*/
public synchronized void addGrabber(Object client, RemoveRandomWithObject requestGrabber, ObjectContainer container) {
if(requestGrabber.getObject() != client)
throw new IllegalArgumentException("Client not equal to RemoveRandomWithObject's client: client="+client+" rr="+requestGrabber+" his object="+requestGrabber.getObject());
addElement(client, requestGrabber);
if(persistent) {
container.store(this);
}
}
public synchronized RandomGrabArrayItem removeRandom(RandomGrabArrayItemExclusionList excluding, ObjectContainer container, ClientContext context) {
/** Count of arrays that have items but didn't return anything because of exclusions */
int excluded = 0;
final int MAX_EXCLUDED = 10;
while(true) {
if(grabArrays.length == 0) return null;
if(grabArrays.length == 1) {
// Optimise the common case
RemoveRandomWithObject rga = grabArrays[0];
if(persistent)
container.activate(rga, 1);
RandomGrabArrayItem item = rga.removeRandom(excluding, container, context);
if(rga.isEmpty()) {
if(logMINOR)
Logger.minor(this, "Removing only grab array (0) : "+rga);
grabArrays = new RemoveRandomWithObject[0];
grabClients = new Object[0];
if(persistent) {
container.store(this);
rga.removeFrom(container);
}
}
if(logMINOR)
Logger.minor(this, "Returning (one item only) "+item+" for "+rga);
return item;
}
if(grabArrays.length == 2) {
// Another simple common case
int x = context.fastWeakRandom.nextBoolean() ? 1 : 0;
RemoveRandomWithObject rga = grabArrays[x];
if(persistent)
container.activate(rga, 1);
RemoveRandomWithObject firstRGA = rga;
if(rga == null) {
Logger.error(this, "rga = null on "+this);
if(container != null && !container.ext().isActive(this))
Logger.error(this, "NOT ACTIVE!!");
if(grabArrays[1-x] == null) {
Logger.error(this, "other rga is also null on "+this);
} else {
RemoveRandomWithObject valid = grabArrays[1-x];
Logger.error(this, "grabArrays["+(1-x)+"] is valid but ["+x+"] is null, correcting...");
grabArrays = new RemoveRandomWithObject[] { grabArrays[1-x] };
grabClients = new Object[] { grabClients[1-x] };
if(persistent) {
container.store(this);
}
continue;
}
}
RandomGrabArrayItem item = rga.removeRandom(excluding, container, context);
if(item == null) {
x = 1-x;
rga = grabArrays[x];
if(persistent)
container.activate(rga, 1);
item = rga.removeRandom(excluding, container, context);
if(firstRGA.isEmpty() && rga.isEmpty()) {
grabArrays = new RemoveRandomWithObject[0];
grabClients = new Object[0];
if(persistent) {
container.store(this);
firstRGA.removeFrom(container);
rga.removeFrom(container);
}
} else if(firstRGA.isEmpty()) {
if(persistent) {
container.activate(firstRGA, 1);
}
grabArrays = new RemoveRandomWithObject[] { rga };
grabClients = new Object[] { grabClients[x] };
if(persistent) {
container.store(this);
firstRGA.removeFrom(container);
}
}
if(persistent) {
container.deactivate(rga, 1);
container.deactivate(firstRGA, 1);
}
if(logMINOR)
Logger.minor(this, "Returning (two items only) "+item+" for "+rga);
return item;
} else {
if(persistent)
container.deactivate(rga, 1);
if(logMINOR)
Logger.minor(this, "Returning (two items only) "+item+" for "+rga);
return item;
}
}
int x = context.fastWeakRandom.nextInt(grabArrays.length);
RemoveRandomWithObject rga = grabArrays[x];
if(persistent)
container.activate(rga, 1);
if(logMINOR)
Logger.minor(this, "Picked "+x+" of "+grabArrays.length+" : "+rga+" on "+this);
RandomGrabArrayItem item = rga.removeRandom(excluding, container, context);
if(logMINOR)
Logger.minor(this, "RGA has picked "+x+"/"+grabArrays.length+": "+item+
(item==null ? "" : (" cancelled="+item.isEmpty(container)+")"))+" rga.isEmpty="+rga.isEmpty());
// Just because the item is cancelled does not necessarily mean the whole client is.
// E.g. a segment may return cancelled because it is decoding, that doesn't mean
// other segments are cancelled. So just go around the loop in that case.
if(rga.isEmpty()) {
if(logMINOR)
Logger.minor(this, "Removing grab array "+x+" : "+rga+" (is empty)");
removeElement(x);
if(persistent) {
container.store(this);
rga.removeFrom(container);
}
}
if(item == null) {
if(!rga.isEmpty()) {
// Hmmm...
excluded++;
if(excluded > MAX_EXCLUDED) {
Logger.normal(this, "Too many sub-arrays are entirely excluded on "+this+" length = "+grabArrays.length, new Exception("error"));
if(persistent)
container.deactivate(rga, 1);
return null;
}
}
if(persistent)
container.deactivate(rga, 1);
continue;
}
if(persistent)
container.deactivate(rga, 1);
if(item.isEmpty(container)) continue;
return item;
}
}
private synchronized void removeElement(int x) {
final int grabArraysLength = grabArrays.length;
int newLen = grabArraysLength > 1 ? grabArraysLength-1 : 0;
RemoveRandomWithObject[] newArray = new RemoveRandomWithObject[newLen];
if(x > 0)
System.arraycopy(grabArrays, 0, newArray, 0, x);
if(x < grabArraysLength-1)
System.arraycopy(grabArrays, x+1, newArray, x, grabArraysLength - (x+1));
grabArrays = newArray;
Object[] newClients = new Object[newLen];
if(x > 0)
System.arraycopy(grabClients, 0, newClients, 0, x);
if(x < grabArraysLength-1)
System.arraycopy(grabClients, x+1, newClients, x, grabArraysLength - (x+1));
grabClients = newClients;
}
public synchronized boolean isEmpty() {
return grabArrays.length == 0;
}
public boolean persistent() {
return persistent;
}
public int size() {
return grabArrays.length;
}
public void removeFrom(ObjectContainer container) {
if(grabArrays != null && grabArrays.length != 0) {
for(RemoveRandomWithObject rr : grabArrays) {
if(rr != null) {
Logger.error(this, "NOT EMPTY REMOVING "+this+" : "+rr);
return;
}
}
}
container.delete(this);
}
public void maybeRemove(RemoveRandom r, ObjectContainer container) {
int count = 0;
synchronized(this) {
while(true) {
int found = -1;
for(int i=0;i<grabArrays.length;i++) {
if(grabArrays[i] == r) {
found = i;
break;
}
}
if(found != -1) {
count++;
if(count > 1) Logger.error(this, "Found "+r+" many times in "+this, new Exception("error"));
removeElement(found);
} else {
break;
}
}
}
if(count == 0) Logger.error(this, "Not in parent: "+r+" for "+this, new Exception("error"));
else if(persistent) {
container.store(this);
r.removeFrom(container);
}
}
}
| spencerjackson/fred-staging | src/freenet/support/SectoredRandomGrabArray.java | Java | gpl-2.0 | 11,090 |
/*
* 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 opennlp.tools.formats;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import opennlp.tools.cmdline.ArgumentParser;
import opennlp.tools.cmdline.ArgumentParser.ParameterDescription;
import opennlp.tools.cmdline.CmdLineUtil;
import opennlp.tools.cmdline.StreamFactoryRegistry;
import opennlp.tools.cmdline.TerminateToolException;
import opennlp.tools.cmdline.params.EncodingParameter;
import opennlp.tools.doccat.DocumentSample;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.ObjectStreamUtils;
/**
* <b>Note:</b> Do not use this class, internal use only!
*/
public class LeipzigDocumentSampleStreamFactory
extends AbstractSampleStreamFactory<DocumentSample> {
protected <P> LeipzigDocumentSampleStreamFactory(Class<P> params) {
super(params);
}
public static void registerFactory() {
StreamFactoryRegistry.registerFactory(DocumentSample.class,
"leipzig", new LeipzigDocumentSampleStreamFactory(Parameters.class));
}
public ObjectStream<DocumentSample> create(String[] args) {
Parameters params = ArgumentParser.parse(args, Parameters.class);
File sentencesFileDir = params.getSentencesDir();
File[] sentencesFiles = sentencesFileDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.contains("sentences") && name.endsWith(".txt");
}
});
@SuppressWarnings("unchecked")
ObjectStream<DocumentSample>[] sampleStreams =
new ObjectStream[sentencesFiles.length];
for (int i = 0; i < sentencesFiles.length; i++) {
try {
sampleStreams[i] = new LeipzigDoccatSampleStream(
sentencesFiles[i].getName().substring(0, 3), 20,
CmdLineUtil.createInputStreamFactory(sentencesFiles[i]));
} catch (IOException e) {
throw new TerminateToolException(-1, "IO error while opening sample data: " + e.getMessage(), e);
}
}
return ObjectStreamUtils.createObjectStream(sampleStreams);
}
interface Parameters extends EncodingParameter {
@ParameterDescription(valueName = "sentencesDir",
description = "dir with Leipig sentences to be used")
File getSentencesDir();
}
}
| manjeetk09/GoogleScrapper | opennlp/tools/formats/LeipzigDocumentSampleStreamFactory.java | Java | gpl-2.0 | 3,047 |
/**
* Copyright (c) 2008-2012 Indivica Inc.
*
* This software is made available under the terms of the
* GNU General Public License, Version 2, 1991 (GPLv2).
* License details are available via "indivica.ca/gplv2"
* and "gnu.org/licenses/gpl-2.0.html".
*/
package org.oscarehr.olis;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import org.oscarehr.olis.dao.OLISSystemPreferencesDao;
import org.oscarehr.olis.model.OLISSystemPreferences;
import org.oscarehr.util.DbConnectionFilter;
import org.oscarehr.util.MiscUtils;
import org.oscarehr.util.SpringUtils;
/**
* A job can start many tasks
*
* @author Indivica
*/
public class OLISSchedulerJob extends TimerTask {
private static final Logger logger = MiscUtils.getLogger();
@Override
public void run() {
try {
logger.info("starting OLIS poller job");
OLISSystemPreferencesDao olisPrefDao = (OLISSystemPreferencesDao) SpringUtils.getBean("OLISSystemPreferencesDao");
OLISSystemPreferences olisPrefs = olisPrefDao.getPreferences();
if (olisPrefs == null) {
// not set to run at all
logger.info("Don't need to run right now..no prefs");
return;
}
Date now = new Date();
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmssZ");
Date startDate = null, endDate = null;
try {
if (olisPrefs.getStartTime() != null && olisPrefs.getStartTime().trim().length() > 0) startDate = dateFormatter.parse(olisPrefs.getStartTime());
if (olisPrefs.getEndTime() != null && olisPrefs.getEndTime().trim().length() > 0) endDate = dateFormatter.parse(olisPrefs.getEndTime());
} catch (ParseException e) {
logger.error("Error", e);
}
logger.info("start date = " + startDate);
logger.info("end date = " + endDate);
if ((startDate != null && now.before(startDate)) || (endDate != null && now.after(endDate))) {
logger.info("Don't need to run right now");
return;
}
if (olisPrefs.getLastRun() != null) {
// check to see if we are past last run + frequency interval
int freqMins = olisPrefs.getPollFrequency();
Calendar cal = Calendar.getInstance();
cal.setTime(olisPrefs.getLastRun());
cal.add(Calendar.MINUTE, freqMins);
if (cal.getTime().getTime() > now.getTime()) {
logger.info("not yet time to run - last run @ " + olisPrefs.getLastRun() + " and freq is " + freqMins + " mins.");
return;
}
}
logger.info("===== OLIS JOB RUNNING....");
olisPrefs.setLastRun(new Date());
olisPrefDao.merge(olisPrefs);
OLISPollingUtil.requestResults();
} catch (Exception e) {
logger.error("error", e);
} finally {
DbConnectionFilter.releaseAllThreadDbResources();
}
}
}
| hexbinary/landing | src/main/java/org/oscarehr/olis/OLISSchedulerJob.java | Java | gpl-2.0 | 2,800 |
package challengetask.group02.controllers.exceptions;
public class FsException extends Exception {
public FsException(String message) {
super(message);
}
}
| lisgie/ChallengeTask_Group2 | src/main/challengetask/group02/controllers/exceptions/FsException.java | Java | gpl-2.0 | 173 |
package org.freeplane.features.presentations.mindmapmode;
import static org.freeplane.features.presentations.mindmapmode.CollectionChangedEvent.EventType.COLLECTION_SIZE_CHANGED;
import static org.freeplane.features.presentations.mindmapmode.CollectionChangedEvent.EventType.SELECTION_CHANGED;
import static org.freeplane.features.presentations.mindmapmode.CollectionChangedEvent.EventType.SELECTION_INDEX_CHANGED;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import org.freeplane.core.util.TextUtils;
public class NamedElementCollection<T extends NamedElement<T>> implements Iterable<T>{
final private DefaultComboBoxModel<Stringifyed<T>> elements;
private int currentIndex;
private ArrayList<CollectionChangeListener<T>> collectionChangeListeners;
private boolean moveInProgress;
private NamedElementFactory<T> factory;
public NamedElementCollection(NamedElementFactory<T> factory) {
super();
this.factory = factory;
this.elements = new DefaultComboBoxModel<>();
elements.addListDataListener(new ListDataListener() {
@Override
public void intervalRemoved(ListDataEvent e) {
}
@Override
public void intervalAdded(ListDataEvent e) {
}
@Override
public void contentsChanged(ListDataEvent e) {
final int index = e.getIndex0();
if (index == -1 && e.getIndex1() == index && ! moveInProgress){
final int newIndex = elements.getIndexOf(elements.getSelectedItem());
if(newIndex != -1) {
currentIndex = newIndex;
fireCollectionChangeEvent(SELECTION_INDEX_CHANGED);
fireCollectionChangeEvent(SELECTION_CHANGED);
}
}
}
});
currentIndex = -1;
collectionChangeListeners = new ArrayList<>();
}
public ComboBoxModel<Stringifyed<T>> getElements() {
return elements;
}
public void add(String name) {
final T currentElement = getCurrentElement();
final T newInstance = currentElement != null ? factory.create(currentElement, name) : factory.create(name);
add(newInstance);
}
public void add(T element) {
final int newElementIndex = currentIndex + 1;
final Stringifyed<T> anObject = new Stringifyed<>(element);
elements.insertElementAt(anObject, newElementIndex);
elements.setSelectedItem(anObject);
selectCurrentElement(newElementIndex);
fireCollectionChangeEvent(COLLECTION_SIZE_CHANGED);
}
public void removeCurrentElement() {
if(currentIndex >= 0) {
elements.removeElementAt(currentIndex);
selectCurrentElement(Math.min(currentIndex, elements.getSize() - 1));
fireCollectionChangeEvent(COLLECTION_SIZE_CHANGED);
}
}
public void selectCurrentElement(int index) {
if(currentIndex != index) {
currentIndex = index;
final Stringifyed<T> newSelecteditem = index == -1 ? null : elements.getElementAt(index);
if(newSelecteditem != elements.getSelectedItem()) {
elements.setSelectedItem(newSelecteditem);
}
else {
fireCollectionChangeEvent(SELECTION_INDEX_CHANGED);
fireCollectionChangeEvent(SELECTION_CHANGED);
}
}
}
private void fireCollectionChangeEvent(CollectionChangedEvent.EventType eventType) {
for (CollectionChangeListener<T> selectionChangeListener : collectionChangeListeners)
selectionChangeListener.onCollectionChange(eventType.of(this));
}
public int getSize() {
return elements.getSize();
}
public T getCurrentElement() {
return currentIndex >= 0 ? elements.getElementAt(currentIndex).element : null;
}
public void moveCurrentElementUp() {
moveCurrentElementTo(currentIndex - 1);
}
public void moveCurrentElementDown() {
moveCurrentElementTo(currentIndex + 1);
}
public void moveCurrentElementTo(int newElementIndex) {
if(canMoveCurrentElementTo(newElementIndex)) {
final Stringifyed<T> currentElement = elements.getElementAt(currentIndex);
moveInProgress = true;
try {
elements.removeElementAt(currentIndex);
elements.insertElementAt(currentElement, newElementIndex);
currentIndex = newElementIndex;
elements.setSelectedItem(currentElement);
} finally {
moveInProgress = false;
}
fireCollectionChangeEvent(SELECTION_INDEX_CHANGED);
}
}
public boolean canMoveCurrentElementTo(int newElementIndex) {
return newElementIndex >= 0 && newElementIndex < getSize() && newElementIndex != currentIndex;
}
public void addCollectionChangeListener(CollectionChangeListener<T> selectionChangeListener) {
this.collectionChangeListeners.add(selectionChangeListener);
}
public void removeCollectionChangeListener(CollectionChangeListener<T> selectionChangeListener) {
this.collectionChangeListeners.remove(selectionChangeListener);
}
public int getCurrentElementIndex() {
return currentIndex;
}
public T getElement(int i) {
return elements.getElementAt(i).element;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < getSize();
}
@Override
public T next() {
if(hasNext())
return NamedElementCollection.this.getElement(index++);
else
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
public void copyCurrentElement() {
final T currentElement = getCurrentElement();
String newName = TextUtils.format("copy_name", currentElement.getName());
final T newInstance = currentElement.saveAs(newName);
add(newInstance);
}
}
| fnatter/freeplane-debian-dev | freeplane/src/main/java/org/freeplane/features/presentations/mindmapmode/NamedElementCollection.java | Java | gpl-2.0 | 5,644 |
///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.graph;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static edu.cmu.tetrad.graph.Edges.directedEdge;
/**
* <p>Stores a graph a list of lists of edges adjacent to each node in the
* graph, with an additional list storing all of the edges in the graph. The
* edges are of the form N1 *-# N2. Multiple edges may be added per node pair to
* this graph, with the caveat that all edges of the form N1 *-# N2 will be
* considered equal. For example, if the edge X --> Y is added to the graph,
* another edge X --> Y may not be added, although an edge Y --> X may be added.
* Edges from nodes to themselves may also be added.</p>
*
* @author Joseph Ramsey
* @author Erin Korber additions summer 2004
* @see edu.cmu.tetrad.graph.Endpoint
*/
public class EdgeListGraph implements Graph, TripleClassifier {
static final long serialVersionUID = 23L;
/**
* A list of the nodes in the graph, in the order in which they were added.
*
* @serial
*/
protected List<Node> nodes;
/**
* The edges in the graph.
*
* @serial
*/
Set<Edge> edgesSet;
/**
* Map from each node to the List of edges connected to that node.
*
* @serial
*/
Map<Node, List<Edge>> edgeLists;
/**
* Fires property change events.
*/
protected transient PropertyChangeSupport pcs;
/**
* Set of ambiguous triples. Note the name can't be changed due to
* serialization.
*/
protected Set<Triple> ambiguousTriples = Collections.newSetFromMap(new ConcurrentHashMap<Triple, Boolean>());
/**
* @serial
*/
Set<Triple> underLineTriples = Collections.newSetFromMap(new ConcurrentHashMap<Triple, Boolean>());
/**
* @serial
*/
Set<Triple> dottedUnderLineTriples = Collections.newSetFromMap(new ConcurrentHashMap<Triple, Boolean>());
/**
* True iff nodes were removed since the last call to an accessor for ambiguous, underline, or dotted underline
* triples. If there are triples in the lists involving removed nodes, these need to be removed from the lists
* first, so as not to cause confusion.
*/
boolean stuffRemovedSinceLastTripleAccess = false;
/**
* The set of highlighted edges.
*/
Set<Edge> highlightedEdges = new HashSet<>();
/**
* A hash from node names to nodes;
*/
Map<String, Node> namesHash = new HashMap<>();
private boolean pattern = false;
private boolean pag = false;
//==============================CONSTUCTORS===========================//
/**
* Constructs a new (empty) EdgeListGraph.
*/
public EdgeListGraph() {
this.edgeLists = new HashMap<>();
this.nodes = new ArrayList<>();
this.edgesSet = new HashSet<>();
this.namesHash = new HashMap<>();
for (Node node : nodes) {
namesHash.put(node.getName(), node);
}
}
/**
* Constructs a EdgeListGraph using the nodes and edges of the given graph.
* If this cannot be accomplished successfully, an exception is thrown. Note
* that any graph constraints from the given graph are forgotten in the new
* graph.
*
* @param graph the graph from which nodes and edges are is to be
* extracted.
* @throws IllegalArgumentException if a duplicate edge is added.
*/
public EdgeListGraph(Graph graph) throws IllegalArgumentException {
this();
if (graph == null) {
throw new NullPointerException("Graph must not be null.");
}
transferNodesAndEdges(graph);
this.ambiguousTriples = graph.getAmbiguousTriples();
this.underLineTriples = graph.getUnderLines();
this.dottedUnderLineTriples = graph.getDottedUnderlines();
for (Edge edge : graph.getEdges()) {
if (graph.isHighlighted(edge)) {
setHighlighted(edge, true);
}
}
for (Node node : nodes) {
namesHash.put(node.getName(), node);
}
this.pag = graph.isPag();
this.pattern = graph.isPattern();
}
/**
* Constructs a new graph, with no edges, using the the given variable
* names.
*/
public EdgeListGraph(List<Node> nodes) {
this();
if (nodes == null) {
throw new NullPointerException();
}
// for (int i = 0; i < nodes.size(); i++) {
// if (nodes.get(i) == null) {
// throw new NullPointerException();
// }
//
// for (int j = 0; j < i; j++) {
// if (nodes.get(i).equals(nodes.get(j))) {
// throw new IllegalArgumentException("Two variables by the same name: " + nodes.get(i));
// }
// }
// }
for (Object variable : nodes) {
if (!addNode((Node) variable)) {
throw new IllegalArgumentException();
}
}
// DataGraphUtils.circleLayout(this, 200, 200, 150);
for (Node node : nodes) {
namesHash.put(node.getName(), node);
}
}
// Makes a copy with the same object identical edges in it. If you make changes to those edges they will be
// reflected here.
public static Graph shallowCopy(EdgeListGraph graph) {
EdgeListGraph _graph = new EdgeListGraph();
_graph.nodes = new ArrayList<>(graph.nodes);
_graph.edgesSet = new HashSet<>(graph.edgesSet);
_graph.edgeLists = new HashMap<>(graph.edgeLists);
for (Node node : graph.nodes) _graph.edgeLists.put(node, new ArrayList<>(graph.edgeLists.get(node)));
_graph.ambiguousTriples = new HashSet<>(graph.ambiguousTriples);
_graph.underLineTriples = new HashSet<>(graph.underLineTriples);
_graph.dottedUnderLineTriples = new HashSet<>(graph.dottedUnderLineTriples);
_graph.stuffRemovedSinceLastTripleAccess = graph.stuffRemovedSinceLastTripleAccess;
_graph.highlightedEdges = new HashSet<>(graph.highlightedEdges);
_graph.namesHash = new HashMap<>(graph.namesHash);
_graph.pag = graph.pag;
_graph.pattern = graph.pattern;
return _graph;
}
/**
* Generates a simple exemplar of this class to test serialization.
*/
public static EdgeListGraph serializableInstance() {
return new EdgeListGraph();
}
//===============================PUBLIC METHODS========================//
/**
* Adds a directed edge to the graph from node A to node B.
*
* @param node1 the "from" node.
* @param node2 the "to" node.
*/
public boolean addDirectedEdge(Node node1, Node node2) {
return addEdge(directedEdge(node1, node2));
}
/**
* Adds an undirected edge to the graph from node A to node B.
*
* @param node1 the "from" node.
* @param node2 the "to" node.
*/
public boolean addUndirectedEdge(Node node1, Node node2) {
return addEdge(Edges.undirectedEdge(node1, node2));
}
/**
* Adds a nondirected edge to the graph from node A to node B.
*
* @param node1 the "from" node.
* @param node2 the "to" node.
*/
public boolean addNondirectedEdge(Node node1, Node node2) {
return addEdge(Edges.nondirectedEdge(node1, node2));
}
/**
* Adds a partially oriented edge to the graph from node A to node B.
*
* @param node1 the "from" node.
* @param node2 the "to" node.
*/
public boolean addPartiallyOrientedEdge(Node node1, Node node2) {
return addEdge(Edges.partiallyOrientedEdge(node1, node2));
}
/**
* Adds a bidirected edge to the graph from node A to node B.
*
* @param node1 the "from" node.
* @param node2 the "to" node.
*/
public boolean addBidirectedEdge(Node node1, Node node2) {
return addEdge(Edges.bidirectedEdge(node1, node2));
}
public boolean existsDirectedCycle() {
for (Node node : getNodes()) {
if (GraphUtils.existsDirectedPathFromToBreathFirst(node, node, this)) {
return true;
}
// if (existsDirectedPathFromTo(node, node)) {
// return true;
// }
}
return false;
}
public boolean isDirectedFromTo(Node node1, Node node2) {
List<Edge> edges = getEdges(node1, node2);
if (edges.size() != 1) return false;
Edge edge = edges.get(0);
return edge.pointsTowards(node2);
}
public boolean isUndirectedFromTo(Node node1, Node node2) {
Edge edge = getEdge(node1, node2);
return edge != null && edge.getEndpoint1() == Endpoint.TAIL && edge.getEndpoint2() == Endpoint.TAIL;
// return getEdges(node1, node2).size() == 1
// && getEndpoint(node2, node1) == Endpoint.TAIL
// && getEndpoint(node1, node2) == Endpoint.TAIL;
}
/**
* added by ekorber, 2004/06/11
*
* @return true if the given edge is definitely visible (Jiji, pg 25)
* @throws IllegalArgumentException if the given edge is not a directed edge
* in the graph
*/
public boolean defVisible(Edge edge) {
if (containsEdge(edge)) {
Node A = Edges.getDirectedEdgeTail(edge);
Node B = Edges.getDirectedEdgeHead(edge);
List<Node> adjToA = getAdjacentNodes(A);
while (!adjToA.isEmpty()) {
Node Curr = adjToA.remove(0);
if (!((getAdjacentNodes(Curr)).contains(B)) &&
((getEdge(Curr, A)).getProximalEndpoint(A) == Endpoint
.ARROW)) {
return true;
}
}
return false;
} else {
throw new IllegalArgumentException(
"Given edge is not in the graph.");
}
}
/**
* IllegalArgument exception raised (by isDirectedFromTo(getEndpoint) or by
* getEdge) if there are multiple edges between any of the node pairs.
*/
public boolean isDefNoncollider(Node node1, Node node2, Node node3) {
List<Edge> edges = getEdges(node2);
boolean circle12 = false;
boolean circle32 = false;
for (Edge edge : edges) {
boolean _node1 = edge.getDistalNode(node2) == node1;
boolean _node3 = edge.getDistalNode(node2) == node3;
if (_node1 && edge.pointsTowards(node1)) return true;
if (_node3 && edge.pointsTowards(node3)) return true;
if (_node1 && edge.getProximalEndpoint(node2) == Endpoint.CIRCLE) circle12 = true;
if (_node3 && edge.getProximalEndpoint(node2) == Endpoint.CIRCLE) circle32 = true;
if (circle12 && circle32 && !isAdjacentTo(node1, node2)) return true;
}
return false;
// if (isDirectedFromTo(node2, node1) || isDirectedFromTo(node2, node3)) {
// return true;
// } else if (!isAdjacentTo(node1, node3)) {
// boolean endpt1 = getEndpoint(node1, node2) == Endpoint.CIRCLE;
// boolean endpt2 = getEndpoint(node3, node2) == Endpoint.CIRCLE;
// return (endpt1 && endpt2);
//// } else if (getEndpoint(node1, node2) == Endpoint.TAIL && getEndpoint(node3, node2) == Endpoint.TAIL){
//// return true;
// } else {
// return false;
// }
}
public boolean isDefCollider(Node node1, Node node2, Node node3) {
// List<Node> nodes2 = getNodesInTo(node2, Endpoint.ARROW);
// return nodes2.contains(node1) && nodes2.contains(node3);
Edge edge1 = getEdge(node1, node2);
Edge edge2 = getEdge(node2, node3);
return !(edge1 == null || edge2 == null) && edge1.getProximalEndpoint(node2) == Endpoint.ARROW && edge2.getProximalEndpoint(node2) == Endpoint.ARROW;
}
/**
* @return true iff there is a directed path from node1 to node2.
* a
*/
public boolean existsDirectedPathFromTo(Node node1, Node node2) {
return existsDirectedPathVisit(node1, node2, new HashSet<Node>());
}
public boolean existsUndirectedPathFromTo(Node node1, Node node2) {
return existsUndirectedPathVisit(node1, node2, new HashSet<Node>());
}
public boolean existsSemiDirectedPathFromTo(Node node1, Set<Node> nodes) {
return existsSemiDirectedPathVisit(node1, nodes,
new LinkedList<Node>());
}
/**
* Determines whether a trek exists between two nodes in the graph. A trek
* exists if there is a directed path between the two nodes or else, for
* some third node in the graph, there is a path to each of the two nodes in
* question.
*/
public boolean existsTrek(Node node1, Node node2) {
for (Node node : getNodes()) {
if (isAncestorOf((node), node1) && isAncestorOf((node), node2)) {
return true;
}
}
return false;
}
/**
* @return the list of children for a node.
*/
public List<Node> getChildren(Node node) {
List<Node> children = new ArrayList<>();
for (Object o : getEdges(node)) {
Edge edge = (Edge) (o);
Node sub = Edges.traverseDirected(node, edge);
if (sub != null) {
children.add(sub);
}
}
return children;
}
public int getConnectivity() {
int connectivity = 0;
List<Node> nodes = getNodes();
for (Node node : nodes) {
int n = getNumEdges(node);
if (n > connectivity) {
connectivity = n;
}
}
return connectivity;
}
public List<Node> getDescendants(List<Node> nodes) {
Set<Node> descendants = new HashSet<>();
for (Object node1 : nodes) {
Node node = (Node) node1;
collectDescendantsVisit(node, descendants);
}
return new LinkedList<>(descendants);
}
/**
* @return the edge connecting node1 and node2, provided a unique such edge
* exists.
*/
public synchronized Edge getEdge(Node node1, Node node2) {
List<Edge> edges = edgeLists.get(node1);
if (edges == null) return null;
for (Edge edge : edges) {
if (edge.getNode1() == node1 && edge.getNode2() == node2) {
return edge;
} else if (edge.getNode1() == node2 && edge.getNode2() == node1) {
return edge;
}
}
return null;
}
public Edge getDirectedEdge(Node node1, Node node2) {
List<Edge> edges = getEdges(node1, node2);
if (edges == null) return null;
if (edges.size() == 0) {
return null;
}
for (Edge edge : edges) {
if (Edges.isDirectedEdge(edge) && edge.getProximalEndpoint(node2) == Endpoint.ARROW) {
return edge;
}
}
return null;
}
/**
* @return the list of parents for a node.
*/
public List<Node> getParents(Node node) {
List<Node> parents = new ArrayList<>();
List<Edge> edges = edgeLists.get(node);
for (Edge edge : new ArrayList<>(edges)) {
// if (edge == null) continue;
Endpoint endpoint1 = edge.getDistalEndpoint(node);
Endpoint endpoint2 = edge.getProximalEndpoint(node);
if (endpoint1 == Endpoint.TAIL && endpoint2 == Endpoint.ARROW) {
parents.add(edge.getDistalNode(node));
}
}
return parents;
}
/**
* @return the number of edges into the given node.
*/
public int getIndegree(Node node) {
return getParents(node).size();
}
@Override
public int getDegree(Node node) {
return edgeLists.get(node).size();
}
/**
* @return the number of edges out of the given node.
*/
public int getOutdegree(Node node) {
return getChildren(node).size();
}
/**
* Determines whether some edge or other exists between two nodes.
*/
public boolean isAdjacentTo(Node node1, Node node2) {
if (node1 == null || node2 == null || edgeLists.get(node1) == null || edgeLists.get(node2) == null) {
return false;
}
for (Edge edge : edgeLists.get(node1)) {
if (Edges.traverse(node1, edge) == node2) {
return true;
}
}
return false;
}
/**
* Determines whether one node is an ancestor of another.
*/
// public boolean isAncestorOf(Node node1, Node node2) {
// boolean b = (node1 == node2) || GraphUtils.existsDirectedPathFromTo(node1, node2, this);
//
// System.out.println(node1 + " ancestor of " + node2 + " = " + b);
//
// return b;
// }
protected Map<Node, Set<Node>> ancestors = null;
/**
* Determines whether one node is an ancestor of another.
*/
public boolean isAncestorOf(Node node1, Node node2) {
return getAncestors(Collections.singletonList(node2)).contains(node1);
// if (ancestors == null) {
// ancestors = new HashMap<>();
// }
//
// if (ancestors.get(node2) != null) {
// return ancestors.get(node2).contains(node1);
// }
//
// ancestors.put(node2, new HashSet<>(getAncestors(Collections.singletonList(node2))));
//
// return ancestors.get(node2).contains(node1);
}
public boolean possibleAncestor(Node node1, Node node2) {
return existsSemiDirectedPathFromTo(node1,
Collections.singleton(node2));
}
/**
* @return true iff node1 is a possible ancestor of at least one member of
* nodes2
*/
protected boolean possibleAncestorSet(Node node1, List<Node> nodes2) {
for (Object aNodes2 : nodes2) {
if (possibleAncestor(node1, (Node) aNodes2)) {
return true;
}
}
return false;
}
public List<Node> getAncestors(List<Node> nodes) {
HashSet<Node> ancestors = new HashSet<>();
for (Object node1 : nodes) {
Node node = (Node) node1;
collectAncestorsVisit(node, ancestors);
}
return new ArrayList<>(ancestors);
}
/**
* Determines whether one node is a child of another.
*/
public boolean isChildOf(Node node1, Node node2) {
for (Object o : getEdges(node2)) {
Edge edge = (Edge) (o);
Node sub = Edges.traverseDirected(node2, edge);
if (sub == node1) {
return true;
}
}
return false;
}
/**
* Determines whether one node is a descendent of another.
*/
public boolean isDescendentOf(Node node1, Node node2) {
return (node1 == node2) || isProperDescendentOf(node1, node2);
}
/**
* added by ekorber, 2004/06/12
*
* @return true iff node2 is a definite nondecendent of node1
*/
public boolean defNonDescendent(Node node1, Node node2) {
return !(possibleAncestor(node1, node2));
}
public boolean isDConnectedTo(Node x, Node y, List<Node> z) {
return GraphUtils.isDConnectedTo(x, y, z, this);
}
protected boolean isDConnectedTo(List<Node> x, List<Node> y, List<Node> z) {
Set<Node> zAncestors = zAncestors(z);
Queue<Pair> Q = new ArrayDeque<>();
Set<Pair> V = new HashSet<>();
for (Node _x : x) {
for (Node node : getAdjacentNodes(_x)) {
if (y.contains(node)) return true;
Pair edge = new Pair(_x, node);
Q.offer(edge);
V.add(edge);
}
}
while (!Q.isEmpty()) {
Pair t = Q.poll();
Node b = t.getY();
Node a = t.getX();
for (Node c : getAdjacentNodes(b)) {
if (c == a) continue;
boolean collider = isDefCollider(a, b, c);
if (!((collider && zAncestors.contains(b)) || (!collider && !z.contains(b)))) continue;
if (y.contains(c)) return true;
Pair u = new Pair(b, c);
if (V.contains(u)) continue;
V.add(u);
Q.offer(u);
}
}
return false;
}
public List<Node> getSepset(Node x, Node y) {
return GraphUtils.getSepset(x, y, this);
}
@Override
public void setNodes(List<Node> nodes) {
if (nodes.size() != this.nodes.size()) {
throw new IllegalArgumentException("Sorry, there is a mismatch in the number of variables " +
"you are trying to set.");
}
this.nodes = nodes;
}
protected Set<Node> zAncestors(List<Node> z) {
Queue<Node> Q = new ArrayDeque<>();
Set<Node> V = new HashSet<>();
for (Node node : z) {
Q.offer(node);
V.add(node);
}
while (!Q.isEmpty()) {
Node t = Q.poll();
for (Node c : getParents(t)) {
if (V.contains(c)) continue;
V.add(c);
Q.offer(c);
}
}
return V;
}
public boolean isDSeparatedFrom(List<Node> x, List<Node> y, List<Node> z) {
return !isDConnectedTo(x, y, z);
}
/**
* True if this graph has been stamped as a pattern. The search algorithm should do this.
*/
@Override
public boolean isPattern() {
return pattern;
}
@Override
public void setPattern(boolean pattern) {
this.pattern = pattern;
}
/**
* True if this graph has been "stamped" as a PAG. The search algorithm should do this.
*/
@Override
public boolean isPag() {
return pag;
}
@Override
public void setPag(boolean pag) {
this.pag = pag;
}
private static class Pair {
private Node x;
private Node y;
Pair(Node x, Node y) {
this.x = x;
this.y = y;
}
public Node getX() {
return x;
}
public Node getY() {
return y;
}
public int hashCode() {
return x.hashCode() + 17 * y.hashCode();
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
Pair pair = (Pair) o;
return x == pair.getX() && y == pair.getY();
}
public String toString() {
return "(" + x.toString() + ", " + y.toString() + ")";
}
}
/**
* Determines whether one n ode is d-separated from another. According to
* Spirtes, Richardson & Meek, two nodes are d- connected given some
* conditioning set Z if there is an acyclic undirected path U between them,
* such that every collider on U is an ancestor of some element in Z and
* every non-collider on U is not in Z. Two elements are d-separated just
* in case they are not d-connected. A collider is a node which two edges
* hold in common for which the endpoints leading into the node are both
* arrow endpoints.
*
* @param node1 the first node.
* @param node2 the second node.
* @param z the conditioning set.
* @return true if node1 is d-separated from node2 given set t, false if
* not.
* @see #isDConnectedTo
*/
public boolean isDSeparatedFrom(Node node1, Node node2, List<Node> z) {
return !isDConnectedTo(node1, node2, z);
}
//added by ekorber, June 2004
public boolean possDConnectedTo(Node node1, Node node2,
List<Node> condNodes) {
LinkedList<Node> allNodes = new LinkedList<>(getNodes());
int sz = allNodes.size();
int[][] edgeStage = new int[sz][sz];
int stage = 1;
int n1x = allNodes.indexOf(node1);
int n2x = allNodes.indexOf(node2);
edgeStage[n1x][n1x] = 1;
edgeStage[n2x][n2x] = 1;
List<int[]> currEdges;
List<int[]> nextEdges = new LinkedList<>();
int[] temp1 = new int[2];
temp1[0] = n1x;
temp1[1] = n1x;
nextEdges.add(temp1);
int[] temp2 = new int[2];
temp2[0] = n2x;
temp2[1] = n2x;
nextEdges.add(temp2);
while (true) {
currEdges = nextEdges;
nextEdges = new LinkedList<>();
for (int[] edge : currEdges) {
Node center = allNodes.get(edge[1]);
List<Node> adj = new LinkedList<>(getAdjacentNodes(center));
for (Node anAdj : adj) {
// check if we've hit this edge before
int testIndex = allNodes.indexOf(anAdj);
if (edgeStage[edge[1]][testIndex] != 0) {
continue;
}
// if the edge pair violates possible d-connection,
// then go to the next adjacent node.
Node X = allNodes.get(edge[0]);
Node Y = allNodes.get(edge[1]);
Node Z = allNodes.get(testIndex);
if (!((isDefNoncollider(X, Y, Z) &&
!(condNodes.contains(Y))) || (
isDefCollider(X, Y, Z) &&
possibleAncestorSet(Y, condNodes)))) {
continue;
}
// if it gets here, then it's legal, so:
// (i) if this is the one we want, we're done
if (anAdj.equals(node2)) {
return true;
}
// (ii) if we need to keep going,
// add the edge to the nextEdges list
int[] nextEdge = new int[2];
nextEdge[0] = edge[1];
nextEdge[1] = testIndex;
nextEdges.add(nextEdge);
// (iii) set the edgeStage array
edgeStage[edge[1]][testIndex] = stage;
edgeStage[testIndex][edge[1]] = stage;
}
}
// find out if there's any reason to move to the next stage
if (nextEdges.size() == 0) {
break;
}
stage++;
}
return false;
}
/**
* Determines whether an inducing path exists between node1 and node2, given
* a set O of observed nodes and a set sem of conditioned nodes.
*
* @param node1 the first node.
* @param node2 the second node.
* @return true if an inducing path exists, false if not.
*/
public boolean existsInducingPath(Node node1, Node node2) {
return node1 == node2 || GraphUtils.existsDirectedPathFromToBreathFirst(node2, node1, this);
}
/**
* Determines whether one node is a parent of another.
*
* @param node1 the first node.
* @param node2 the second node.
* @return true if node1 is a parent of node2, false if not.
* @see #isChildOf
* @see #getParents
* @see #getChildren
*/
public boolean isParentOf(Node node1, Node node2) {
for (Edge edge : getEdges(node1)) {
Node sub = Edges.traverseDirected(node1, (edge));
if (sub == node2) {
return true;
}
}
return false;
}
/**
* Determines whether one node is a proper ancestor of another.
*/
public boolean isProperAncestorOf(Node node1, Node node2) {
return node1 != node2 && isAncestorOf(node1, node2);
}
/**
* Determines whether one node is a proper decendent of another
*/
public boolean isProperDescendentOf(Node node1, Node node2) {
return node1 != node2 && isDescendentOf(node1, node2);
}
/**
* Transfers nodes and edges from one graph to another. One way this is
* used is to change graph types. One constructs a new graph based on the
* old graph, and this method is called to transfer the nodes and edges of
* the old graph to the new graph.
*
* @param graph the graph from which nodes and edges are to be pilfered.
* @throws IllegalArgumentException This exception is thrown if adding some
* node or edge violates one of the
* basicConstraints of this graph.
*/
public void transferNodesAndEdges(Graph graph)
throws IllegalArgumentException {
if (graph == null) {
throw new NullPointerException("No graph was provided.");
}
// System.out.println("TANSFER BEFORE " + graph.getEdges());
for (Node node : graph.getNodes()) {
if (!addNode(node)) {
throw new IllegalArgumentException();
}
}
for (Edge edge : graph.getEdges()) {
if (!addEdge(edge)) {
throw new IllegalArgumentException();
}
}
ancestors = null;
// System.out.println("TANSFER AFTER " + getEdges());
}
/**
* Determines whether a node in a graph is exogenous.
*/
public boolean isExogenous(Node node) {
return getIndegree(node) == 0;
}
/**
* @return the set of nodes adjacent to the given node. If there are multiple edges between X and Y, Y will show
* up twice in the list of adjacencies for X, for optimality; simply create a list an and array from these to
* eliminate the duplication.
*/
public List<Node> getAdjacentNodes(Node node) {
List<Edge> edges = edgeLists.get(node);
Set<Node> adj = new HashSet<>(edges.size());
for (Edge edge : edges) {
if (edge == null) continue;
Node z = edge.getDistalNode(node);
if (!adj.contains(z)) {
adj.add(z);
}
}
return new ArrayList<>(adj);
}
/**
* Removes the edge connecting the two given nodes.
*/
public boolean removeEdge(Node node1, Node node2) {
List<Edge> edges = getEdges(node1, node2);
if (edges.size() > 1) {
throw new IllegalStateException(
"There is more than one edge between " + node1 + " and " +
node2);
}
return removeEdges(edges);
}
/**
* @return the endpoint along the edge from node to node2 at the node2 end.
*/
public Endpoint getEndpoint(Node node1, Node node2) {
List<Edge> edges = getEdges(node2);
for (Edge edge : edges) {
if (edge.getDistalNode(node2) == node1) return edge.getProximalEndpoint(node2);
}
return null;
// List<Edge> edges = getEdges(node1, node2);
//
// if (edges.size() == 0) {
// retu rn null;
// }
//
// if (edges.size() > 1) {
// throw new IllegalArgumentException(
// "More than one edge between " + node1 + " and " + node2);
// }
//
// return (edges.get(0)).getProximalEndpoint(node2);
}
/**
* If there is currently an edge from node1 to node2, sets the endpoint at
* node2 to the given endpoint; if there is no such edge, adds an edge --#
* where # is the given endpoint. Setting an endpoint to null, provided
* there is exactly one edge connecting the given nodes, removes the edge.
* (If there is more than one edge, an exception is thrown.)
*
* @throws IllegalArgumentException if the edge with the revised endpoint
* cannot be added to the graph.
*/
public boolean setEndpoint(Node from, Node to, Endpoint endPoint)
throws IllegalArgumentException {
List<Edge> edges = getEdges(from, to);
ancestors = null;
if (endPoint == null) {
throw new NullPointerException();
} else if (edges.size() == 0) {
removeEdges(from, to);
addEdge(new Edge(from, to, Endpoint.TAIL, endPoint));
return true;
} else if (edges.size() == 1) {
Edge edge = edges.get(0);
Edge newEdge = new Edge(from, to, edge.getProximalEndpoint(from), endPoint);
try {
removeEdges(edge.getNode1(), edge.getNode2());
addEdge(newEdge);
return true;
} catch (IllegalArgumentException e) {
return false;
}
} else {
throw new NullPointerException(
"An endpoint between node1 and node2 " +
"may not be set in this graph if there is more than one " +
"edge between node1 and node2.");
}
}
/**
* Nodes adjacent to the given node with the given proximal endpoint.
*/
public List<Node> getNodesInTo(Node node, Endpoint endpoint) {
List<Node> nodes = new ArrayList<>(4);
List<Edge> edges = getEdges(node);
for (Object edge1 : edges) {
Edge edge = (Edge) edge1;
if (edge.getProximalEndpoint(node) == endpoint) {
nodes.add(edge.getDistalNode(node));
}
}
return nodes;
}
/**
* Nodes adjacent to the given node with the given distal endpoint.
*/
public List<Node> getNodesOutTo(Node node, Endpoint endpoint) {
List<Node> nodes = new ArrayList<>(4);
List<Edge> edges = getEdges(node);
for (Object edge1 : edges) {
Edge edge = (Edge) edge1;
if (edge.getDistalEndpoint(node) == endpoint) {
nodes.add(edge.getDistalNode(node));
}
}
return nodes;
}
/**
* @return a matrix of endpoints for the nodes in this graph, with nodes in
* the same order as getNodes().
*/
public Endpoint[][] getEndpointMatrix() {
int size = nodes.size();
Endpoint[][] endpoints = new Endpoint[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == j) {
continue;
}
Node nodei = nodes.get(i);
Node nodej = nodes.get(j);
endpoints[i][j] = getEndpoint(nodei, nodej);
}
}
return endpoints;
}
/**
* Adds an edge to the graph.
*
* @param edge the edge to be added
* @return true if the edge was added, false if not.
*/
public boolean addEdge(Edge edge) {
if (edge == null) throw new NullPointerException();
List<Edge> edgeList1 = edgeLists.get(edge.getNode1());
List<Edge> edgeList2 = edgeLists.get(edge.getNode2());
if (edgeList1 == null || edgeList2 == null) {
// Do not comment this out; if the user changes the names of variables, this is the
// mechanism for adjusting the maps from nodes to edge lists to compensate.
edgeLists = new HashMap<>(edgeLists);
edgeList1 = edgeLists.get(edge.getNode1());
edgeList2 = edgeLists.get(edge.getNode2());
}
if (edgeList1 == null || edgeList2 == null) {
throw new NullPointerException("Can't add an edge unless both " +
"nodes are in the graph: " + edge);
}
if (edgeList1.contains(edge)) {
return true;
// throw new IllegalArgumentException(
// "That edge is already in the graph: " + edge);
}
if (edgeList2.contains(edge)) {
return true;
// throw new IllegalArgumentException(
// "That edge is already in the graph: " + edge);
}
edgeList1 = new ArrayList<>(edgeList1);
edgeList2 = new ArrayList<>(edgeList2);
edgeList1.add(edge);
edgeList2.add(edge);
edgeLists.put(edge.getNode1(), edgeList1);
edgeLists.put(edge.getNode2(), edgeList2);
edgesSet.add(edge);
if (Edges.isDirectedEdge(edge)) {
Node node = Edges.getDirectedEdgeTail(edge);
if (node.getNodeType() == NodeType.ERROR) {
getPcs().firePropertyChange("nodeAdded", null, node);
}
}
ancestors = null;
getPcs().firePropertyChange("edgeAdded", null, edge);
return true;
}
/**
* Adds a PropertyChangeListener to the graph.
*
* @param l the property change listener.
*/
public void addPropertyChangeListener(PropertyChangeListener l) {
getPcs().addPropertyChangeListener(l);
}
/**
* Adds a node to the graph. Precondition: The proposed name of the node
* cannot already be used by any other node in the same graph.
*
* @param node the node to be added.
* @return true if the the node was added, false if not.
*/
public boolean addNode(Node node) {
if (nodes.contains(node)) return true;
if (node == null) {
throw new NullPointerException();
}
if (!(getNode(node.getName()) == null)) {
if (nodes.contains(node)) {
namesHash.put(node.getName(), node);
}
}
if (edgeLists.containsKey(node)) {
return false;
}
edgeLists.put(node, new ArrayList<Edge>(4));
nodes.add(node);
namesHash.put(node.getName(), node);
if (node.getNodeType() != NodeType.ERROR) {
getPcs().firePropertyChange("nodeAdded", null, node);
}
return true;
}
/**
* @return the list of edges in the graph. No particular ordering of the
* edges in the list is guaranteed.
*/
public Set<Edge> getEdges() {
return new HashSet<>(this.edgesSet);
}
/**
* Determines if the graph contains a particular edge.
*/
public boolean containsEdge(Edge edge) {
return edgesSet.contains(edge);
}
/**
* Determines whether the graph contains a particular node.
*/
public boolean containsNode(Node node) {
return nodes.contains(node);
}
/**
* @return the list of edges connected to a particular node. No particular
* ordering of the edges in the list is guaranteed.
*/
public synchronized List<Edge> getEdges(Node node) {
List<Edge> list = edgeLists.get(node);
return new ArrayList<>(list);
}
public int hashCode() {
int hashCode = 0;
int sum = 0;
for (Node node : getNodes()) {
sum += node.hashCode();
}
hashCode += 23 * sum;
sum = 0;
for (Edge edge : getEdges()) {
sum += edge.hashCode();
}
hashCode += 41 * sum;
return hashCode;
}
/**
* @return true iff the given object is a graph that is equal to this graph,
* in the sense that it contains the same nodes and the edges are
* isomorphic.
*/
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o instanceof EdgeListGraph) {
EdgeListGraph _o = (EdgeListGraph) o;
boolean nodesEqual = new HashSet<>(_o.nodes).equals(new HashSet<>(this.nodes));
boolean edgesEqual = new HashSet<>(_o.edgesSet).equals(new HashSet<>(this.edgesSet));
return (nodesEqual && edgesEqual);
} else {
Graph graph = (Graph) o;
return new HashSet<>(graph.getNodeNames()).equals(new HashSet<>(getNodeNames())) &&
new HashSet<>(graph.getEdges()).equals(new HashSet<>(getEdges()));
}
}
/**
* Resets the graph so that it is fully connects it using #-# edges, where #
* is the given endpoint.
*/
public void fullyConnect(Endpoint endpoint) {
edgesSet.clear();
edgeLists.clear();
for (Node node : nodes) {
edgeLists.put(node, new ArrayList<Edge>(4));
}
for (int i = 0; i < nodes.size(); i++) {
for (int j = i + 1; j < nodes.size(); j++) {
Node node1 = nodes.get(i);
Node node2 = nodes.get(j);
Edge edge = new Edge(node1, node2, endpoint, endpoint);
addEdge(edge);
}
}
}
public void reorientAllWith(Endpoint endpoint) {
for (Edge edge : new ArrayList<>(edgesSet)) {
Node a = edge.getNode1();
Node b = edge.getNode2();
setEndpoint(a, b, endpoint);
setEndpoint(b, a, endpoint);
}
}
/**
* @return the node with the given name, or null if no such node exists.
*/
public Node getNode(String name) {
return namesHash.get(name);
}
/**
* @return the number of nodes in the graph.
*/
public int getNumNodes() {
return nodes.size();
}
/**
* @return the number of edges in the (entire) graph.
*/
public int getNumEdges() {
return edgesSet.size();
}
/**
* @return the number of edges connected to a particular node in the graph.
*/
public int getNumEdges(Node node) {
List<Edge> list = edgeLists.get(node);
return (list == null) ? 0 : list.size();
}
public List<Node> getNodes() {
return new ArrayList<>(nodes);
}
/**
* Removes all nodes (and therefore all edges) from the graph.
*/
public void clear() {
Iterator<Edge> it = getEdges().iterator();
while (it.hasNext()) {
Edge edge = it.next();
it.remove();
getPcs().firePropertyChange("edgeRemoved", edge, null);
}
Iterator<Node> it2 = this.nodes.iterator();
while (it2.hasNext()) {
Node node = it2.next();
it2.remove();
namesHash.remove(node.getName());
getPcs().firePropertyChange("nodeRemoved", node, null);
}
edgeLists.clear();
}
/**
* Removes an edge from the graph. (Note: It is dangerous to make a
* recursive call to this method (as it stands) from a method containing
* certain types of iterators. The problem is that if one uses an iterator
* that iterates over the edges of node A or node B, and tries in the
* process to remove those edges using this method, a concurrent
* modification exception will be thrown.)
*
* @param edge the edge to remove.
* @return true if the edge was removed, false if not.
*/
public synchronized boolean removeEdge(Edge edge) {
if (!edgesSet.contains(edge)) {
return false;
}
List<Edge> edgeList1 = edgeLists.get(edge.getNode1());
List<Edge> edgeList2 = edgeLists.get(edge.getNode2());
edgeList1 = new ArrayList<>(edgeList1);
edgeList2 = new ArrayList<>(edgeList2);
edgesSet.remove(edge);
edgeList1.remove(edge);
edgeList2.remove(edge);
edgeLists.put(edge.getNode1(), edgeList1);
edgeLists.put(edge.getNode2(), edgeList2);
highlightedEdges.remove(edge);
stuffRemovedSinceLastTripleAccess = true;
ancestors = null;
getPcs().firePropertyChange("edgeRemoved", edge, null);
return true;
}
/**
* Removes any relevant edge objects found in this collection. G
*
* @param edges the collection of edges to remove.
* @return true if any edges in the collection were removed, false if not.
*/
public boolean removeEdges(Collection<Edge> edges) {
boolean change = false;
for (Edge edge : edges) {
boolean _change = removeEdge(edge);
change = change || _change;
}
return change;
}
/**
* Removes all edges connecting node A to node B.
*
* @param node1 the first node.,
* @param node2 the second node.
* @return true if edges were removed between A and B, false if not.
*/
public boolean removeEdges(Node node1, Node node2) {
return removeEdges(getEdges(node1, node2));
}
/**
* Removes a node from the graph.
*/
public boolean removeNode(Node node) {
if (!nodes.contains(node)) {
return false;
}
boolean changed = false;
List<Edge> edgeList1 =
edgeLists.get(node); //list of edges connected to that node
for (Iterator<Edge> i = edgeList1.iterator(); i.hasNext(); ) {
Edge edge = (i.next());
Node node2 = edge.getDistalNode(node);
if (node2 != node) {
List<Edge> edgeList2 = edgeLists.get(node2);
edgeList2.remove(edge);
edgesSet.remove(edge);
changed = true;
}
i.remove();
getPcs().firePropertyChange("edgeRemoved", edge, null);
}
edgeLists.remove(node);
nodes.remove(node);
namesHash.remove(node.getName());
stuffRemovedSinceLastTripleAccess = true;
getPcs().firePropertyChange("nodeRemoved", node, null);
return changed;
}
/**
* Removes any relevant node objects found in this collection.
*
* @param newNodes the collection of nodes to remove.
* @return true if nodes from the collection were removed, false if not.
*/
public boolean removeNodes(List<Node> newNodes) {
boolean changed = false;
for (Object newNode : newNodes) {
boolean _changed = removeNode((Node) newNode);
changed = changed || _changed;
}
return changed;
}
/**
* @return a string representation of the graph.
*/
public String toString() {
return GraphUtils.graphToText(this).toString();
}
public Graph subgraph(List<Node> nodes) {
Graph graph = new EdgeListGraph(nodes);
Set<Edge> edges = getEdges();
for (Object edge1 : edges) {
Edge edge = (Edge) edge1;
if (nodes.contains(edge.getNode1()) &&
nodes.contains(edge.getNode2())) {
graph.addEdge(edge);
}
}
return graph;
}
/**
* @return the edges connecting node1 and node2.
*/
public List<Edge> getEdges(Node node1, Node node2) {
List<Edge> edges = edgeLists.get(node1);
List<Edge> _edges = new ArrayList<>();
for (Edge edge : edges) {
if (edge.getDistalNode(node1) == node2) {
_edges.add(edge);
}
}
return _edges;
}
public Set<Triple> getAmbiguousTriples() {
// removeTriplesNotInGraph();
return new HashSet<>(ambiguousTriples);
}
public Set<Triple> getUnderLines() {
// removeTriplesNotInGraph();
return new HashSet<>(underLineTriples);
}
public Set<Triple> getDottedUnderlines() {
// removeTriplesNotInGraph();
return new HashSet<>(dottedUnderLineTriples);
}
/**
* States whether r-s-r is an underline triple or not.
*/
public boolean isAmbiguousTriple(Node x, Node y, Node z) {
// Triple triple = new Triple(x, y, z);
// if (!triple.alongPathIn(this)) {
// throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> is not along a path.");
// }
// removeTriplesNotInGraph();
return ambiguousTriples.contains(new Triple(x, y, z));
}
/**
* States whether r-s-r is an underline triple or not.
*/
public boolean isUnderlineTriple(Node x, Node y, Node z) {
// Triple triple = new Triple(x, y, z);
// if (!triple.alongPathIn(this)) {
// throw new IllegalArgumentException("<" + r + ", " + s + ", " + t + "> is not along a path.");
// }
// removeTriplesNotInGraph();
return underLineTriples.contains(new Triple(x, y, z));
}
/**
* States whether r-s-r is an underline triple or not.
*/
public boolean isDottedUnderlineTriple(Node x, Node y, Node z) {
// Triple triple = new Triple(x, y, z);
// if (!triple.alongPathIn(this)) {
// throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> is not along a path.");
// }
// removeTriplesNotInGraph();
return dottedUnderLineTriples.contains(new Triple(x, y, z));
}
public void addAmbiguousTriple(Node x, Node y, Node z) {
ambiguousTriples.add(new Triple(x, y, z));
}
public void addUnderlineTriple(Node x, Node y, Node z) {
Triple triple = new Triple(x, y, z);
if (!triple.alongPathIn(this)) {
return;
// throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> must lie along a path in the graph.");
}
underLineTriples.add(new Triple(x, y, z));
}
public void addDottedUnderlineTriple(Node x, Node y, Node z) {
Triple triple = new Triple(x, y, z);
if (!triple.alongPathIn(this)) {
return;
// throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> must lie along a path in the graph.");
}
dottedUnderLineTriples.add(triple);
}
public void removeAmbiguousTriple(Node x, Node y, Node z) {
ambiguousTriples.remove(new Triple(x, y, z));
}
public void removeUnderlineTriple(Node x, Node y, Node z) {
underLineTriples.remove(new Triple(x, y, z));
}
public void removeDottedUnderlineTriple(Node x, Node y, Node z) {
dottedUnderLineTriples.remove(new Triple(x, y, z));
}
public void setAmbiguousTriples(Set<Triple> triples) {
ambiguousTriples.clear();
for (Triple triple : triples) {
addAmbiguousTriple(triple.getX(), triple.getY(), triple.getZ());
}
}
public void setUnderLineTriples(Set<Triple> triples) {
underLineTriples.clear();
for (Triple triple : triples) {
addUnderlineTriple(triple.getX(), triple.getY(), triple.getZ());
}
}
public void setDottedUnderLineTriples(Set<Triple> triples) {
dottedUnderLineTriples.clear();
for (Triple triple : triples) {
addDottedUnderlineTriple(triple.getX(), triple.getY(), triple.getZ());
}
}
public List<String> getNodeNames() {
List<String> names = new ArrayList<>();
for (Node node : getNodes()) {
names.add(node.getName());
}
return names;
}
//===============================PRIVATE METHODS======================//
public void removeTriplesNotInGraph() {
// if (!stuffRemovedSinceLastTripleAccess) return;
for (Triple triple : new HashSet<>(ambiguousTriples)) {
if (!containsNode(triple.getX()) || !containsNode(triple.getY()) || !containsNode(triple.getZ())) {
ambiguousTriples.remove(triple);
continue;
}
if (!isAdjacentTo(triple.getX(), triple.getY()) || !isAdjacentTo(triple.getY(), triple.getZ())) {
ambiguousTriples.remove(triple);
}
}
for (Triple triple : new HashSet<>(underLineTriples)) {
if (!containsNode(triple.getX()) || !containsNode(triple.getY()) || !containsNode(triple.getZ())) {
underLineTriples.remove(triple);
continue;
}
if (!isAdjacentTo(triple.getX(), triple.getY()) || !isAdjacentTo(triple.getY(), triple.getZ())) {
underLineTriples.remove(triple);
}
}
for (Triple triple : new HashSet<>(dottedUnderLineTriples)) {
if (!containsNode(triple.getX()) || !containsNode(triple.getY()) || !containsNode(triple.getZ())) {
dottedUnderLineTriples.remove(triple);
continue;
}
if (!isAdjacentTo(triple.getX(), triple.getY()) || !isAdjacentTo(triple.getY(), triple.getZ())) {
dottedUnderLineTriples.remove(triple);
}
}
stuffRemovedSinceLastTripleAccess = false;
}
private void collectAncestorsVisit(Node node, Set<Node> ancestors) {
if (ancestors.contains(node)) return;
ancestors.add(node);
List<Node> parents = getParents(node);
if (!parents.isEmpty()) {
for (Node parent : parents) {
collectAncestorsVisit(parent, ancestors);
}
}
}
private void collectDescendantsVisit(Node node, Set<Node> descendants) {
descendants.add(node);
List<Node> children = getChildren(node);
if (!children.isEmpty()) {
for (Object aChildren : children) {
Node child = (Node) aChildren;
doChildClosureVisit(child, descendants);
}
}
}
/**
* closure under the child relation
*/
private void doChildClosureVisit(Node node, Set<Node> closure) {
if (!closure.contains(node)) {
closure.add(node);
for (Edge edge1 : getEdges(node)) {
Node sub = Edges.traverseDirected(node, edge1);
if (sub == null) {
continue;
}
doChildClosureVisit(sub, closure);
}
}
}
/**
* This is a simple auxiliary visit method for the isDConnectedTo() method
* used to find the closure of a conditioning set of nodes under the parent
* relation.
*
* @param node the node in question
* @param closure the closure of the conditioning set uner the parent
* relation (to be calculated recursively).
*/
private void doParentClosureVisit(Node node, Set<Node> closure) {
if (closure.contains(node)) return;
closure.add(node);
for (Edge edge : getEdges(node)) {
Node sub = Edges.traverseReverseDirected(node, edge);
if (sub != null) {
doParentClosureVisit(sub, closure);
}
}
}
/**
* @return this object.
*/
protected PropertyChangeSupport getPcs() {
if (pcs == null) {
pcs = new PropertyChangeSupport(this);
}
return pcs;
}
/**
* @return true iff there is a directed path from node1 to node2.
*/
boolean existsUndirectedPathVisit(Node node1, Node node2, Set<Node> path) {
path.add(node1);
for (Edge edge : getEdges(node1)) {
Node child = Edges.traverse(node1, edge);
if (child == null) {
continue;
}
if (child == node2) {
return true;
}
if (path.contains(child)) {
continue;
}
if (existsUndirectedPathVisit(child, node2, path)) {
return true;
}
}
path.remove(node1);
return false;
}
boolean existsDirectedPathVisit(Node node1, Node node2, Set<Node> path) {
path.add(node1);
for (Edge edge : getEdges(node1)) {
Node child = Edges.traverseDirected(node1, edge);
if (child == null) {
continue;
}
if (child == node2) {
return true;
}
if (path.contains(child)) {
continue;
}
if (existsDirectedPathVisit(child, node2, path)) {
return true;
}
}
path.remove(node1);
return false;
}
/**
* @return true iff there is a semi-directed path from node1 to node2
*/
private boolean existsSemiDirectedPathVisit(Node node1, Set<Node> nodes2,
LinkedList<Node> path) {
path.addLast(node1);
for (Edge edge : getEdges(node1)) {
Node child = Edges.traverseSemiDirected(node1, edge);
if (child == null) {
continue;
}
if (nodes2.contains(child)) {
return true;
}
if (path.contains(child)) {
continue;
}
if (existsSemiDirectedPathVisit(child, nodes2, path)) {
return true;
}
}
path.removeLast();
return false;
}
public List<Node> getCausalOrdering() {
return GraphUtils.getCausalOrdering(this);
}
public void setHighlighted(Edge edge, boolean highlighted) {
highlightedEdges.add(edge);
}
public boolean isHighlighted(Edge edge) {
return highlightedEdges.contains(edge);
}
public boolean isParameterizable(Node node) {
return true;
}
public boolean isTimeLagModel() {
return false;
}
public TimeLagGraph getTimeLagGraph() {
return null;
}
/**
* Adds semantic checks to the default deserialization method. This method
* must have the standard signature for a readObject method, and the body of
* the method must begin with "s.defaultReadObject();". Other than that, any
* semantic checks can be specified and do not need to stay the same from
* version to version. A readObject method of this form may be added to any
* class, even if Tetrad sessions were previously saved out using a version
* of the class that didn't include it. (That's what the
* "s.defaultReadObject();" is for. See J. Bloch, Effective Java, for help.
*
* @throws java.io.IOException
* @throws ClassNotFoundException
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (nodes == null) {
throw new NullPointerException();
}
if (edgesSet == null) {
throw new NullPointerException();
}
if (edgeLists == null) {
throw new NullPointerException();
}
if (ambiguousTriples == null) {
ambiguousTriples = new HashSet<>();
}
if (highlightedEdges == null) {
highlightedEdges = new HashSet<>();
}
if (underLineTriples == null) {
underLineTriples = new HashSet<>();
}
if (dottedUnderLineTriples == null) {
dottedUnderLineTriples = new HashSet<>();
}
}
public void changeName(String name, String newName) {
Node node = namesHash.get(name);
namesHash.remove(name);
node.setName(newName);
namesHash.put(newName, node);
}
/**
* @return the names of the triple classifications. Coordinates with <code>getTriplesList</code>
*/
public List<String> getTriplesClassificationTypes() {
List<String> names = new ArrayList<>();
names.add("Underlines");
names.add("Dotted Underlines");
names.add("Ambiguous Triples");
return names;
}
/**
* @return the list of triples corresponding to <code>getTripleClassificationNames</code> for the given
* node.
*/
public List<List<Triple>> getTriplesLists(Node node) {
List<List<Triple>> triplesList = new ArrayList<>();
triplesList.add(GraphUtils.getUnderlinedTriplesFromGraph(node, this));
triplesList.add(GraphUtils.getDottedUnderlinedTriplesFromGraph(node, this));
triplesList.add(GraphUtils.getAmbiguousTriplesFromGraph(node, this));
return triplesList;
}
}
| ekummerfeld/GdistanceP | tetrad-lib/src/main/java/edu/cmu/tetrad/graph/EdgeListGraph.java | Java | gpl-2.0 | 61,880 |
package com.floreantpos.ui.ticket;
import java.awt.Color;
import java.awt.Rectangle;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import com.floreantpos.model.Ticket;
import com.floreantpos.model.TicketItem;
import com.floreantpos.model.TicketItemModifier;
import com.floreantpos.util.ModifierStateChangeListener;
public class TicketViewerTable extends JTable {
private TicketViewerTableModel model;
private DefaultListSelectionModel selectionModel;
private TicketViewerTableCellRenderer cellRenderer;
private ModifierStateChangeListener modifierStateChangeListener;
public TicketViewerTable() {
this(null);
}
public TicketViewerTable(Ticket ticket) {
model = new TicketViewerTableModel(this);
setModel(model);
selectionModel = new DefaultListSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellRenderer = new TicketViewerTableCellRenderer();
setGridColor(Color.LIGHT_GRAY);
setSelectionModel(selectionModel);
setAutoscrolls(true);
setShowGrid(true);
setBorder(null);
setFocusable(false);
setRowHeight(60);
resizeTableColumns();
setTicket(ticket);
}
private void resizeTableColumns() {
setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS);
setColumnWidth(1, 50);
setColumnWidth(2, 30);
setColumnWidth(3, 60);
}
private void setColumnWidth(int columnNumber, int width) {
TableColumn column = getColumnModel().getColumn(columnNumber);
column.setPreferredWidth(width);
column.setMaxWidth(width);
column.setMinWidth(width);
}
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
return cellRenderer;
}
public TicketViewerTableCellRenderer getRenderer() {
return cellRenderer;
}
private boolean isTicketNull() {
Ticket ticket = getTicket();
if (ticket == null) {
return true;
}
if (ticket.getTicketItems() == null) {
return true;
}
return false;
}
public void scrollUp() {
if (isTicketNull())
return;
int selectedRow = getSelectedRow();
int rowCount = model.getItemCount();
if (selectedRow > (rowCount - 1)) {
return;
}
--selectedRow;
selectionModel.addSelectionInterval(selectedRow, selectedRow);
Rectangle cellRect = getCellRect(selectedRow, 0, false);
scrollRectToVisible(cellRect);
}
public void scrollDown() {
if (isTicketNull())
return;
int selectedRow = getSelectedRow();
if (selectedRow >= model.getItemCount() - 1) {
return;
}
++selectedRow;
selectionModel.addSelectionInterval(selectedRow, selectedRow);
Rectangle cellRect = getCellRect(selectedRow, 0, false);
scrollRectToVisible(cellRect);
}
public void increaseItemAmount(TicketItem ticketItem) {
int itemCount = ticketItem.getItemCount();
ticketItem.setItemCount(++itemCount);
repaint();
}
public boolean increaseItemAmount() {
int selectedRow = getSelectedRow();
if (selectedRow < 0) {
return false;
}
else if (selectedRow >= model.getItemCount()) {
return false;
}
Object object = model.get(selectedRow);
if (object instanceof TicketItem) {
TicketItem ticketItem = (TicketItem) object;
int itemCount = ticketItem.getItemCount();
ticketItem.setItemCount(++itemCount);
repaint();
return true;
}
else if (object instanceof TicketItemModifier) {
TicketItemModifier modifier = (TicketItemModifier) object;
int itemCount = modifier.getItemCount();
modifier.setItemCount(++itemCount);
repaint();
if(modifierStateChangeListener != null) {
modifierStateChangeListener.modifierStateChanged();
}
return true;
}
return false;
}
public boolean decreaseItemAmount() {
int selectedRow = getSelectedRow();
if (selectedRow < 0) {
return false;
}
else if (selectedRow >= model.getItemCount()) {
return false;
}
Object object = model.get(selectedRow);
if (object instanceof TicketItem) {
TicketItem ticketItem = (TicketItem) object;
int itemCount = ticketItem.getItemCount();
if (itemCount == 1)
return false;
ticketItem.setItemCount(--itemCount);
repaint();
return true;
}
else if (object instanceof TicketItemModifier) {
TicketItemModifier modifier = (TicketItemModifier) object;
int itemCount = modifier.getItemCount();
if (itemCount == 1)
return false;
modifier.setItemCount(--itemCount);
repaint();
if(modifierStateChangeListener != null) {
modifierStateChangeListener.modifierStateChanged();
}
return true;
}
return false;
}
public void setTicket(Ticket ticket) {
model.setTicket(ticket);
}
public Ticket getTicket() {
return model.getTicket();
}
public void addTicketItem(TicketItem ticketItem) {
ticketItem.setTicket(getTicket());
int addTicketItem = model.addTicketItem(ticketItem);
int actualRowCount = addTicketItem;//getActualRowCount() - 1;
selectionModel.addSelectionInterval(actualRowCount, actualRowCount);
Rectangle cellRect = getCellRect(actualRowCount, 0, false);
scrollRectToVisible(cellRect);
}
public Object deleteSelectedItem() {
int selectedRow = getSelectedRow();
Object delete = model.delete(selectedRow);
if(delete instanceof TicketItemModifier) {
if(modifierStateChangeListener != null) {
TicketItemModifier modifier = (TicketItemModifier) delete;
modifier.setModifierType(TicketItemModifier.MODIFIER_NOT_INITIALIZED);
modifier.setItemCount(0);
modifierStateChangeListener.updateView(modifier);
}
}
return delete;
}
public boolean containsTicketItem(TicketItem ticketItem) {
return model.containsTicketItem(ticketItem);
}
public void delete(int index) {
model.delete(index);
}
public Object get(int index) {
return model.get(index);
}
public Object getSelected() {
int index = getSelectedRow();
return model.get(index);
}
public void addAllTicketItem(TicketItem ticketItem) {
model.addAllTicketItem(ticketItem);
}
public void removeModifier(TicketItem parent, TicketItemModifier modifier) {
model.removeModifier(parent, modifier);
}
public void updateView() {
int selectedRow = getSelectedRow();
model.update();
try {
getSelectionModel().setSelectionInterval(selectedRow, selectedRow);
}catch (Exception e) {
// do nothing
}
}
public int getActualRowCount() {
return model.getActualRowCount();
}
public void selectLast() {
int actualRowCount = getActualRowCount() - 1;
selectionModel.addSelectionInterval(actualRowCount, actualRowCount);
Rectangle cellRect = getCellRect(actualRowCount, 0, false);
scrollRectToVisible(cellRect);
}
public void selectRow(int index) {
if(index < 0 || index >= getActualRowCount()) {
index = 0;
}
selectionModel.addSelectionInterval(index, index);
Rectangle cellRect = getCellRect(index, 0, false);
scrollRectToVisible(cellRect);
}
public ModifierStateChangeListener getModifierStateChangeListener() {
return modifierStateChangeListener;
}
public void setModifierStateChangeListener(ModifierStateChangeListener modifierStateChangeListener) {
this.modifierStateChangeListener = modifierStateChangeListener;
}
}
| meyerdg/floreant | src/com/floreantpos/ui/ticket/TicketViewerTable.java | Java | gpl-2.0 | 7,550 |
/*
* Copyright (c) 2005, 2006, 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.xml.internal.bind.v2.runtime.reflect.opt;
import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor;
/**
* Template {@link Accessor} for boolean getter/setter.
*
* <p>
* All the MethodAccessors are generated from <code>MethodAccessor_B y t e</code>
*
* @author Kohsuke Kawaguchi
*/
public class MethodAccessor_Double extends Accessor {
public MethodAccessor_Double() {
super(Double.class);
}
public Object get(Object bean) {
return ((Bean)bean).get_double();
}
public void set(Object bean, Object value) {
((Bean)bean).set_double( value==null ? Const.default_value_double : (Double)value );
}
}
| samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/xml/internal/bind/v2/runtime/reflect/opt/MethodAccessor_Double.java | Java | gpl-2.0 | 1,887 |
/*
* SSHTools - Java SSH2 API
*
* Copyright (C) 2002-2003 Lee David Painter and Contributors.
*
* Contributions made by:
*
* Brett Smith
* Richard Pernavas
* Erwin Bolwidt
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// ===========================================================================
// CONTENT : CLASS StringPattern
// AUTHOR : Manfred Duchrow
// VERSION : 1.7 - 13/02/2003
// HISTORY :
// 24/01/2000 duma CREATED
// 08/01/2002 duma bugfix -> Handle *xxx (equal characters after star) correctly
// 16/01/2002 duma changed -> Implements Serializable
// 06/07/2002 duma bugfix -> Couldn't match "London" on "L*n"
// 19/09/2002 duma bugfix -> Couldn't match "MA_DR_HRBLUB" on "*_HR*"
// 19/09/2002 duma changed -> Using now StringExaminer instead of CharacterIterator
// 29/09/2002 duma changed -> Refactored: Using StringExaminer instead of StringScanner
// 26/12/2002 duma changed -> Comment of matches() was wrong / new hasWildcard()
// 13/02/2003 duma added -> setDigitWildcardChar()
//
// Copyright (c) 2000-2003, by Manfred Duchrow. All rights reserved.
// ===========================================================================
package com.sshtools.daemon.util;
// ===========================================================================
// IMPORTS
// ===========================================================================
import java.io.*;
/**
* This class provides services for checking strings against string-patterns.
* Currently it supports the wildcards<br>
* '' for any number of any character and <br>
* '?' for any one character. The API is very simple:<br>
* <br>
* There are only the two class methods <i>match()</i> and
* <i>matchIgnoreCase()</i>. <br>
* Example: <br>
* StringPattern.match( 'Hello World", "H W" ) ; --> evaluates to true <br>
* StringPattern.matchIgnoreCase( 'StringPattern", "str???pat" ) ; -->
* evaluates to true <br>
*
* @author Manfred Duchrow
* @version 1.7
*/
public class StringPattern implements Serializable {
// =========================================================================
// CONSTANTS
// =========================================================================
/** */
protected final static String MULTI_WILDCARD = "*";
/** */
protected final static char MULTICHAR_WILDCARD = '*';
/** */
protected final static char SINGLECHAR_WILDCARD = '?';
// =========================================================================
// INSTANCE VARIABLES
// =========================================================================
private boolean ignoreCase = false;
private String pattern = null;
// -------------------------------------------------------------------------
private Character digitWildcard = null;
// -------------------------------------------------------------------------
// =========================================================================
// CONSTRUCTORS
// =========================================================================
/**
* Initializes the new instance with the string pattern and the selecteion,
* if case should be ignored when comparing characters.
*
* @param pattern The pattern to check against ( May contain '' and '?'
* wildcards )
* @param ignoreCase Definition, if case sensitive character comparison or
* not.
*/
public StringPattern(String pattern, boolean ignoreCase) {
this.setPattern(pattern);
this.setIgnoreCase(ignoreCase);
}
// StringPattern()
// -------------------------------------------------------------------------
/**
* Initializes the new instance with the string pattern. The default is
* case sensitive checking.
*
* @param pattern The pattern to check against ( May contain '' and '?'
* wildcards )
*/
public StringPattern(String pattern) {
this(pattern, false);
}
// StringPattern()
// -------------------------------------------------------------------------
/**
* Initializes the new instance with the string pattern and a digit
* wildcard character. The default is case sensitive checking.
*
* @param pattern The pattern to check against ( May contain '', '?'
* wildcards and the digit wildcard )
* @param digitWildcard A wildcard character that stands as placeholder for
* digits
*/
public StringPattern(String pattern, char digitWildcard) {
this(pattern, false, digitWildcard);
}
// StringPattern()
// -------------------------------------------------------------------------
/**
* Initializes the new instance with the string pattern and the selecteion,
* if case should be ignored when comparing characters plus a wildcard
* character for digits.
*
* @param pattern The pattern to check against ( May contain '' and '?'
* wildcards )
* @param ignoreCase Definition, if case sensitive character comparison or
* not.
* @param digitWildcard A wildcard character that stands as placeholder for
* digits
*/
public StringPattern(String pattern, boolean ignoreCase, char digitWildcard) {
this.setPattern(pattern);
this.setIgnoreCase(ignoreCase);
this.setDigitWildcardChar(digitWildcard);
}
// StringPattern()
/**
* Returns whether or not the pattern matching ignores upper and lower case
*
* @return
*/
public boolean getIgnoreCase() {
return ignoreCase;
}
/**
* Sets whether the pattern matching should ignore case or not
*
* @param newValue
*/
public void setIgnoreCase(boolean newValue) {
ignoreCase = newValue;
}
/**
* Returns the pattern as string.
*
* @return
*/
public String getPattern() {
return pattern;
}
/**
* Sets the pattern to a new value
*
* @param newValue
*/
public void setPattern(String newValue) {
pattern = newValue;
}
/**
*
*
* @return
*/
protected Character digitWildcard() {
return digitWildcard;
}
/**
*
*
* @param newValue
*/
protected void digitWildcard(Character newValue) {
digitWildcard = newValue;
}
// =========================================================================
// CLASS METHODS
// =========================================================================
/**
* Returns true, if the given probe string matches the given pattern. <br>
* The character comparison is done case sensitive.
*
* @param probe The string to check against the pattern.
* @param pattern The patter, that probably contains wildcards ( '' or '?'
* )
*
* @return
*/
public static boolean match(String probe, String pattern) {
StringPattern stringPattern = new StringPattern(pattern, false);
return (stringPattern.matches(probe));
}
// match()
// -------------------------------------------------------------------------
/**
* Returns true, if the given probe string matches the given pattern. <br>
* The character comparison is done ignoring upper/lower-case.
*
* @param probe The string to check against the pattern.
* @param pattern The patter, that probably contains wildcards ( '' or '?'
* )
*
* @return
*/
public static boolean matchIgnoreCase(String probe, String pattern) {
StringPattern stringPattern = new StringPattern(pattern, true);
return (stringPattern.matches(probe));
}
// matchIgnoreCase()
// -------------------------------------------------------------------------
// =========================================================================
// PUBLIC INSTANCE METHODS
// =========================================================================
/**
* Tests if a specified string matches the pattern.
*
* @param probe The string to compare to the pattern
*
* @return true if and only if the probe matches the pattern, false
* otherwise.
*/
public boolean matches(String probe) {
StringExaminer patternIterator = null;
StringExaminer probeIterator = null;
char patternCh = '-';
char probeCh = '-';
String newPattern = null;
String subPattern = null;
int charIndex = 0;
if (probe == null) {
return false;
}
if (probe.length() == 0) {
return false;
}
patternIterator = this.newExaminer(this.getPattern());
probeIterator = this.newExaminer(probe);
probeCh = probeIterator.nextChar();
patternCh = this.getPatternChar(patternIterator, probeCh);
while ((this.endNotReached(patternCh)) &&
(this.endNotReached(probeCh))) {
if (patternCh == MULTICHAR_WILDCARD) {
patternCh = this.skipWildcards(patternIterator);
if (this.endReached(patternCh)) {
return true; // No more characters after multi wildcard - So everything matches
} else {
patternIterator.skip(-1);
newPattern = this.upToEnd(patternIterator);
charIndex = newPattern.indexOf(MULTICHAR_WILDCARD);
if (charIndex >= 0) {
subPattern = newPattern.substring(0, charIndex);
if (this.skipAfter(probeIterator, subPattern)) {
patternIterator = this.newExaminer(newPattern.substring(
charIndex));
patternCh = probeCh;
} else {
return false;
}
} else {
probeIterator.skip(-1);
return this.matchReverse(newPattern, probeIterator);
}
}
}
if (this.charsAreEqual(probeCh, patternCh)) {
if (this.endNotReached(patternCh)) {
probeCh = probeIterator.nextChar();
patternCh = this.getPatternChar(patternIterator, probeCh);
}
} else {
if (patternCh != MULTICHAR_WILDCARD) {
return false; // character is not matching - return immediately
}
}
}
// while()
return ((this.endReached(patternCh)) && (this.endReached(probeCh)));
}
// matches()
// -------------------------------------------------------------------------
/**
* Returns the pattern string.
*
* @see java.lang.Object#toString()
*/
public String toString() {
if (this.getPattern() == null) {
return super.toString();
} else {
return this.getPattern();
}
}
// toString()
// -------------------------------------------------------------------------
/**
* Returns true if the pattern contains any '' or '?' wildcard character.
*
* @return
*/
public boolean hasWildcard() {
if (this.getPattern() == null) {
return false;
}
if (this.hasDigitWildcard()) {
if (this.getPattern().indexOf(this.digitWildcardChar()) >= 0) {
return true;
}
}
return (this.getPattern().indexOf(MULTI_WILDCARD) >= 0) ||
(this.getPattern().indexOf(SINGLECHAR_WILDCARD) >= 0);
}
// hasWildcard()
// -------------------------------------------------------------------------
/**
* Sets the given character as a wildcard character in this pattern to
* match only digits ('0'-'9'). <br>
*
* @param digitWildcard The placeholder character for digits
*/
public void setDigitWildcardChar(char digitWildcard) {
if (digitWildcard <= 0) {
this.digitWildcard(null);
} else {
this.digitWildcard(new Character(digitWildcard));
}
}
// setDigitWildcardChar()
/**
*
*
* @return
*/
protected boolean hasDigitWildcard() {
return this.digitWildcard() != null;
}
// hasDigitWildcard()
// -------------------------------------------------------------------------
protected char digitWildcardChar() {
if (this.hasDigitWildcard()) {
return this.digitWildcard().charValue();
} else {
return '\0';
}
}
// digitWildcardChar()
// -------------------------------------------------------------------------
/**
* Moves the iterator position to the next character that is no wildcard.
* Doesn't skip digit wildcards !
*
* @param iterator
*
* @return
*/
protected char skipWildcards(StringExaminer iterator) {
char result = '-';
do {
result = iterator.nextChar();
} while ((result == MULTICHAR_WILDCARD) ||
(result == SINGLECHAR_WILDCARD));
return result;
}
// skipWildcards()
// -------------------------------------------------------------------------
/**
* Increments the given iterator up to the last character that matched the
* character sequence in the given matchString. Returns true, if the
* matchString was found, otherwise false.
*
* @param examiner
* @param matchString The string to be found (must not contain )
*
* @return
*/
protected boolean skipAfter(StringExaminer examiner, String matchString) {
// Do not use the method of StringExaminer anymore, because digit wildcard
// support is in the charsAreEqual() method which is unknown to the examiner.
// return examiner.skipAfter( matchString ) ;
char ch = '-';
char matchChar = ' ';
boolean found = false;
int index = 0;
if ((matchString == null) || (matchString.length() == 0)) {
return false;
}
ch = examiner.nextChar();
while ((examiner.endNotReached(ch)) && (!found)) {
matchChar = matchString.charAt(index);
if (this.charsAreEqual(ch, matchChar)) {
index++;
if (index >= matchString.length()) { // whole matchString checked ?
found = true;
} else {
ch = examiner.nextChar();
}
} else {
if (index == 0) {
ch = examiner.nextChar();
} else {
index = 0;
}
}
}
return found;
}
// skipAfter()
// -------------------------------------------------------------------------
protected String upToEnd(StringExaminer iterator) {
return iterator.upToEnd();
}
// upToEnd()
// -------------------------------------------------------------------------
protected boolean matchReverse(String pattern, StringExaminer probeIterator) {
String newPattern;
String newProbe;
StringPattern newMatcher;
newPattern = MULTI_WILDCARD + pattern;
newProbe = this.upToEnd(probeIterator);
newPattern = this.strUtil().reverse(newPattern);
newProbe = this.strUtil().reverse(newProbe);
newMatcher = new StringPattern(newPattern, this.getIgnoreCase());
if (this.hasDigitWildcard()) {
newMatcher.setDigitWildcardChar(this.digitWildcardChar());
}
return newMatcher.matches(newProbe);
}
// matchReverse()
// -------------------------------------------------------------------------
protected boolean charsAreEqual(char probeChar, char patternChar) {
if (this.hasDigitWildcard()) {
if (patternChar == this.digitWildcardChar()) {
return Character.isDigit(probeChar);
}
}
if (this.getIgnoreCase()) {
return (Character.toUpperCase(probeChar) == Character.toUpperCase(patternChar));
} else {
return (probeChar == patternChar);
}
}
// charsAreEqual()
// -------------------------------------------------------------------------
protected boolean endReached(char character) {
return (character == StringExaminer.END_REACHED);
}
// endReached()
// -------------------------------------------------------------------------
protected boolean endNotReached(char character) {
return (!endReached(character));
}
// endNotReached()
// -------------------------------------------------------------------------
protected char getPatternChar(StringExaminer patternIterator, char probeCh) {
char patternCh;
patternCh = patternIterator.nextChar();
return ((patternCh == SINGLECHAR_WILDCARD) ? probeCh : patternCh);
}
// getPatternChar()
// -------------------------------------------------------------------------
protected StringExaminer newExaminer(String str) {
return new StringExaminer(str, this.getIgnoreCase());
}
// newExaminer()
// -------------------------------------------------------------------------
protected StringUtil strUtil() {
return StringUtil.current();
}
// strUtil()
// -------------------------------------------------------------------------
}
// class StringPattern
| petergeneric/j2ssh | src/main/java/com/sshtools/daemon/util/StringPattern.java | Java | gpl-2.0 | 18,028 |
/*
* Copyright (c) 2017, 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.
*/
module mymod {
requires javafx.fxml;
requires javafx.graphics;
exports myapp6;
// myapp6.pkg1 is deliberately not listed
exports myapp6.pkg2;
exports myapp6.pkg3 to javafx.fxml;
opens myapp6.pkg4;
opens myapp6.pkg5 to javafx.fxml;
}
| teamfx/openjfx-10-dev-rt | tests/system/src/testapp6/java/mymod/module-info.java | Java | gpl-2.0 | 1,475 |
/*
* Copyright (c) 2009, 2012, 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.
*
* 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 test.com.sun.max.vm.jtrun;
import com.sun.max.config.*;
import com.sun.max.vm.*;
import com.sun.max.vm.run.*;
/**
*/
public class Package extends BootImagePackage {
public Package() {
super();
}
@Override
public boolean isPartOfMaxineVM(VMConfiguration vmConfiguration) {
return vmConfiguration.schemeImplClassIsSubClass(RunScheme.class, JTAbstractRunScheme.class);
}
}
| arodchen/MaxSim | maxine/com.oracle.max.vm.tests/src/test/com/sun/max/vm/jtrun/Package.java | Java | gpl-2.0 | 1,475 |
public class wideStudent
{
public static void a(){int i = 0;}
public static void b(){int i = 1;}
public static void c(){int i = 2;}
public static void d(){int i = 3;}
public static void e(){int i = 4;}
public static void f(){int i = 5;}
public static void g(){int i = 6;}
public static void h(){int i = 7;}
public static void i(){int i = 8;}
}
| DATX02-17-26/DATX02-17-26 | bench/Programs/wideStudent.java | Java | gpl-2.0 | 363 |
package com.darkorbit.objects;
public class Clan {
private int clanID;
private String tagName;
public Clan(int clanID, String tagName) {
this.clanID = clanID;
this.tagName = tagName;
}
/* get methods */
public int getClanID() { return clanID; }
public String getTagName() { return tagName; }
/* @end */
}
| krypticdestro/DarkOrbitProject | src/com/darkorbit/objects/Clan.java | Java | gpl-2.0 | 330 |
/*
* Copyright (c) 1997, 2010, 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 java.util;
import org.checkerframework.checker.lock.qual.*;
/**
* An ordered collection (also known as a <i>sequence</i>). The user of this
* interface has precise control over where in the list each element is
* inserted. The user can access elements by their integer index (position in
* the list), and search for elements in the list.<p>
*
* Unlike sets, lists typically allow duplicate elements. More formally,
* lists typically allow pairs of elements <tt>e1</tt> and <tt>e2</tt>
* such that <tt>e1.equals(e2)</tt>, and they typically allow multiple
* null elements if they allow null elements at all. It is not inconceivable
* that someone might wish to implement a list that prohibits duplicates, by
* throwing runtime exceptions when the user attempts to insert them, but we
* expect this usage to be rare.<p>
*
* The <tt>List</tt> interface places additional stipulations, beyond those
* specified in the <tt>Collection</tt> interface, on the contracts of the
* <tt>iterator</tt>, <tt>add</tt>, <tt>remove</tt>, <tt>equals</tt>, and
* <tt>hashCode</tt> methods. Declarations for other inherited methods are
* also included here for convenience.<p>
*
* The <tt>List</tt> interface provides four methods for positional (indexed)
* access to list elements. Lists (like Java arrays) are zero based. Note
* that these operations may execute in time proportional to the index value
* for some implementations (the <tt>LinkedList</tt> class, for
* example). Thus, iterating over the elements in a list is typically
* preferable to indexing through it if the caller does not know the
* implementation.<p>
*
* The <tt>List</tt> interface provides a special iterator, called a
* <tt>ListIterator</tt>, that allows element insertion and replacement, and
* bidirectional access in addition to the normal operations that the
* <tt>Iterator</tt> interface provides. A method is provided to obtain a
* list iterator that starts at a specified position in the list.<p>
*
* The <tt>List</tt> interface provides two methods to search for a specified
* object. From a performance standpoint, these methods should be used with
* caution. In many implementations they will perform costly linear
* searches.<p>
*
* The <tt>List</tt> interface provides two methods to efficiently insert and
* remove multiple elements at an arbitrary point in the list.<p>
*
* Note: While it is permissible for lists to contain themselves as elements,
* extreme caution is advised: the <tt>equals</tt> and <tt>hashCode</tt>
* methods are no longer well defined on such a list.
*
* <p>Some list implementations have restrictions on the elements that
* they may contain. For example, some implementations prohibit null elements,
* and some have restrictions on the types of their elements. Attempting to
* add an ineligible element throws an unchecked exception, typically
* <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
* to query the presence of an ineligible element may throw an exception,
* or it may simply return false; some implementations will exhibit the former
* behavior and some will exhibit the latter. More generally, attempting an
* operation on an ineligible element whose completion would not result in
* the insertion of an ineligible element into the list may throw an
* exception or it may succeed, at the option of the implementation.
* Such exceptions are marked as "optional" in the specification for this
* interface.
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @param <E> the type of elements in this list
*
* @author Josh Bloch
* @author Neal Gafter
* @see Collection
* @see Set
* @see ArrayList
* @see LinkedList
* @see Vector
* @see Arrays#asList(Object[])
* @see Collections#nCopies(int, Object)
* @see Collections#EMPTY_LIST
* @see AbstractList
* @see AbstractSequentialList
* @since 1.2
*/
// Subclasses of this interface/class may opt to prohibit null elements
public interface List<E extends Object> extends Collection<E> {
// Query Operations
/**
* Returns the number of elements in this list. If this list contains
* more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this list
*/
int size(@GuardSatisfied List<E> this);
/**
* Returns <tt>true</tt> if this list contains no elements.
*
* @return <tt>true</tt> if this list contains no elements
*/
boolean isEmpty(@GuardSatisfied List<E> this);
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
*/
boolean contains(@GuardSatisfied List<E> this, Object o);
/**
* Returns an iterator over the elements in this list in proper sequence.
*
* @return an iterator over the elements in this list in proper sequence
*/
Iterator<E> iterator();
/**
* Returns an array containing all of the elements in this list in proper
* sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in proper
* sequence
* @see Arrays#asList(Object[])
*/
Object[] toArray();
/**
* Returns an array containing all of the elements in this list in
* proper sequence (from first to last element); the runtime type of
* the returned array is that of the specified array. If the list fits
* in the specified array, it is returned therein. Otherwise, a new
* array is allocated with the runtime type of the specified array and
* the size of this list.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to <tt>null</tt>.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any null elements.)
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose <tt>x</tt> is a list known to contain only strings.
* The following code can be used to dump the list into a newly
* allocated array of <tt>String</tt>:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>.
*
* @param a the array into which the elements of this list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of this list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
<T extends Object> T [] toArray(T [] a);
// Modification Operations
/**
* Appends the specified element to the end of this list (optional
* operation).
*
* <p>Lists that support this operation may place limitations on what
* elements may be added to this list. In particular, some
* lists will refuse to add null elements, and others will impose
* restrictions on the type of elements that may be added. List
* classes should clearly specify in their documentation any restrictions
* on what elements may be added.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws UnsupportedOperationException if the <tt>add</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this list
*/
@ReleasesNoLocks
boolean add(@GuardSatisfied List<E> this, E e);
/**
* Removes the first occurrence of the specified element from this list,
* if it is present (optional operation). If this list does not contain
* the element, it is unchanged. More formally, removes the element with
* the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list changed
* as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this list
*/
boolean remove(Object o);
// Bulk Modification Operations
/**
* Returns <tt>true</tt> if this list contains all of the elements of the
* specified collection.
*
* @param c collection to be checked for containment in this list
* @return <tt>true</tt> if this list contains all of the elements of the
* specified collection
* @throws ClassCastException if the types of one or more elements
* in the specified collection are incompatible with this
* list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified collection contains one
* or more null elements and this list does not permit null
* elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #contains(Object)
*/
boolean containsAll(@GuardSatisfied List<E> this, Collection<?> c);
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator (optional operation). The behavior of this
* operation is undefined if the specified collection is modified while
* the operation is in progress. (Note that this will occur if the
* specified collection is this list, and it's nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>addAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of the specified
* collection prevents it from being added to this list
* @throws NullPointerException if the specified collection contains one
* or more null elements and this list does not permit null
* elements, or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this list
* @see #add(Object)
*/
boolean addAll(Collection<? extends E> c);
/**
* Inserts all of the elements in the specified collection into this
* list at the specified position (optional operation). Shifts the
* element currently at that position (if any) and any subsequent
* elements to the right (increases their indices). The new elements
* will appear in this list in the order that they are returned by the
* specified collection's iterator. The behavior of this operation is
* undefined if the specified collection is modified while the
* operation is in progress. (Note that this will occur if the specified
* collection is this list, and it's nonempty.)
*
* @param index index at which to insert the first element from the
* specified collection
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>addAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of the specified
* collection prevents it from being added to this list
* @throws NullPointerException if the specified collection contains one
* or more null elements and this list does not permit null
* elements, or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index > size()</tt>)
*/
boolean addAll(int index, Collection<? extends E> c);
/**
* Removes from this list all of its elements that are contained in the
* specified collection (optional operation).
*
* @param c collection containing elements to be removed from this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean removeAll(Collection<?> c);
/**
* Retains only the elements in this list that are contained in the
* specified collection (optional operation). In other words, removes
* from this list all of its elements that are not contained in the
* specified collection.
*
* @param c collection containing elements to be retained in this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean retainAll(Collection<?> c);
/**
* Removes all of the elements from this list (optional operation).
* The list will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this list
*/
void clear();
// Comparison and hashing
/**
* Compares the specified object with this list for equality. Returns
* <tt>true</tt> if and only if the specified object is also a list, both
* lists have the same size, and all corresponding pairs of elements in
* the two lists are <i>equal</i>. (Two elements <tt>e1</tt> and
* <tt>e2</tt> are <i>equal</i> if <tt>(e1==null ? e2==null :
* e1.equals(e2))</tt>.) In other words, two lists are defined to be
* equal if they contain the same elements in the same order. This
* definition ensures that the equals method works properly across
* different implementations of the <tt>List</tt> interface.
*
* @param o the object to be compared for equality with this list
* @return <tt>true</tt> if the specified object is equal to this list
*/
boolean equals(@GuardSatisfied List<E> this, Object o);
/**
* Returns the hash code value for this list. The hash code of a list
* is defined to be the result of the following calculation:
* <pre>
* int hashCode = 1;
* for (E e : list)
* hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
* </pre>
* This ensures that <tt>list1.equals(list2)</tt> implies that
* <tt>list1.hashCode()==list2.hashCode()</tt> for any two lists,
* <tt>list1</tt> and <tt>list2</tt>, as required by the general
* contract of {@link Object#hashCode}.
*
* @return the hash code value for this list
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode(@GuardSatisfied List<E> this);
// Positional Access Operations
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index >= size()</tt>)
*/
E get(@GuardSatisfied List<E> this, int index);
/**
* Replaces the element at the specified position in this list with the
* specified element (optional operation).
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws UnsupportedOperationException if the <tt>set</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list
* @throws NullPointerException if the specified element is null and
* this list does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index >= size()</tt>)
*/
E set(int index, E element);
/**
* Inserts the specified element at the specified position in this list
* (optional operation). Shifts the element currently at that position
* (if any) and any subsequent elements to the right (adds one to their
* indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws UnsupportedOperationException if the <tt>add</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list
* @throws NullPointerException if the specified element is null and
* this list does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index > size()</tt>)
*/
@ReleasesNoLocks
void add(@GuardSatisfied List<E> this, int index, E element);
/**
* Removes the element at the specified position in this list (optional
* operation). Shifts any subsequent elements to the left (subtracts one
* from their indices). Returns the element that was removed from the
* list.
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index >= size()</tt>)
*/
@ReleasesNoLocks
E remove(@GuardSatisfied List<E> this, int index);
// Search Operations
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
*/
int indexOf(@GuardSatisfied List<E> this, Object o);
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
*/
int lastIndexOf(@GuardSatisfied List<E> this, Object o);
// List Iterators
/**
* Returns a list iterator over the elements in this list (in proper
* sequence).
*
* @return a list iterator over the elements in this list (in proper
* sequence)
*/
ListIterator<E> listIterator();
/**
* Returns a list iterator over the elements in this list (in proper
* sequence), starting at the specified position in the list.
* The specified index indicates the first element that would be
* returned by an initial call to {@link ListIterator#next next}.
* An initial call to {@link ListIterator#previous previous} would
* return the element with the specified index minus one.
*
* @param index index of the first element to be returned from the
* list iterator (by a call to {@link ListIterator#next next})
* @return a list iterator over the elements in this list (in proper
* sequence), starting at the specified position in the list
* @throws IndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index > size()})
*/
ListIterator<E> listIterator(int index);
// View
/**
* Returns a view of the portion of this list between the specified
* <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. (If
* <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is
* empty.) The returned list is backed by this list, so non-structural
* changes in the returned list are reflected in this list, and vice-versa.
* The returned list supports all of the optional list operations supported
* by this list.<p>
*
* This method eliminates the need for explicit range operations (of
* the sort that commonly exist for arrays). Any operation that expects
* a list can be used as a range operation by passing a subList view
* instead of a whole list. For example, the following idiom
* removes a range of elements from a list:
* <pre>
* list.subList(from, to).clear();
* </pre>
* Similar idioms may be constructed for <tt>indexOf</tt> and
* <tt>lastIndexOf</tt>, and all of the algorithms in the
* <tt>Collections</tt> class can be applied to a subList.<p>
*
* The semantics of the list returned by this method become undefined if
* the backing list (i.e., this list) is <i>structurally modified</i> in
* any way other than via the returned list. (Structural modifications are
* those that change the size of this list, or otherwise perturb it in such
* a fashion that iterations in progress may yield incorrect results.)
*
* @param fromIndex low endpoint (inclusive) of the subList
* @param toIndex high endpoint (exclusive) of the subList
* @return a view of the specified range within this list
* @throws IndexOutOfBoundsException for an illegal endpoint index value
* (<tt>fromIndex < 0 || toIndex > size ||
* fromIndex > toIndex</tt>)
*/
List<E> subList(@GuardSatisfied List<E> this, int fromIndex, int toIndex);
}
| CharlesZ-Chen/checker-framework | checker/jdk/lock/src/java/util/List.java | Java | gpl-2.0 | 28,797 |
/**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest02300")
public class BenchmarkTest02300 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
java.util.Map<String,String[]> map = request.getParameterMap();
String param = "";
if (!map.isEmpty()) {
String[] values = map.get("vector");
if (values != null) param = values[0];
}
String bar = doSomething(param);
float rand = new java.util.Random().nextFloat();
String rememberMeKey = Float.toString(rand).substring(2); // Trim off the 0. at the front.
String user = "Floyd";
String fullClassName = this.getClass().getName();
String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
user+= testCaseNumber;
String cookieName = "rememberMe" + testCaseNumber;
boolean foundUser = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
javax.servlet.http.Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
foundUser = true;
}
}
}
if (foundUser) {
response.getWriter().println("Welcome back: " + user + "<br/>");
} else {
javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
rememberMe.setSecure(true);
request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
+ " whose value is: " + rememberMe.getValue() + "<br/>");
}
response.getWriter().println("Weak Randomness Test java.util.Random.nextFloat() executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple if statement that assigns param to bar on true condition
int num = 196;
if ( (500/42) + num > 200 )
bar = param;
else bar = "This should never happen";
return bar;
}
}
| andresriancho/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest02300.java | Java | gpl-2.0 | 3,529 |
package org.nxtgenutils.cmd;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.commandline.Gatherer;
import org.broadinstitute.sting.gatk.walkers.bqsr.BQSRGatherer;
import org.nxtgenutils.NxtGenUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This file is part of NxtGenUtils.
*
* NxtGenUtils is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NxtGenUtils is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NxtGenUtils. If not, see <http://www.gnu.org/licenses/>.
*
* Created with IntelliJ IDEA.
* User: mmuelle1
* Date: 3/2/13
* Time: 3:47 PM
*/
/**
* @author Michael Mueller
*/
public class GatherGatkBqsrReports extends AbstractCommand {
/**
* the log4j logger
*/
private static Logger logger = Logger.getLogger(GatherGatkBqsrReports.class);
public GatherGatkBqsrReports() {
usage = "Arguments for GatherGatkBqsrReports\n" +
"\n" +
" -i --reportInput <path_to_basecall_recalibration_report>\n" +
" (argument can be specified multiple times for multiple input files)\n" +
" -o --mergedReportOutput <path_to_merged_report_output>\n";
}
@Override
public void run(String[] args) {
List<File> inputReports = new ArrayList<File>();
File outputReport = null;
try {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("--reportInput") || args[i].equals("-i")) {
String filename = args[i + 1];
inputReports.add(new File(filename));
}
if (args[i].equals("--mergedReportOutput") || args[i].equals("-o")) {
String filename = args[i + 1];
outputReport = new File(filename);
}
}
} catch (Exception e) {
System.out.println(NxtGenUtils.usage);
System.out.println(usage);
System.out.println(Arrays.toString(args));
logger.error("Exception while reading command line arguments: " + e.getMessage());
System.exit(1);
}
if (inputReports.size() == 0) {
System.out.println(NxtGenUtils.usage);
System.out.println(usage);
logger.error("Required input argument --reportInput missing.");
System.exit(1);
}
if (outputReport == null) {
System.out.println(NxtGenUtils.usage);
System.out.println(usage);
logger.error("Required input argument --mergedReportOutput missing.");
System.exit(1);
}
logger.info("Merging GATK reclibration reports...");
logger.info("Report input file(s) : " + inputReports.toString());
logger.info("Report output file: " + outputReport);
new BQSRGatherer().gather(inputReports, outputReport);
logger.info("done");
}
public static void main(String[] args) {
new GatherGatkBqsrReports().run(args);
}
}
| mmueller76/nxtgen-utils | src/main/java/org/nxtgenutils/io/GatherGatkBqsrReports.java | Java | gpl-2.0 | 3,552 |
/**
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.action.configuration.ssm;
import com.redhat.rhn.common.util.DatePicker;
import com.redhat.rhn.domain.user.User;
import com.redhat.rhn.frontend.struts.RequestContext;
import com.redhat.rhn.frontend.struts.RhnListDispatchAction;
import com.redhat.rhn.manager.configuration.ConfigurationManager;
import com.redhat.rhn.manager.rhnset.RhnSetDecl;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* EnableSubmitAction
* Does all the real work for enabling configuration.
* @version $Rev$
*/
public class EnableSubmitAction extends RhnListDispatchAction {
/**
* {@inheritDoc}
*/
protected void processMethodKeys(Map map) {
map.put("targetsystems.jsp.enable", "enable");
}
/**
* {@inheritDoc}
*/
protected void processParamMap(ActionForm form, HttpServletRequest request,
Map params) {
getStrutsDelegate().rememberDatePicker(params, (DynaActionForm)form, "date",
DatePicker.YEAR_RANGE_POSITIVE);
}
/**
* Enables the selected set of systems for configuration management
* @param mapping struts ActionMapping
* @param formIn struts ActionForm
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return forward to the summary page.
*/
public ActionForward enable(ActionMapping mapping,
ActionForm formIn,
HttpServletRequest request,
HttpServletResponse response) {
User user = new RequestContext(request).getCurrentUser();
RhnSetDecl set = RhnSetDecl.SYSTEMS;
//get the earliest schedule for package install actions.
DynaActionForm form = (DynaActionForm) formIn;
Date earliest = getStrutsDelegate().readDatePicker(form, "date",
DatePicker.YEAR_RANGE_POSITIVE);
ConfigurationManager.getInstance().enableSystems(set, user, earliest);
return mapping.findForward("summary");
}
}
| dmacvicar/spacewalk | java/code/src/com/redhat/rhn/frontend/action/configuration/ssm/EnableSubmitAction.java | Java | gpl-2.0 | 2,888 |
package com.numhero.client.widget.calendar;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.*;
import com.numhero.client.Application;
import java.util.Date;
public class CalendarWidget extends Composite implements ClickListener, SourcesChangeEvents {
private class NavBar extends Composite implements ClickListener {
public final DockPanel bar = new DockPanel();
public final Button prevMonth = new Button("<", this);
public final Button prevYear = new Button("<<", this);
public final Button nextYear = new Button(">>", this);
public final Button nextMonth = new Button(">", this);
public final HTML title = new HTML();
private final CalendarWidget calendar;
public NavBar(CalendarWidget calendar) {
this.calendar = calendar;
setWidget(bar);
bar.setStyleName("navbar");
title.setStyleName("header");
HorizontalPanel prevButtons = new HorizontalPanel();
prevButtons.add(prevMonth);
prevButtons.add(prevYear);
HorizontalPanel nextButtons = new HorizontalPanel();
nextButtons.add(nextYear);
nextButtons.add(nextMonth);
bar.add(prevButtons, DockPanel.WEST);
bar.setCellHorizontalAlignment(prevButtons, DockPanel.ALIGN_LEFT);
bar.add(nextButtons, DockPanel.EAST);
bar.setCellHorizontalAlignment(nextButtons, DockPanel.ALIGN_RIGHT);
bar.add(title, DockPanel.CENTER);
bar.setVerticalAlignment(DockPanel.ALIGN_MIDDLE);
bar.setCellHorizontalAlignment(title, HasAlignment.ALIGN_CENTER);
bar.setCellVerticalAlignment(title, HasAlignment.ALIGN_MIDDLE);
bar.setCellWidth(title, "100%");
}
public void onClick(Widget sender) {
if (sender == prevMonth) {
calendar.prevMonth();
} else if (sender == prevYear) {
calendar.prevYear();
} else if (sender == nextYear) {
calendar.nextYear();
} else if (sender == nextMonth) {
calendar.nextMonth();
}
}
}
private static class CellHTML extends HTML {
private int day;
public CellHTML(String text, int day) {
super(text);
this.day = day;
}
public int getDay() {
return day;
}
}
private final NavBar navbar = new NavBar(this);
private final DockPanel outer = new DockPanel();
private final Grid grid = new Grid(6, 7) {
public boolean clearCell(int row, int column) {
boolean retValue = super.clearCell(row, column);
Element td = getCellFormatter().getElement(row, column);
DOM.setInnerHTML(td, "");
return retValue;
}
};
private Date date = new Date();
private ChangeListenerCollection changeListeners;
String[] days = new String[]{
Application.getConstants().sunday(),
Application.getConstants().monday(),
Application.getConstants().tuesday(),
Application.getConstants().wednesday(),
Application.getConstants().thursday(),
Application.getConstants().friday(),
Application.getConstants().saturday()};
private String[] months = new String[]{
Application.getConstants().january(),
Application.getConstants().february(),
Application.getConstants().march(),
Application.getConstants().april(),
Application.getConstants().may(),
Application.getConstants().june(),
Application.getConstants().july(),
Application.getConstants().august(),
Application.getConstants().september(),
Application.getConstants().october(),
Application.getConstants().november(),
Application.getConstants().december()};
public CalendarWidget() {
setWidget(outer);
grid.setStyleName("table");
grid.setCellSpacing(0);
outer.add(navbar, DockPanel.NORTH);
outer.add(grid, DockPanel.CENTER);
drawCalendar();
setStyleName("CalendarWidget");
}
private void drawCalendar() {
int year = getYear();
int month = getMonth();
int day = getDay();
setHeaderText(year, month);
grid.getRowFormatter().setStyleName(0, "weekheader");
for (int i = 0; i < days.length; i++) {
grid.getCellFormatter().setStyleName(0, i, "days");
grid.setText(0, i, days[i].substring(0, 3));
}
Date now = new Date();
int sameDay = now.getDate();
int today = (now.getMonth() == month && now.getYear() + 1900 == year) ? sameDay : 0;
int firstDay = new Date(year - 1900, month, 1).getDay();
int numOfDays = getDaysInMonth(year, month);
int j = 0;
for (int i = 1; i < 6; i++) {
for (int k = 0; k < 7; k++, j++) {
int displayNum = (j - firstDay + 1);
if (j < firstDay || displayNum > numOfDays) {
grid.getCellFormatter().setStyleName(i, k, "empty");
grid.setHTML(i, k, " ");
} else {
HTML html = new CellHTML(
"<span>" + String.valueOf(displayNum) + "</span>",
displayNum);
html.addClickListener(this);
grid.getCellFormatter().setStyleName(i, k, "cell");
if (displayNum == today) {
grid.getCellFormatter().addStyleName(i, k, "today");
} else if (displayNum == sameDay) {
grid.getCellFormatter().addStyleName(i, k, "day");
}
grid.setWidget(i, k, html);
}
}
}
}
protected void setHeaderText(int year, int month) {
navbar.title.setText(months[month] + ", " + year);
}
private int getDaysInMonth(int year, int month) {
switch (month) {
case 1:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return 29; // leap year
else
return 28;
case 3:
return 30;
case 5:
return 30;
case 8:
return 30;
case 10:
return 30;
default:
return 31;
}
}
public void prevMonth() {
int month = getMonth() - 1;
if (month < 0) {
setDate(getYear() - 1, 11, getDay());
} else {
setMonth(month);
}
drawCalendar();
}
public void nextMonth() {
int month = getMonth() + 1;
if (month > 11) {
setDate(getYear() + 1, 0, getDay());
} else {
setMonth(month);
}
drawCalendar();
}
public void prevYear() {
setYear(getYear() - 1);
drawCalendar();
}
public void nextYear() {
setYear(getYear() + 1);
drawCalendar();
}
private void setDate(int year, int month, int day) {
date = new Date(year - 1900, month, day);
}
private void setYear(int year) {
date.setYear(year - 1900);
}
private void setMonth(int month) {
date.setMonth(month);
}
public int getYear() {
return 1900 + date.getYear();
}
public int getMonth() {
return date.getMonth();
}
public int getDay() {
return date.getDate();
}
public Date getDate() {
return date;
}
public void onClick(Widget sender) {
CellHTML cell = (CellHTML) sender;
setDate(getYear(), getMonth(), cell.getDay());
drawCalendar();
if (changeListeners != null) {
changeListeners.fireChange(this);
}
}
public void addChangeListener(ChangeListener listener) {
if (changeListeners == null)
changeListeners = new ChangeListenerCollection();
changeListeners.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
if (changeListeners != null)
changeListeners.remove(listener);
}
} | midaboghetich/netnumero | src/com/numhero/client/widget/calendar/CalendarWidget.java | Java | gpl-2.0 | 8,515 |
/**
* Comment
*/
public class TestClass {
public static String test1(String blah) {
return "blah";
}
public static void main(String[] argv) {
test1();
try {
inner = new InnerClass() {
public void innerTest1(String blah) {
System.out.println("blah");
}
}
catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
private final static void usage() {
System.out.println("blah");
}
}
| robmcmullen/peppy | tests/samples/javafunctions.java | Java | gpl-2.0 | 512 |
/************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* Use is subject to license terms.
*
* 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. You can also
* obtain a copy of the License at http://odftoolkit.org/docs/license.txt
*
* 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.
*
************************************************************************/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.attribute.draw;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.pkg.OdfAttribute;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
/**
* DOM implementation of OpenDocument attribute {@odf.attribute draw:end-line-spacing-horizontal}.
*
*/
public class DrawEndLineSpacingHorizontalAttribute extends OdfAttribute {
public static final OdfName ATTRIBUTE_NAME = OdfName.newName(OdfDocumentNamespace.DRAW, "end-line-spacing-horizontal");
/**
* Create the instance of OpenDocument attribute {@odf.attribute draw:end-line-spacing-horizontal}.
*
* @param ownerDocument The type is <code>OdfFileDom</code>
*/
public DrawEndLineSpacingHorizontalAttribute(OdfFileDom ownerDocument) {
super(ownerDocument, ATTRIBUTE_NAME);
}
/**
* Returns the attribute name.
*
* @return the <code>OdfName</code> for {@odf.attribute draw:end-line-spacing-horizontal}.
*/
@Override
public OdfName getOdfName() {
return ATTRIBUTE_NAME;
}
/**
* @return Returns the name of this attribute.
*/
@Override
public String getName() {
return ATTRIBUTE_NAME.getLocalName();
}
/**
* Returns the default value of {@odf.attribute draw:end-line-spacing-horizontal}.
*
* @return the default value as <code>String</code> dependent of its element name
* return <code>null</code> if the default value does not exist
*/
@Override
public String getDefault() {
return null;
}
/**
* Default value indicator. As the attribute default value is dependent from its element, the attribute has only a default, when a parent element exists.
*
* @return <code>true</code> if {@odf.attribute draw:end-line-spacing-horizontal} has an element parent
* otherwise return <code>false</code> as undefined.
*/
@Override
public boolean hasDefault() {
return false;
}
/**
* @return Returns whether this attribute is known to be of type ID (i.e. xml:id ?)
*/
@Override
public boolean isId() {
return false;
}
}
| jbjonesjr/geoproponis | external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/attribute/draw/DrawEndLineSpacingHorizontalAttribute.java | Java | gpl-2.0 | 3,110 |
/*
* 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.
*/
/**
* @author Alexey A. Ivanov
*/
package javax.swing.text.html;
import javax.swing.BasicSwingTestCase;
import javax.swing.text.html.HTML.Tag;
import junit.framework.TestCase;
public class HTML_TagTest extends TestCase {
private Tag tag;
public void testTag() {
tag = new Tag();
assertNull(tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testTagString() {
final String tagName = "newTag";
tag = new Tag(tagName);
assertEquals("newTag", tag.toString());
assertSame(tagName, tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testTagStringboolbool() {
tag = new Tag("tag1", true, false);
assertSame("tag1", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
tag = new Tag("tag2", false, true);
assertSame("tag2", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testIsPreformatted() throws Exception {
tag = new Tag("pre", false, false);
assertNotSame(Tag.PRE, tag);
assertEquals(Tag.PRE.toString(), tag.toString());
assertFalse("isPre", tag.isPreformatted());
tag = new Tag("textarea", false, false);
assertNotSame(Tag.TEXTAREA, tag);
assertEquals(Tag.TEXTAREA.toString(), tag.toString());
assertFalse("isPre", tag.isPreformatted());
tag = new Tag("verb", true, false) {
public boolean isPreformatted() {
return true;
}
};
assertEquals("verb", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertTrue("isPre", tag.isPreformatted());
}
public void testA() {
tag = HTML.Tag.A;
assertEquals("a", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testADDRESS() {
tag = HTML.Tag.ADDRESS;
assertEquals("address", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testAPPLET() {
tag = HTML.Tag.APPLET;
assertEquals("applet", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testAREA() {
tag = HTML.Tag.AREA;
assertEquals("area", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testB() {
tag = HTML.Tag.B;
assertEquals("b", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testBASE() {
tag = HTML.Tag.BASE;
assertEquals("base", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testBASEFONT() {
tag = HTML.Tag.BASEFONT;
assertEquals("basefont", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testBIG() {
tag = HTML.Tag.BIG;
assertEquals("big", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testBLOCKQUOTE() {
tag = HTML.Tag.BLOCKQUOTE;
assertEquals("blockquote", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testBODY() {
tag = HTML.Tag.BODY;
assertEquals("body", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testBR() {
tag = HTML.Tag.BR;
assertEquals("br", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testCAPTION() {
tag = HTML.Tag.CAPTION;
assertEquals("caption", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testCENTER() {
tag = HTML.Tag.CENTER;
assertEquals("center", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testCITE() {
tag = HTML.Tag.CITE;
assertEquals("cite", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testCODE() {
tag = HTML.Tag.CODE;
assertEquals("code", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testCOMMENT() {
tag = HTML.Tag.COMMENT;
assertEquals("comment", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testCONTENT() {
tag = HTML.Tag.CONTENT;
assertEquals("content", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testDD() {
tag = HTML.Tag.DD;
assertEquals("dd", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testDFN() {
tag = HTML.Tag.DFN;
assertEquals("dfn", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testDIR() {
tag = HTML.Tag.DIR;
assertEquals("dir", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testDIV() {
tag = HTML.Tag.DIV;
assertEquals("div", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testDL() {
tag = HTML.Tag.DL;
assertEquals("dl", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testDT() {
tag = HTML.Tag.DT;
assertEquals("dt", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testEM() {
tag = HTML.Tag.EM;
assertEquals("em", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testFONT() {
tag = HTML.Tag.FONT;
assertEquals("font", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testFORM() {
tag = HTML.Tag.FORM;
assertEquals("form", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testFRAME() {
tag = HTML.Tag.FRAME;
assertEquals("frame", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testFRAMESET() {
tag = HTML.Tag.FRAMESET;
assertEquals("frameset", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testH1() {
tag = HTML.Tag.H1;
assertEquals("h1", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testH2() {
tag = HTML.Tag.H2;
assertEquals("h2", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testH3() {
tag = HTML.Tag.H3;
assertEquals("h3", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testH4() {
tag = HTML.Tag.H4;
assertEquals("h4", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testH5() {
tag = HTML.Tag.H5;
assertEquals("h5", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testH6() {
tag = HTML.Tag.H6;
assertEquals("h6", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testHEAD() {
tag = HTML.Tag.HEAD;
assertEquals("head", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testHR() {
tag = HTML.Tag.HR;
assertEquals("hr", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testHTML() {
tag = HTML.Tag.HTML;
assertEquals("html", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testI() {
tag = HTML.Tag.I;
assertEquals("i", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testIMG() {
tag = HTML.Tag.IMG;
assertEquals("img", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testIMPLIED() {
tag = HTML.Tag.IMPLIED;
assertEquals("p-implied", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testINPUT() {
tag = HTML.Tag.INPUT;
assertEquals("input", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testISINDEX() {
tag = HTML.Tag.ISINDEX;
assertEquals("isindex", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testKBD() {
tag = HTML.Tag.KBD;
assertEquals("kbd", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testLI() {
tag = HTML.Tag.LI;
assertEquals("li", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testLINK() {
tag = HTML.Tag.LINK;
assertEquals("link", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testMAP() {
tag = HTML.Tag.MAP;
assertEquals("map", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testMENU() {
tag = HTML.Tag.MENU;
assertEquals("menu", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testMETA() {
tag = HTML.Tag.META;
assertEquals("meta", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testNOFRAMES() {
tag = HTML.Tag.NOFRAMES;
assertEquals("noframes", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testOBJECT() {
tag = HTML.Tag.OBJECT;
assertEquals("object", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testOL() {
tag = HTML.Tag.OL;
assertEquals("ol", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testOPTION() {
tag = HTML.Tag.OPTION;
assertEquals("option", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testP() {
tag = HTML.Tag.P;
assertEquals("p", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testPARAM() {
tag = HTML.Tag.PARAM;
assertEquals("param", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testPRE() {
tag = HTML.Tag.PRE;
assertEquals("pre", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertTrue("isPre", tag.isPreformatted());
}
public void testS() {
tag = HTML.Tag.S;
assertEquals("s", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSAMP() {
tag = HTML.Tag.SAMP;
assertEquals("samp", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSCRIPT() {
tag = HTML.Tag.SCRIPT;
assertEquals("script", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSELECT() {
tag = HTML.Tag.SELECT;
assertEquals("select", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSMALL() {
tag = HTML.Tag.SMALL;
assertEquals("small", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSPAN() {
tag = HTML.Tag.SPAN;
assertEquals("span", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSTRIKE() {
tag = HTML.Tag.STRIKE;
assertEquals("strike", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSTRONG() {
tag = HTML.Tag.STRONG;
assertEquals("strong", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSTYLE() {
tag = HTML.Tag.STYLE;
assertEquals("style", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSUB() {
tag = HTML.Tag.SUB;
assertEquals("sub", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testSUP() {
tag = HTML.Tag.SUP;
assertEquals("sup", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testTABLE() {
tag = HTML.Tag.TABLE;
assertEquals("table", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testTD() {
tag = HTML.Tag.TD;
assertEquals("td", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testTEXTAREA() {
tag = HTML.Tag.TEXTAREA;
assertEquals("textarea", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertTrue("isPre", tag.isPreformatted());
}
public void testTH() {
tag = HTML.Tag.TH;
assertEquals("th", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testTITLE() {
tag = HTML.Tag.TITLE;
assertEquals("title", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testTR() {
tag = HTML.Tag.TR;
assertEquals("tr", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testTT() {
tag = HTML.Tag.TT;
assertEquals("tt", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testU() {
tag = HTML.Tag.U;
assertEquals("u", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testUL() {
tag = HTML.Tag.UL;
assertEquals("ul", tag.toString());
assertTrue("breaks Flow", tag.breaksFlow());
assertTrue("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
public void testVAR() {
tag = HTML.Tag.VAR;
assertEquals("var", tag.toString());
assertFalse("breaks Flow", tag.breaksFlow());
assertFalse("isBlock", tag.isBlock());
assertFalse("isPre", tag.isPreformatted());
}
// Tags for HTML 4.0
public void testABBR() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.ABBR;
assertEquals("abbr", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testACRONYM() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.ACRONYM;
assertEquals("acronym", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testBDO() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.BDO;
assertEquals("bdo", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testBUTTON() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.BUTTON;
assertEquals("button", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testCOL() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.COL;
assertEquals("col", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testCOLGROUP() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.COLGROUP;
assertEquals("colgroup", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testDEL() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.DEL;
assertEquals("del", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testFIELDSET() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.FIELDSET;
assertEquals("fieldset", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testIFRAME() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.IFRAME;
assertEquals("iframe", tag.toString());
assertTrue(tag.breaksFlow());
assertTrue(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testINS() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.INS;
assertEquals("ins", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testLABEL() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.LABEL;
assertEquals("label", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testLEGEND() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.LEGEND;
assertEquals("legend", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testNOSCRIPT() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.NOSCRIPT;
assertEquals("noscript", tag.toString());
assertTrue(tag.breaksFlow());
assertTrue(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testOPTGROUP() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.OPTGROUP;
assertEquals("optgroup", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testQ() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.Q;
assertEquals("q", tag.toString());
assertFalse(tag.breaksFlow());
assertFalse(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testTBODY() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.TBODY;
assertEquals("tbody", tag.toString());
assertTrue(tag.breaksFlow());
assertTrue(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testTFOOT() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.TFOOT;
assertEquals("tfoot", tag.toString());
assertTrue(tag.breaksFlow());
assertTrue(tag.isBlock());
assertFalse(tag.isPreformatted());
}
public void testTHEAD() {
if (!BasicSwingTestCase.isHarmony()) {
return;
}
tag = HTML.Tag.THEAD;
assertEquals("thead", tag.toString());
assertTrue(tag.breaksFlow());
assertTrue(tag.isBlock());
assertFalse(tag.isPreformatted());
}
}
| shannah/cn1 | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/swing/src/test/api/java.injected/javax/swing/text/html/HTML_TagTest.java | Java | gpl-2.0 | 29,482 |
package org.mule.galaxy.impl.artifact;
import static org.mule.galaxy.event.DefaultEvents.ITEM_DELETED;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.query.InvalidQueryException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.ExtensibleElement;
import org.apache.abdera.protocol.server.context.ResponseContextException;
import org.mule.galaxy.Item;
import org.mule.galaxy.Link;
import org.mule.galaxy.PropertyException;
import org.mule.galaxy.Registry;
import org.mule.galaxy.RegistryException;
import org.mule.galaxy.artifact.Artifact;
import org.mule.galaxy.artifact.ArtifactType;
import org.mule.galaxy.artifact.ArtifactTypeDao;
import org.mule.galaxy.artifact.ContentHandler;
import org.mule.galaxy.artifact.ContentService;
import org.mule.galaxy.artifact.XmlContentHandler;
import org.mule.galaxy.event.ItemDeletedEvent;
import org.mule.galaxy.event.annotation.BindToEvent;
import org.mule.galaxy.event.annotation.OnEvent;
import org.mule.galaxy.extension.AtomExtension;
import org.mule.galaxy.impl.extension.AbstractExtension;
import org.mule.galaxy.impl.jcr.JcrUtil;
import org.mule.galaxy.impl.link.LinkExtension;
import org.mule.galaxy.policy.PolicyException;
import org.mule.galaxy.security.AccessException;
import org.mule.galaxy.type.PropertyDescriptor;
import org.mule.galaxy.util.BundleUtils;
import org.mule.galaxy.util.Constants;
import org.mule.galaxy.util.GalaxyUtils;
import org.mule.galaxy.util.Message;
import org.springmodules.jcr.JcrCallback;
import org.springmodules.jcr.JcrTemplate;
@BindToEvent(ITEM_DELETED)
public class ArtifactExtension extends AbstractExtension implements AtomExtension {
private static final QName ARTIFACT_QNAME = new QName(Constants.ATOM_NAMESPACE, "artifact");
private static final Collection<QName> UNDERSTOOD = new ArrayList<QName>();
static {
UNDERSTOOD.add(ARTIFACT_QNAME);
}
public static final String ID = "artifactExtension";
public static final String ITEM_ID = "item";
private JcrTemplate template;
private String artifactsNodeId;
private ContentService contentService;
private ArtifactTypeDao artifactTypeDao;
private Registry registry;
public void initialize() throws Exception {
JcrUtil.doInTransaction(template.getSessionFactory(), new JcrCallback() {
public Object doInJcr(Session session) throws IOException,
RepositoryException {
artifactsNodeId = JcrUtil.getOrCreate(session.getRootNode(), "artifacts").getUUID();
session.save();
return null;
}
});
}
/**
* In previous versions we didn't properly clean up artifacts. This method will clean up those old ones
* on startup.
*/
public void cleanupOldArtifacts() throws IOException, RepositoryException {
JcrUtil.doInTransaction(template.getSessionFactory(), new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
for (NodeIterator artifacts = session.getNodeByUUID(artifactsNodeId).getNodes(); artifacts.hasNext();) {
Node artifact = artifacts.nextNode();
QueryManager qm = session.getWorkspace().getQueryManager();
QueryResult result = qm.createQuery("//element(*, galaxy:item)[@artifact = '" + artifact.getUUID() + "']", Query.XPATH).execute();
if (result.getNodes().getSize() == 0) {
artifact.remove();
}
}
return null;
}
});
}
@OnEvent
public void onItemDeleted(final ItemDeletedEvent e) {
template.execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
QueryManager qm = session.getWorkspace().getQueryManager();
QueryResult result = qm.createQuery("/jcr:root/artifacts/*[item='" + e.getItemId() + "']", Query.XPATH).execute();
for (NodeIterator nodes = result.getNodes(); nodes.hasNext();) {
Node artifact = nodes.nextNode();
artifact.remove();
}
session.save();
return null;
}
});
}
/**
* Count the number of artifacts in the system. Used for testing to ensure deletes happen properly.
* @return
*/
public int getArtifactCount() {
return (Integer) template.execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
return new Long(session.getNodeByUUID(artifactsNodeId).getNodes().getSize()).intValue();
}
});
}
public Object get(Item item, PropertyDescriptor pd, boolean getWithNoData) {
Object storedValue = item.getInternalProperty(pd.getProperty());
if (storedValue == null) {
return null;
}
return getArtifact(item, (String)storedValue);
}
public void store(final Item item, final PropertyDescriptor pd, Object value)
throws PolicyException, PropertyException, AccessException {
if (value == null) {
item.setInternalProperty(pd.getProperty(), null);
} else if (value instanceof Object[]) {
Object[] values = (Object[]) value;
if (values.length != 2) {
throw new PropertyException(new Message("INVALID_VALUES", BundleUtils.getBundle(ArtifactExtension.class)));
}
final InputStream is = (InputStream) values[0];
final String ct = (String) values[1];
store(item, pd, is, ct);
} else if (value instanceof Artifact) {
try {
final InputStream is = ((Artifact) value).getInputStream();
final String ct = ((Artifact) value).getContentType().toString();
store(item, pd, is, ct);
} catch (IOException e) {
throw new PropertyException(e);
}
} else {
throw new UnsupportedOperationException("Values of type " + value.getClass() + " can not be stored as files.");
}
}
public void store(final Item item, final PropertyDescriptor pd, final InputStream is, final String ct)
throws PropertyException, PolicyException {
String id = (String) template.execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException,
RepositoryException {
return persistArtifact(item, pd, is, ct, session);
}
});
item.setInternalProperty(pd.getProperty(), id);
}
private Artifact getArtifact(final Item item, final String storedValue) {
return (Artifact) template.execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException,
RepositoryException {
Node node = session.getNodeByUUID(storedValue);
return new ArtifactImpl(item, node, contentService);
}
});
}
protected String persistArtifact(final Item item,
final PropertyDescriptor pd,
final InputStream is,
String contentType,
Session session)
throws RepositoryException {
String nodeId = item.getInternalProperty(pd.getProperty());
Node node;
if (nodeId == null) {
Node artifacts = session.getNodeByUUID(artifactsNodeId);
node = artifacts.addNode(UUID.randomUUID().toString());
node.addMixin("mix:referenceable");
} else {
node = session.getNodeByUUID(nodeId);
}
contentType = trimContentType(contentType);
// Deal with the case where we don't have a good mime type
if ("application/octet-stream".equals(contentType)) {
String ext = getExtension(item.getParent().getName());
ArtifactType type = artifactTypeDao.getArtifactType(ext);
if (type == null && "xml".equals(ext)) {
contentType = "application/xml";
} else if (type != null) {
contentType = type.getContentType();
}
}
node.setProperty(ITEM_ID, item.getId());
node.setProperty(ArtifactImpl.CONTENT_TYPE, contentType);
createContentNode(node, is, contentType);
ArtifactImpl artifact = new ArtifactImpl(item, node, contentService);
ContentHandler ch = artifact.getContentHandler();
try {
Object loadedData = artifact.getData();
if (ch instanceof XmlContentHandler) {
XmlContentHandler xch = (XmlContentHandler) ch;
node.setProperty(ArtifactImpl.DOCUMENT_TYPE, xch.getDocumentType(loadedData).toString());
ch = contentService.getContentHandler(artifact.getDocumentType());
}
Item container = item.getParent().getParent();
Set<String> dependencies = ch.detectDependencies(loadedData, container);
Set<Link> links = new HashSet<Link>();
for (String p : dependencies) {
Item resolvedItem = registry.resolve(container, p);
links.add(new Link(item, resolvedItem, p, true));
}
if (links.size() > 0) {
item.setProperty(LinkExtension.DEPENDS, links);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (PropertyException e) {
throw new RuntimeException(e);
} catch (AccessException e) {
throw new RuntimeException(e);
} catch (PolicyException e) {
throw new RuntimeException(e);
} catch (RegistryException e) {
throw new RuntimeException(e);
}
return node.getUUID();
}
public List<String> getArtifactsForContentType(final String propertyId,
final boolean like,
final Object value) {
return (List<String>) template.execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
return getArtifacts(session, propertyId, like, "contentType", value);
}
});
}
public List<String> getArtifactsForDocumentType(final String propertyId,
final boolean like,
final Object value) {
return (List<String>) template.execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
return getArtifacts(session, propertyId, like, "documentType", value);
}
});
}
public List<String> getArtifacts(Session session,
final String propertyId,
final boolean like,
final String searchField,
final Object value) throws RepositoryException {
List<String> ids = new ArrayList<String>();
if (value instanceof Collection) {
for (Object o : ((Collection) value)) {
getArtifacts(session, like, searchField, o.toString(), ids);
}
} else {
getArtifacts(session, like, searchField, value.toString(), ids);
}
return ids;
}
protected void getArtifacts(Session session, final boolean like, final String searchField, final String value,
List<String> ids) throws RepositoryException, InvalidQueryException,
UnsupportedRepositoryOperationException {
String comparison = like ? "like" : "=";
QueryManager qm = session.getWorkspace().getQueryManager();
String queryString = MessageFormat.format("//*[jcr:uuid=\"{0}\"]/*[@{1} {2} \"{3}\"]", artifactsNodeId, searchField, comparison, value);
Query query = qm.createQuery(queryString, Query.XPATH);
for (NodeIterator nodes = query.execute().getNodes(); nodes.hasNext();) {
ids.add(nodes.nextNode().getUUID());
}
}
protected Node createContentNode(Node versionNode,
final InputStream is,
final String contentType)
throws RepositoryException {
for (NodeIterator nodes = versionNode.getNodes(); nodes.hasNext();) {
nodes.nextNode().remove();
}
// these are required since we inherit from nt:file
Node resNode = versionNode.addNode("jcr:content", "nt:resource");
resNode.setProperty("jcr:mimeType", contentType);
// resNode.setProperty("jcr:encoding", "");
resNode.setProperty("jcr:lastModified", GalaxyUtils.getCalendarForNow());
if (is != null) {
resNode.setProperty("jcr:data", is);
}
return resNode;
}
private String trimContentType(String contentType) {
int comma = contentType.indexOf(';');
if (comma != -1) {
contentType = contentType.substring(0, comma);
}
return contentType;
}
private String getExtension(String name) {
int idx = name.lastIndexOf('.');
if (idx > 0) {
return name.substring(idx + 1);
}
return "";
}
public Map<String, String> getQueryProperties(PropertyDescriptor pd) {
HashMap<String, String> props = new HashMap<String, String>();
// props.put(pd.getProperty() + ".contents", pd.getDescription() + " Contents");
props.put(pd.getProperty() + ".contentType", pd.getDescription() + " Content Type");
props.put(pd.getProperty() + ".artifactType", pd.getDescription() + " Artifact Type");
props.put(pd.getProperty() + ".documentType", pd.getDescription() + " Document Type");
return props;
}
public void annotateAtomEntry(Item item,
PropertyDescriptor pd,
Entry entry,
ExtensibleElement metadata,
Factory factory) {
Artifact artifact = item.getProperty(pd.getProperty());
ExtensibleElement el = factory.newElement(ARTIFACT_QNAME, metadata);
el.setAttributeValue("property", pd.getProperty());
el.setAttributeValue("mediaType", artifact.getContentType().toString());
QName docType = artifact.getDocumentType();
if (docType != null) {
el.setAttributeValue("documentType", docType.toString());
}
}
public Collection<QName> getUnderstoodElements() {
return UNDERSTOOD;
}
public Object getValue(Item item, ExtensibleElement e, Factory factory) throws ResponseContextException {
return null;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public void setArtifactTypeDao(ArtifactTypeDao artifactTypeDao) {
this.artifactTypeDao = artifactTypeDao;
}
public void setTemplate(JcrTemplate template) {
this.template = template;
}
public void setRegistry(Registry registry) {
this.registry = registry;
}
}
| genjosanzo/galaxy-ce | core/src/main/java/org/mule/galaxy/impl/artifact/ArtifactExtension.java | Java | gpl-2.0 | 16,604 |
/*
* This file is part of the LIRE project: http://www.SemanticMetadata.net/lire.
*
* Lire is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Lire is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Lire; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Copyright statement:
* --------------------
* (c) 2008 by Savvas A. Chatzichristofis, [email protected]
*/
package net.semanticmetadata.lire.imageanalysis.cedd;
public class MaskResults {
public double Mask1;
public double Mask2;
public double Mask3;
public double Mask4;
public double Mask5;
}
| viirya/lire-sparsevw | src/main/java/net/semanticmetadata/lire/imageanalysis/cedd/MaskResults.java | Java | gpl-2.0 | 1,132 |
/*
* Copyright (C) 2007-2014 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.text.model;
public interface CharStorage {
int size();
char[] block(int index);
char[] createNewBlock(int minimumLength);
void freezeLastBlock();
}
| xiaosea/easyreader | src/main/java/org/geometerplus/zlibrary/text/model/CharStorage.java | Java | gpl-2.0 | 987 |
/*
* Copyright (c) 2011, 2013, 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 javafx.css;
import javafx.beans.property.BooleanPropertyBase;
import javafx.beans.value.ObservableValue;
/**
* This class extends {@code BooleanPropertyBase} and provides a partial
* implementation of a {@code StyleableProperty}. The method
* {@link StyleableProperty#getCssMetaData()} is not implemented.
*
* This class is used to make a {@link javafx.beans.property.BooleanProperty},
* that would otherwise be implemented as a {@link BooleanPropertyBase},
* style‑able by CSS.
*
* @see javafx.beans.property.BooleanPropertyBase
* @see CssMetaData
* @see StyleableProperty
* @since JavaFX 8.0
*/
public abstract class StyleableBooleanProperty
extends BooleanPropertyBase implements StyleableProperty<Boolean> {
/**
* The constructor of the {@code StyleableBooleanProperty}.
*/
public StyleableBooleanProperty() {
super();
}
/**
* The constructor of the {@code StyleableBooleanProperty}.
*
* @param initialValue
* the initial value of the wrapped {@code Object}
*/
public StyleableBooleanProperty(boolean initialValue) {
super(initialValue);
}
/** {@inheritDoc} */
@Override
public void applyStyle(StyleOrigin origin, Boolean v) {
// call set here in case it has been overridden in the javafx.beans.property
set(v.booleanValue());
this.origin = origin;
}
/** {@inheritDoc} */
@Override
public void bind(ObservableValue<? extends Boolean> observable) {
super.bind(observable);
origin = StyleOrigin.USER;
}
/** {@inheritDoc} */
@Override
public void set(boolean v) {
super.set(v);
origin = StyleOrigin.USER;
}
/** {@inheritDoc} */
@Override
public StyleOrigin getStyleOrigin() { return origin; }
private StyleOrigin origin = null;
}
| Debian/openjfx | modules/graphics/src/main/java/javafx/css/StyleableBooleanProperty.java | Java | gpl-2.0 | 3,091 |
/*
* Copyright 2002 Sun Microsystems, Inc. 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.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/**
*This is a description for C5.
*/
public class C5 {
public static final int I = 1;
}
| TheTypoMaster/Scaper | openjdk/langtools/test/com/sun/javadoc/testCmndLineClass/C5.java | Java | gpl-2.0 | 1,152 |
/*
* Copyright (c) 2011, 2018, 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.
*
* 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 org.graalvm.compiler.nodes.memory;
import static org.graalvm.compiler.nodeinfo.InputType.Memory;
import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_2;
import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_1;
import org.graalvm.compiler.core.common.LIRKind;
import org.graalvm.compiler.core.common.type.ObjectStamp;
import org.graalvm.compiler.core.common.type.Stamp;
import org.graalvm.compiler.debug.DebugCloseable;
import org.graalvm.compiler.graph.Node;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.graph.spi.Canonicalizable;
import org.graalvm.compiler.graph.spi.CanonicalizerTool;
import org.graalvm.compiler.nodeinfo.NodeInfo;
import org.graalvm.compiler.nodes.NodeView;
import org.graalvm.compiler.nodes.ValueNodeUtil;
import org.graalvm.compiler.nodes.ValuePhiNode;
import org.graalvm.compiler.nodes.extended.GuardingNode;
import org.graalvm.compiler.nodes.memory.address.AddressNode;
import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
import jdk.internal.vm.compiler.word.LocationIdentity;
/**
* A floating read of a value from memory specified in terms of an object base and an object
* relative location. This node does not null check the object.
*/
@NodeInfo(nameTemplate = "Read#{p#location/s}", cycles = CYCLES_2, size = SIZE_1)
public final class FloatingReadNode extends FloatingAccessNode implements LIRLowerableAccess, Canonicalizable {
public static final NodeClass<FloatingReadNode> TYPE = NodeClass.create(FloatingReadNode.class);
@OptionalInput(Memory) MemoryNode lastLocationAccess;
public FloatingReadNode(AddressNode address, LocationIdentity location, MemoryNode lastLocationAccess, Stamp stamp) {
this(address, location, lastLocationAccess, stamp, null, BarrierType.NONE);
}
public FloatingReadNode(AddressNode address, LocationIdentity location, MemoryNode lastLocationAccess, Stamp stamp, GuardingNode guard) {
this(address, location, lastLocationAccess, stamp, guard, BarrierType.NONE);
}
public FloatingReadNode(AddressNode address, LocationIdentity location, MemoryNode lastLocationAccess, Stamp stamp, GuardingNode guard, BarrierType barrierType) {
super(TYPE, address, location, stamp, guard, barrierType);
this.lastLocationAccess = lastLocationAccess;
// The input to floating reads must be always non-null or have at least a guard.
assert guard != null || !(address.getBase().stamp(NodeView.DEFAULT) instanceof ObjectStamp) || address.getBase() instanceof ValuePhiNode ||
((ObjectStamp) address.getBase().stamp(NodeView.DEFAULT)).nonNull() : address.getBase();
}
@Override
public MemoryNode getLastLocationAccess() {
return lastLocationAccess;
}
@Override
public void setLastLocationAccess(MemoryNode newlla) {
updateUsages(ValueNodeUtil.asNode(lastLocationAccess), ValueNodeUtil.asNode(newlla));
lastLocationAccess = newlla;
}
@Override
public void generate(NodeLIRBuilderTool gen) {
LIRKind readKind = gen.getLIRGeneratorTool().getLIRKind(stamp(NodeView.DEFAULT));
gen.setResult(this, gen.getLIRGeneratorTool().getArithmetic().emitLoad(readKind, gen.operand(address), null));
}
@Override
public Node canonical(CanonicalizerTool tool) {
Node result = ReadNode.canonicalizeRead(this, getAddress(), getLocationIdentity(), tool);
if (result != this) {
return result;
}
if (tool.canonicalizeReads() && getAddress().hasMoreThanOneUsage() && lastLocationAccess instanceof WriteNode) {
WriteNode write = (WriteNode) lastLocationAccess;
if (write.getAddress() == getAddress() && write.getAccessStamp().isCompatible(getAccessStamp())) {
// Same memory location with no intervening write
return write.value();
}
}
return this;
}
@SuppressWarnings("try")
@Override
public FixedAccessNode asFixedNode() {
try (DebugCloseable position = withNodeSourcePosition()) {
ReadNode result = graph().add(new ReadNode(getAddress(), getLocationIdentity(), stamp(NodeView.DEFAULT), getBarrierType()));
result.setGuard(getGuard());
return result;
}
}
@Override
public boolean verify() {
MemoryNode lla = getLastLocationAccess();
assert lla != null || getLocationIdentity().isImmutable() : "lastLocationAccess of " + this + " shouldn't be null for mutable location identity " + getLocationIdentity();
return super.verify();
}
@Override
public Stamp getAccessStamp() {
return stamp(NodeView.DEFAULT);
}
}
| md-5/jdk10 | src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/memory/FloatingReadNode.java | Java | gpl-2.0 | 5,793 |
/*
* Copyright (c) 2013, 2017, 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 javafx.scene.shape;
import com.sun.javafx.geom.BaseBounds;
import com.sun.javafx.geom.PickRay;
import com.sun.javafx.geom.Vec3d;
import com.sun.javafx.geom.transform.BaseTransform;
import com.sun.javafx.scene.DirtyBits;
import com.sun.javafx.scene.NodeHelper;
import com.sun.javafx.scene.input.PickResultChooser;
import com.sun.javafx.scene.shape.MeshHelper;
import com.sun.javafx.scene.shape.SphereHelper;
import com.sun.javafx.sg.prism.NGNode;
import com.sun.javafx.sg.prism.NGSphere;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Point2D;
import javafx.geometry.Point3D;
import javafx.scene.Node;
import javafx.scene.input.PickResult;
import javafx.scene.transform.Rotate;
/**
* The {@code Sphere} class defines a 3 dimensional sphere with the specified size.
* A {@code Sphere} is a 3D geometry primitive created with a given radius.
* It is centered at the origin.
*
* @since JavaFX 8.0
*/
public class Sphere extends Shape3D {
static {
// This is used by classes in different packages to get access to
// private and package private methods.
SphereHelper.setSphereAccessor(new SphereHelper.SphereAccessor() {
@Override
public NGNode doCreatePeer(Node node) {
return ((Sphere) node).doCreatePeer();
}
@Override
public void doUpdatePeer(Node node) {
((Sphere) node).doUpdatePeer();
}
@Override
public BaseBounds doComputeGeomBounds(Node node,
BaseBounds bounds, BaseTransform tx) {
return ((Sphere) node).doComputeGeomBounds(bounds, tx);
}
@Override
public boolean doComputeContains(Node node, double localX, double localY) {
return ((Sphere) node).doComputeContains(localX, localY);
}
@Override
public boolean doComputeIntersects(Node node, PickRay pickRay,
PickResultChooser pickResult) {
return ((Sphere) node).doComputeIntersects(pickRay, pickResult);
}
});
}
static final int DEFAULT_DIVISIONS = 64;
static final double DEFAULT_RADIUS = 1;
private int divisions = DEFAULT_DIVISIONS;
private TriangleMesh mesh;
/**
* Creates a new instance of {@code Sphere} with radius of 1.0.
* The resolution defaults to 64 divisions along the sphere's axes.
*/
public Sphere() {
this(DEFAULT_RADIUS, DEFAULT_DIVISIONS);
}
/**
* Creates a new instance of {@code Sphere} with the given radius.
* The resolution defaults to 64 divisions along the sphere's axes.
*
* @param radius Radius
*/
public Sphere(double radius) {
this(radius, DEFAULT_DIVISIONS);
}
/**
* Creates a new instance of {@code Sphere} with the given radius and number
* of divisions.
* The resolution is defined in terms of number of subdivisions along the
* sphere's axes. More divisions lead to more finely tesselated objects.
*
* Note that divisions should be at least 1. Any value less than that will be
* clamped to 1.
*
* @param radius Radius
* @param divisions Divisions
*/
public Sphere(double radius, int divisions) {
SphereHelper.initHelper(this);
this.divisions = divisions < 1 ? 1: divisions;
setRadius(radius);
}
/**
* Defines the radius of the Sphere.
*
* @defaultValue 1.0
*/
private DoubleProperty radius;
public final void setRadius(double value) {
radiusProperty().set(value);
}
public final double getRadius() {
return radius == null ? 1 : radius.get();
}
public final DoubleProperty radiusProperty() {
if (radius == null) {
radius = new SimpleDoubleProperty(Sphere.this, "radius", DEFAULT_RADIUS) {
@Override
public void invalidated() {
NodeHelper.markDirty(Sphere.this, DirtyBits.MESH_GEOM);
manager.invalidateSphereMesh(key);
key = 0;
NodeHelper.geomChanged(Sphere.this);
}
};
}
return radius;
}
/**
* Retrieves the divisions attribute use to generate this sphere.
*
* @return the divisions attribute.
*/
public int getDivisions() {
return divisions;
}
/*
* Note: This method MUST only be called via its accessor method.
*/
private NGNode doCreatePeer() {
return new NGSphere();
}
/*
* Note: This method MUST only be called via its accessor method.
*/
private void doUpdatePeer() {
if (NodeHelper.isDirty(this, DirtyBits.MESH_GEOM)) {
final NGSphere pgSphere = NodeHelper.getPeer(this);
final float r = (float) getRadius();
if (r < 0) {
pgSphere.updateMesh(null);
} else {
if (key == 0) {
key = generateKey(r, divisions);
}
mesh = manager.getSphereMesh(r, divisions, key);
mesh.updatePG();
pgSphere.updateMesh(mesh.getPGTriangleMesh());
}
}
}
/*
* Note: This method MUST only be called via its accessor method.
*/
private BaseBounds doComputeGeomBounds(BaseBounds bounds, BaseTransform tx) {
final float r = (float) getRadius();
if (r < 0) {
return bounds.makeEmpty();
}
bounds = bounds.deriveWithNewBounds(-r, -r, -r, r, r ,r);
bounds = tx.transform(bounds, bounds);
return bounds;
}
/*
* Note: This method MUST only be called via its accessor method.
*/
private boolean doComputeContains(double localX, double localY) {
double r = getRadius();
double n2 = localX * localX + localY * localY;
return n2 <= r * r;
}
/*
* Note: This method MUST only be called via its accessor method.
*/
private boolean doComputeIntersects(PickRay pickRay, PickResultChooser pickResult) {
final boolean exactPicking = divisions < DEFAULT_DIVISIONS && mesh != null;
final double r = getRadius();
final Vec3d dir = pickRay.getDirectionNoClone();
final double dirX = dir.x;
final double dirY = dir.y;
final double dirZ = dir.z;
final Vec3d origin = pickRay.getOriginNoClone();
final double originX = origin.x;
final double originY = origin.y;
final double originZ = origin.z;
// Coeficients of a quadratic equation desribing intersection with sphere
final double a = dirX * dirX + dirY * dirY + dirZ * dirZ;
final double b = 2 * (dirX * originX + dirY * originY + dirZ * originZ);
final double c = originX * originX + originY * originY + originZ * originZ - r * r;
final double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
// No real roots of the equation, missed the shape
return false;
}
final double distSqrt = Math.sqrt(discriminant);
final double q = (b < 0) ? (-b - distSqrt) / 2.0 : (-b + distSqrt) / 2.0;
double t0 = q / a;
double t1 = c / q;
if (t0 > t1) {
final double temp = t0;
t0 = t1;
t1 = temp;
}
final double minDistance = pickRay.getNearClip();
final double maxDistance = pickRay.getFarClip();
if (t1 < minDistance || t0 > maxDistance) {
// the sphere is out of clipping planes
return false;
}
double t = t0;
final CullFace cullFace = getCullFace();
if (t0 < minDistance || cullFace == CullFace.FRONT) {
if (t1 <= maxDistance && getCullFace() != CullFace.BACK) {
// picking the back wall
t = t1;
} else {
// we are inside the sphere with the back wall culled, but the
// exact picking still needs to be done because the front faced
// triangles may still be in front of us
if (!exactPicking) {
return false;
}
}
}
if (Double.isInfinite(t) || Double.isNaN(t)) {
// We've got a nonsense pick ray or sphere size.
return false;
}
if (exactPicking) {
return MeshHelper.computeIntersects(mesh, pickRay, pickResult, this, cullFace, false);
}
if (pickResult != null && pickResult.isCloser(t)) {
final Point3D point = PickResultChooser.computePoint(pickRay, t);
// computing texture coords
final Point3D proj = new Point3D(point.getX(), 0, point.getZ());
final Point3D cross = proj.crossProduct(Rotate.Z_AXIS);
double angle = proj.angle(Rotate.Z_AXIS);
if (cross.getY() > 0) {
angle = 360 - angle;
}
Point2D txtCoords = new Point2D(1 - angle / 360, 0.5 + point.getY() / (2 * r));
pickResult.offer(this, t, PickResult.FACE_UNDEFINED, point, txtCoords);
}
return true;
}
private static int correctDivisions(int div) {
return ((div + 3) / 4) * 4;
}
static TriangleMesh createMesh(int div, float r) {
div = correctDivisions(div);
// NOTE: still create mesh for degenerated sphere
final int div2 = div / 2;
final int nPoints = div * (div2 - 1) + 2;
final int nTPoints = (div + 1) * (div2 - 1) + div * 2;
final int nFaces = div * (div2 - 2) * 2 + div * 2;
final float rDiv = 1.f / div;
float points[] = new float[nPoints * 3];
float tPoints[] = new float[nTPoints * 2];
int faces[] = new int[nFaces * 6];
int pPos = 0, tPos = 0;
for (int y = 0; y < div2 - 1; ++y) {
float va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI;
float sin_va = (float) Math.sin(va);
float cos_va = (float) Math.cos(va);
float ty = 0.5f + sin_va * 0.5f;
for (int i = 0; i < div; ++i) {
double a = rDiv * i * 2 * (float) Math.PI;
float hSin = (float) Math.sin(a);
float hCos = (float) Math.cos(a);
points[pPos + 0] = hSin * cos_va * r;
points[pPos + 2] = hCos * cos_va * r;
points[pPos + 1] = sin_va * r;
tPoints[tPos + 0] = 1 - rDiv * i;
tPoints[tPos + 1] = ty;
pPos += 3;
tPos += 2;
}
tPoints[tPos + 0] = 0;
tPoints[tPos + 1] = ty;
tPos += 2;
}
points[pPos + 0] = 0;
points[pPos + 1] = -r;
points[pPos + 2] = 0;
points[pPos + 3] = 0;
points[pPos + 4] = r;
points[pPos + 5] = 0;
pPos += 6;
int pS = (div2 - 1) * div;
float textureDelta = 1.f / 256;
for (int i = 0; i < div; ++i) {
tPoints[tPos + 0] = 1.0f - rDiv * (0.5f + i);
tPoints[tPos + 1] = textureDelta;
tPos += 2;
}
for (int i = 0; i < div; ++i) {
tPoints[tPos + 0] = 1.0f - rDiv * (0.5f + i);
tPoints[tPos + 1] = 1 - textureDelta;
tPos += 2;
}
int fIndex = 0;
for (int y = 0; y < div2 - 2; ++y) {
for (int x = 0; x < div; ++x) {
int p0 = y * div + x;
int p1 = p0 + 1;
int p2 = p0 + div;
int p3 = p1 + div;
int t0 = p0 + y;
int t1 = t0 + 1;
int t2 = t0 + (div + 1);
int t3 = t1 + (div + 1);
// add p0, p1, p2
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1 % div == 0 ? p1 - div : p1;
faces[fIndex + 3] = t1;
faces[fIndex + 4] = p2;
faces[fIndex + 5] = t2;
fIndex += 6;
// add p3, p2, p1
faces[fIndex + 0] = p3 % div == 0 ? p3 - div : p3;
faces[fIndex + 1] = t3;
faces[fIndex + 2] = p2;
faces[fIndex + 3] = t2;
faces[fIndex + 4] = p1 % div == 0 ? p1 - div : p1;
faces[fIndex + 5] = t1;
fIndex += 6;
}
}
int p0 = pS;
int tB = (div2 - 1) * (div + 1);
for (int x = 0; x < div; ++x) {
int p2 = x, p1 = x + 1, t0 = tB + x;
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1 == div ? 0 : p1;
faces[fIndex + 3] = p1;
faces[fIndex + 4] = p2;
faces[fIndex + 5] = p2;
fIndex += 6;
}
p0 = p0 + 1;
tB = tB + div;
int pB = (div2 - 2) * div;
for (int x = 0; x < div; ++x) {
int p1 = pB + x, p2 = pB + x + 1, t0 = tB + x;
int t1 = (div2 - 2) * (div + 1) + x, t2 = t1 + 1;
faces[fIndex + 0] = p0;
faces[fIndex + 1] = t0;
faces[fIndex + 2] = p1;
faces[fIndex + 3] = t1;
faces[fIndex + 4] = p2 % div == 0 ? p2 - div : p2;
faces[fIndex + 5] = t2;
fIndex += 6;
}
TriangleMesh m = new TriangleMesh(true);
m.getPoints().setAll(points);
m.getTexCoords().setAll(tPoints);
m.getFaces().setAll(faces);
return m;
}
private static int generateKey(float r, int div) {
int hash = 5;
hash = 23 * hash + Float.floatToIntBits(r);
hash = 23 * hash + div;
return hash;
}
}
| teamfx/openjfx-10-dev-rt | modules/javafx.graphics/src/main/java/javafx/scene/shape/Sphere.java | Java | gpl-2.0 | 15,237 |
/*
* Copyright (c) 1999, 2019, 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.javac.main;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.tools.JavaFileManager;
import com.sun.tools.javac.api.BasicJavacTask;
import com.sun.tools.javac.file.CacheFSInfo;
import com.sun.tools.javac.file.BaseFileManager;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.main.CommandLine.UnmatchedQuote;
import com.sun.tools.javac.platform.PlatformDescription;
import com.sun.tools.javac.processing.AnnotationProcessingError;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticInfo;
import com.sun.tools.javac.util.Log.PrefixKind;
import com.sun.tools.javac.util.Log.WriterKind;
/** This class provides a command line interface to the javac compiler.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Main {
/** The name of the compiler, for use in diagnostics.
*/
String ownName;
/** The writer to use for normal output.
*/
PrintWriter stdOut;
/** The writer to use for diagnostic output.
*/
PrintWriter stdErr;
/** The log to use for diagnostic output.
*/
public Log log;
/**
* If true, certain errors will cause an exception, such as command line
* arg errors, or exceptions in user provided code.
*/
boolean apiMode;
private static final String ENV_OPT_NAME = "JDK_JAVAC_OPTIONS";
/** Result codes.
*/
public enum Result {
OK(0), // Compilation completed with no errors.
ERROR(1), // Completed but reported errors.
CMDERR(2), // Bad command-line arguments
SYSERR(3), // System error or resource exhaustion.
ABNORMAL(4); // Compiler terminated abnormally
Result(int exitCode) {
this.exitCode = exitCode;
}
public boolean isOK() {
return (exitCode == 0);
}
public final int exitCode;
}
/**
* Construct a compiler instance.
* @param name the name of this tool
*/
public Main(String name) {
this.ownName = name;
}
/**
* Construct a compiler instance.
* @param name the name of this tool
* @param out a stream to which to write messages
*/
public Main(String name, PrintWriter out) {
this.ownName = name;
this.stdOut = this.stdErr = out;
}
/**
* Construct a compiler instance.
* @param name the name of this tool
* @param out a stream to which to write expected output
* @param err a stream to which to write diagnostic output
*/
public Main(String name, PrintWriter out, PrintWriter err) {
this.ownName = name;
this.stdOut = out;
this.stdErr = err;
}
/** Report a usage error.
*/
void reportDiag(DiagnosticInfo diag) {
if (apiMode) {
String msg = log.localize(diag);
throw new PropagatedException(new IllegalStateException(msg));
}
reportHelper(diag);
log.printLines(PrefixKind.JAVAC, "msg.usage", ownName);
}
/** Report helper.
*/
void reportHelper(DiagnosticInfo diag) {
String msg = log.localize(diag);
String errorPrefix = log.localize(Errors.Error);
msg = msg.startsWith(errorPrefix) ? msg : errorPrefix + msg;
log.printRawLines(msg);
}
/**
* Programmatic interface for main function.
* @param args the command line parameters
* @return the result of the compilation
*/
public Result compile(String[] args) {
Context context = new Context();
JavacFileManager.preRegister(context); // can't create it until Log has been set up
Result result = compile(args, context);
try {
// A fresh context was created above, so the file manager can be safely closed:
if (fileManager != null)
fileManager.close();
} catch (IOException ex) {
bugMessage(ex);
}
return result;
}
/**
* Internal version of compile, allowing context to be provided.
* Note that the context needs to have a file manager set up.
* @param argv the command line parameters
* @param context the context
* @return the result of the compilation
*/
public Result compile(String[] argv, Context context) {
if (stdOut != null) {
context.put(Log.outKey, stdOut);
}
if (stdErr != null) {
context.put(Log.errKey, stdErr);
}
log = Log.instance(context);
if (argv.length == 0) {
OptionHelper h = new OptionHelper.GrumpyHelper(log) {
@Override
public String getOwnName() { return ownName; }
@Override
public void put(String name, String value) { }
};
try {
Option.HELP.process(h, "-help");
} catch (Option.InvalidValueException ignore) {
}
return Result.CMDERR;
}
// prefix argv with contents of environment variable and expand @-files
try {
argv = CommandLine.parse(ENV_OPT_NAME, argv);
} catch (UnmatchedQuote ex) {
reportDiag(Errors.UnmatchedQuote(ex.variableName));
return Result.CMDERR;
} catch (FileNotFoundException | NoSuchFileException e) {
reportHelper(Errors.FileNotFound(e.getMessage()));
return Result.SYSERR;
} catch (IOException ex) {
log.printLines(PrefixKind.JAVAC, "msg.io");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
return Result.SYSERR;
}
Arguments args = Arguments.instance(context);
args.init(ownName, argv);
if (log.nerrors > 0)
return Result.CMDERR;
Options options = Options.instance(context);
// init Log
boolean forceStdOut = options.isSet("stdout");
if (forceStdOut) {
log.flush();
log.setWriters(new PrintWriter(System.out, true));
}
// init CacheFSInfo
// allow System property in following line as a Mustang legacy
boolean batchMode = (options.isUnset("nonBatchMode")
&& System.getProperty("nonBatchMode") == null);
if (batchMode)
CacheFSInfo.preRegister(context);
boolean ok = true;
// init file manager
fileManager = context.get(JavaFileManager.class);
JavaFileManager undel = fileManager instanceof DelegatingJavaFileManager ?
((DelegatingJavaFileManager) fileManager).getBaseFileManager() : fileManager;
if (undel instanceof BaseFileManager) {
((BaseFileManager) undel).setContext(context); // reinit with options
ok &= ((BaseFileManager) undel).handleOptions(args.getDeferredFileManagerOptions());
}
// handle this here so it works even if no other options given
String showClass = options.get("showClass");
if (showClass != null) {
if (showClass.equals("showClass")) // no value given for option
showClass = "com.sun.tools.javac.Main";
showClass(showClass);
}
ok &= args.validate();
if (!ok || log.nerrors > 0)
return Result.CMDERR;
if (args.isEmpty())
return Result.OK;
// init Dependencies
if (options.isSet("debug.completionDeps")) {
Dependencies.GraphDependencies.preRegister(context);
}
BasicJavacTask t = (BasicJavacTask) BasicJavacTask.instance(context);
// init plugins
Set<List<String>> pluginOpts = args.getPluginOpts();
t.initPlugins(pluginOpts);
// init multi-release jar handling
if (fileManager.isSupportedOption(Option.MULTIRELEASE.primaryName) == 1) {
Target target = Target.instance(context);
List<String> list = List.of(target.multiReleaseValue());
fileManager.handleOption(Option.MULTIRELEASE.primaryName, list.iterator());
}
// init JavaCompiler
JavaCompiler comp = JavaCompiler.instance(context);
// init doclint
List<String> docLintOpts = args.getDocLintOpts();
if (!docLintOpts.isEmpty()) {
t.initDocLint(docLintOpts);
}
if (options.get(Option.XSTDOUT) != null) {
// Stdout reassigned - ask compiler to close it when it is done
comp.closeables = comp.closeables.prepend(log.getWriter(WriterKind.NOTICE));
}
boolean printArgsToFile = options.isSet("printArgsToFile");
try {
comp.compile(args.getFileObjects(), args.getClassNames(), null, List.nil());
if (log.expectDiagKeys != null) {
if (log.expectDiagKeys.isEmpty()) {
log.printRawLines("all expected diagnostics found");
return Result.OK;
} else {
log.printRawLines("expected diagnostic keys not found: " + log.expectDiagKeys);
return Result.ERROR;
}
}
return (comp.errorCount() == 0) ? Result.OK : Result.ERROR;
} catch (OutOfMemoryError | StackOverflowError ex) {
resourceMessage(ex);
return Result.SYSERR;
} catch (FatalError ex) {
feMessage(ex, options);
return Result.SYSERR;
} catch (AnnotationProcessingError ex) {
apMessage(ex);
return Result.SYSERR;
} catch (PropagatedException ex) {
// TODO: what about errors from plugins? should not simply rethrow the error here
throw ex.getCause();
} catch (IllegalAccessError iae) {
if (twoClassLoadersInUse(iae)) {
bugMessage(iae);
}
printArgsToFile = true;
return Result.ABNORMAL;
} catch (Throwable ex) {
// Nasty. If we've already reported an error, compensate
// for buggy compiler error recovery by swallowing thrown
// exceptions.
if (comp == null || comp.errorCount() == 0 || options.isSet("dev"))
bugMessage(ex);
printArgsToFile = true;
return Result.ABNORMAL;
} finally {
if (printArgsToFile) {
printArgumentsToFile(argv);
}
if (comp != null) {
try {
comp.close();
} catch (ClientCodeException ex) {
throw new RuntimeException(ex.getCause());
}
}
}
}
void printArgumentsToFile(String... params) {
Path out = Paths.get(String.format("javac.%s.args",
new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime())));
String strOut = "";
try {
try (Writer w = Files.newBufferedWriter(out)) {
for (String param : params) {
param = param.replaceAll("\\\\", "\\\\\\\\");
if (param.matches(".*\\s+.*")) {
param = "\"" + param + "\"";
}
strOut += param + '\n';
}
w.write(strOut);
}
log.printLines(PrefixKind.JAVAC, "msg.parameters.output", out.toAbsolutePath());
} catch (IOException ioe) {
log.printLines(PrefixKind.JAVAC, "msg.parameters.output.error", out.toAbsolutePath());
System.err.println(strOut);
System.err.println();
}
}
private boolean twoClassLoadersInUse(IllegalAccessError iae) {
String msg = iae.getMessage();
Pattern pattern = Pattern.compile("(?i)(?<=tried to access class )([a-z_$][a-z\\d_$]*\\.)*[a-z_$][a-z\\d_$]*");
Matcher matcher = pattern.matcher(msg);
if (matcher.find()) {
try {
String otherClassName = matcher.group(0);
Class<?> otherClass = Class.forName(otherClassName);
ClassLoader otherClassLoader = otherClass.getClassLoader();
ClassLoader javacClassLoader = this.getClass().getClassLoader();
if (javacClassLoader != otherClassLoader) {
CodeSource otherClassCodeSource = otherClass.getProtectionDomain().getCodeSource();
CodeSource javacCodeSource = this.getClass().getProtectionDomain().getCodeSource();
if (otherClassCodeSource != null && javacCodeSource != null) {
log.printLines(Errors.TwoClassLoaders2(otherClassCodeSource.getLocation(),
javacCodeSource.getLocation()));
} else {
log.printLines(Errors.TwoClassLoaders1);
}
return true;
}
} catch (Throwable t) {
return false;
}
}
return false;
}
/** Print a message reporting an internal error.
*/
void bugMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.bug", JavaCompiler.version());
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Print a message reporting a fatal error.
*/
void feMessage(Throwable ex, Options options) {
log.printRawLines(ex.getMessage());
if (ex.getCause() != null && options.isSet("dev")) {
ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE));
}
}
/** Print a message reporting an input/output error.
*/
void ioMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.io");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Print a message reporting an out-of-resources error.
*/
void resourceMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.resource");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Print a message reporting an uncaught exception from an
* annotation processor.
*/
void apMessage(AnnotationProcessingError ex) {
log.printLines(PrefixKind.JAVAC, "msg.proc.annotation.uncaught.exception");
ex.getCause().printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Print a message reporting an uncaught exception from an
* annotation processor.
*/
void pluginMessage(Throwable ex) {
log.printLines(PrefixKind.JAVAC, "msg.plugin.uncaught.exception");
ex.printStackTrace(log.getWriter(WriterKind.NOTICE));
}
/** Display the location and checksum of a class. */
void showClass(String className) {
PrintWriter pw = log.getWriter(WriterKind.NOTICE);
pw.println("javac: show class: " + className);
URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
if (url != null) {
pw.println(" " + url);
}
try (InputStream in = getClass().getResourceAsStream('/' + className.replace('.', '/') + ".class")) {
final String algorithm = "SHA-256";
byte[] digest;
MessageDigest md = MessageDigest.getInstance(algorithm);
try (DigestInputStream din = new DigestInputStream(in, md)) {
byte[] buf = new byte[8192];
int n;
do { n = din.read(buf); } while (n > 0);
digest = md.digest();
}
StringBuilder sb = new StringBuilder();
for (byte b: digest)
sb.append(String.format("%02x", b));
pw.println(" " + algorithm + " checksum: " + sb);
} catch (NoSuchAlgorithmException | IOException e) {
pw.println(" cannot compute digest: " + e);
}
}
// TODO: update this to JavacFileManager
private JavaFileManager fileManager;
/* ************************************************************************
* Internationalization
*************************************************************************/
public static final String javacBundleName =
"com.sun.tools.javac.resources.javac";
}
| md-5/jdk10 | src/jdk.compiler/share/classes/com/sun/tools/javac/main/Main.java | Java | gpl-2.0 | 18,380 |
/*
* Copyright (c) 2005, 2006, 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.xml.internal.rngom.nc;
import javax.xml.namespace.QName;
public final class NsNameClass extends NameClass {
private final String namespaceUri;
public NsNameClass(String namespaceUri) {
this.namespaceUri = namespaceUri;
}
public boolean contains(QName name) {
return this.namespaceUri.equals(name.getNamespaceURI());
}
public int containsSpecificity(QName name) {
return contains(name) ? SPECIFICITY_NS_NAME : SPECIFICITY_NONE;
}
public int hashCode() {
return namespaceUri.hashCode();
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof NsNameClass))
return false;
return namespaceUri.equals(((NsNameClass)obj).namespaceUri);
}
public <V> V accept(NameClassVisitor<V> visitor) {
return visitor.visitNsName(namespaceUri);
}
public boolean isOpen() {
return true;
}
}
| samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/xml/internal/rngom/nc/NsNameClass.java | Java | gpl-2.0 | 2,095 |
/*
* Copyright 2006 Sun Microsystems, Inc. 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.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6413682
* @summary Compiler confused about implicit type args and arrays
* @author Peter von der Ah\u00e9
*/
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import static javax.tools.JavaFileObject.Kind.SOURCE;
import javax.tools.ToolProvider;
public class TestPos {
static final String errCode = "compiler.err.cannot.create.array.with.type.arguments";
static final String expected =
String.format("%s%n%s%n",
"compiler.err.cannot.create.array.with.type.arguments @ 33",
"begin=28, end=50 : new Object[0],T,e,s,t");
public static void main(String... args) throws IOException {
final boolean[] sawError = { false };
final StringBuilder log = new StringBuilder();
class MyFileObject extends SimpleJavaFileObject {
MyFileObject() {
super(URI.create("myfo:///Test.java"), SOURCE);
}
@Override
public String getCharContent(boolean ignoreEncodingErrors) {
// 0 1 2 3 4 5
// 0123456789012345678901234567890123456789012345678901234
return "class Test { { Object[] o = new <T,e,s,t>Object[0]; } }";
}
}
class Scanner extends TreeScanner<Void,Trees> {
CompilationUnitTree toplevel = null;
@Override
public Void visitCompilationUnit(CompilationUnitTree node, Trees trees) {
toplevel = node;
return super.visitCompilationUnit(node, trees);
}
@Override
public Void visitErroneous(ErroneousTree node, Trees trees) {
sawError[0] = true;
long startPos = trees.getSourcePositions().getStartPosition(toplevel, node);
long endPos = trees.getSourcePositions().getEndPosition(toplevel, node);
log.append(String.format("begin=%s, end=%s : %s%n",
startPos,
endPos,
node.getErrorTrees()));
if (startPos != 28)
error("Start pos for %s is incorrect (%s)!", node, startPos);
if (endPos != 50)
error("End pos for %s is incorrect (%s)!", node, endPos);
return null;
}
}
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
List<JavaFileObject> compilationUnits =
Collections.<JavaFileObject>singletonList(new MyFileObject());
DiagnosticListener<JavaFileObject> dl = new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic<? extends JavaFileObject> diag) {
log.append(String.format("%s @ %s%n", diag.getCode(), diag.getPosition()));
if (!diag.getCode().equals(errCode))
error("unexpected error");
if (diag.getPosition() != 33)
error("Error pos for %s is incorrect (%s)!",
diag.getCode(), diag.getPosition());
sawError[0] = true;
}
};
JavacTask task = (JavacTask)javac.getTask(null, null, dl, null, null,
compilationUnits);
Trees trees = Trees.instance(task);
Iterable<? extends Tree> toplevels = task.parse();
if (!sawError[0])
error("No parse error detected");
sawError[0] = false;
new Scanner().scan(toplevels, trees);
if (!sawError[0])
error("No error tree detected");
if (!log.toString().equals(expected))
error("Unexpected log message: %n%s%n", log);
System.out.print(log);
System.out.flush();
}
static void error(String format, Object... args) {
throw new AssertionError(String.format(format, args));
}
}
| TheTypoMaster/Scaper | openjdk/langtools/test/tools/javac/generics/6413682/TestPos.java | Java | gpl-2.0 | 5,523 |
package org.iatoki.judgels.sandalphon.problem.programming.grading.blackbox;
public abstract class SingleSourceFileBlackBoxGradingConfigForm extends AbstractBlackBoxGradingConfigForm {
}
| ia-toki/judgels | judgels-backends/sandalphon/sandalphon-app/app/org/iatoki/judgels/sandalphon/problem/programming/grading/blackbox/SingleSourceFileBlackBoxGradingConfigForm.java | Java | gpl-2.0 | 188 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2007, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------
* LabelBlock.java
* ---------------
* (C) Copyright 2004-2007, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Pierre-Marie Le Biot;
*
* Changes:
* --------
* 22-Oct-2004 : Version 1 (DG);
* 19-Apr-2005 : Added optional tooltip and URL text items,
* draw() method now returns entities if
* requested (DG);
* 13-May-2005 : Added methods to set the font (DG);
* 01-Sep-2005 : Added paint management (PMLB);
* Implemented equals() and clone() (PublicCloneable) (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 20-Jul-2006 : Fixed entity area in draw() method (DG);
* 16-Mar-2007 : Fixed serialization when using GradientPaint (DG);
* 20-Jun-2007 : Removed JCommon dependencies (DG);
*
*/
package org.jfree.chart.block;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.text.TextBlock;
import org.jfree.chart.text.TextBlockAnchor;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.chart.util.Size2D;
/**
* A block containing a label.
*/
public class LabelBlock extends AbstractBlock
implements Block, PublicCloneable {
/**
* The text for the label - retained in case the label needs
* regenerating (for example, to change the font).
*/
private String text;
/** The label. */
private TextBlock label;
/** The font. */
private Font font;
/** The tool tip text (can be <code>null</code>). */
private String toolTipText;
/** The URL text (can be <code>null</code>). */
private String urlText;
/** The default color. */
public static final Paint DEFAULT_PAINT = Color.black;
/** The paint. */
private transient Paint paint;
/**
* Creates a new label block.
*
* @param label the label (<code>null</code> not permitted).
*/
public LabelBlock(String label) {
this(label, new Font("SansSerif", Font.PLAIN, 10), DEFAULT_PAINT);
}
/**
* Creates a new label block.
*
* @param text the text for the label (<code>null</code> not permitted).
* @param font the font (<code>null</code> not permitted).
*/
public LabelBlock(String text, Font font) {
this(text, font, DEFAULT_PAINT);
}
/**
* Creates a new label block.
*
* @param text the text for the label (<code>null</code> not permitted).
* @param font the font (<code>null</code> not permitted).
* @param paint the paint (<code>null</code> not permitted).
*/
public LabelBlock(String text, Font font, Paint paint) {
this.text = text;
this.paint = paint;
this.label = TextUtilities.createTextBlock(text, font, this.paint);
this.font = font;
this.toolTipText = null;
this.urlText = null;
}
/**
* Returns the font.
*
* @return The font (never <code>null</code>).
*
* @see #setFont(Font)
*/
public Font getFont() {
return this.font;
}
/**
* Sets the font and regenerates the label.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getFont()
*/
public void setFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.font = font;
this.label = TextUtilities.createTextBlock(this.text, font, this.paint);
}
/**
* Returns the paint.
*
* @return The paint (never <code>null</code>).
*
* @see #setPaint(Paint)
*/
public Paint getPaint() {
return this.paint;
}
/**
* Sets the paint and regenerates the label.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPaint()
*/
public void setPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.paint = paint;
this.label = TextUtilities.createTextBlock(this.text, this.font,
this.paint);
}
/**
* Returns the tool tip text.
*
* @return The tool tip text (possibly <code>null</code>).
*
* @see #setToolTipText(String)
*/
public String getToolTipText() {
return this.toolTipText;
}
/**
* Sets the tool tip text.
*
* @param text the text (<code>null</code> permitted).
*
* @see #getToolTipText()
*/
public void setToolTipText(String text) {
this.toolTipText = text;
}
/**
* Returns the URL text.
*
* @return The URL text (possibly <code>null</code>).
*
* @see #setURLText(String)
*/
public String getURLText() {
return this.urlText;
}
/**
* Sets the URL text.
*
* @param text the text (<code>null</code> permitted).
*
* @see #getURLText()
*/
public void setURLText(String text) {
this.urlText = text;
}
/**
* Arranges the contents of the block, within the given constraints, and
* returns the block size.
*
* @param g2 the graphics device.
* @param constraint the constraint (<code>null</code> not permitted).
*
* @return The block size (in Java2D units, never <code>null</code>).
*/
public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) {
g2.setFont(this.font);
Size2D s = this.label.calculateDimensions(g2);
return new Size2D(calculateTotalWidth(s.getWidth()),
calculateTotalHeight(s.getHeight()));
}
/**
* Draws the block.
*
* @param g2 the graphics device.
* @param area the area.
*/
public void draw(Graphics2D g2, Rectangle2D area) {
draw(g2, area, null);
}
/**
* Draws the block within the specified area.
*
* @param g2 the graphics device.
* @param area the area.
* @param params ignored (<code>null</code> permitted).
*
* @return Always <code>null</code>.
*/
public Object draw(Graphics2D g2, Rectangle2D area, Object params) {
area = trimMargin(area);
drawBorder(g2, area);
area = trimBorder(area);
area = trimPadding(area);
// check if we need to collect chart entities from the container
EntityBlockParams ebp = null;
StandardEntityCollection sec = null;
Shape entityArea = null;
if (params instanceof EntityBlockParams) {
ebp = (EntityBlockParams) params;
if (ebp.getGenerateEntities()) {
sec = new StandardEntityCollection();
entityArea = (Shape) area.clone();
}
}
g2.setPaint(this.paint);
g2.setFont(this.font);
this.label.draw(g2, (float) area.getX(), (float) area.getY(),
TextBlockAnchor.TOP_LEFT);
BlockResult result = null;
if (ebp != null && sec != null) {
if (this.toolTipText != null || this.urlText != null) {
ChartEntity entity = new ChartEntity(entityArea,
this.toolTipText, this.urlText);
sec.add(entity);
result = new BlockResult();
result.setEntityCollection(sec);
}
}
return result;
}
/**
* Tests this <code>LabelBlock</code> for equality with an arbitrary
* object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (!(obj instanceof LabelBlock)) {
return false;
}
LabelBlock that = (LabelBlock) obj;
if (!this.text.equals(that.text)) {
return false;
}
if (!this.font.equals(that.font)) {
return false;
}
if (!PaintUtilities.equal(this.paint, that.paint)) {
return false;
}
if (!ObjectUtilities.equal(this.toolTipText, that.toolTipText)) {
return false;
}
if (!ObjectUtilities.equal(this.urlText, that.urlText)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a clone of this <code>LabelBlock</code> instance.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.paint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.paint = SerialUtilities.readPaint(stream);
}
}
| SpoonLabs/astor | examples/chart_11/source/org/jfree/chart/block/LabelBlock.java | Java | gpl-2.0 | 11,671 |
/*
* Copyright (c) 2009, 2018, 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 org.graalvm.compiler.jtt.optimize;
import org.junit.Test;
import org.graalvm.compiler.jtt.JTTTest;
/*
* Tests optimization of integer operations.
*/
public class VN_Int02 extends JTTTest {
public static int test(int arg) {
if (arg == 0) {
return shift0(arg + 10);
}
if (arg == 1) {
return shift1(arg + 10);
}
if (arg == 2) {
return shift2(arg + 10);
}
return 0;
}
public static int shift0(int x) {
int c = 1;
int t = x >> c;
int u = x >> c;
return t + u;
}
public static int shift1(int x) {
int c = 1;
int t = x >>> c;
int u = x >>> c;
return t + u;
}
public static int shift2(int x) {
int c = 1;
int t = x << c;
int u = x << c;
return t + u;
}
@Test
public void run0() throws Throwable {
runTest("test", 0);
}
@Test
public void run1() throws Throwable {
runTest("test", 1);
}
@Test
public void run2() throws Throwable {
runTest("test", 2);
}
}
| smarr/Truffle | compiler/src/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/optimize/VN_Int02.java | Java | gpl-2.0 | 2,359 |
/*
* Copyright (C) 2015 University of Dundee & Open Microscopy Environment.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package omero.cmd.graphs;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import ome.model.IObject;
import ome.services.util.ReadOnlyStatus;
import omero.cmd.HandleI.Cancel;
import omero.cmd.ERR;
import omero.cmd.Helper;
import omero.cmd.IRequest;
import omero.cmd.LegalGraphTargets;
import omero.cmd.LegalGraphTargetsResponse;
import omero.cmd.Response;
/**
* Query which model object classes are legal as targets for a request.
* @author [email protected]
* @since 5.1.4
*/
public class LegalGraphTargetsI extends LegalGraphTargets implements IRequest, ReadOnlyStatus.IsAware {
private final GraphRequestFactory graphRequestFactory;
private Helper helper;
/**
* Construct a new legal graph targets query.
* @param graphRequestFactory the graph request factory
*/
public LegalGraphTargetsI(GraphRequestFactory graphRequestFactory) {
this.graphRequestFactory = graphRequestFactory;
}
@Override
public Map<String, String> getCallContext() {
return null;
}
@Override
public void init(Helper helper) {
this.helper = helper;
helper.setSteps(1);
}
@Override
public Object step(int step) throws Cancel {
if (step == 0) {
try {
return graphRequestFactory.getLegalTargets(request.getClass());
} catch (Exception e) {
throw helper.cancel(new ERR(), e, "graph-no-targets");
}
} else {
final Exception e = new IllegalArgumentException("request has no step " + step);
throw helper.cancel(new ERR(), e, "bad-step");
}
}
@Override
public void finish() throws Cancel {
}
@Override
public void buildResponse(int step, Object object) {
helper.assertResponse(step);
if (step == 0) {
final LegalGraphTargetsResponse response = new LegalGraphTargetsResponse();
final Collection<Class<? extends IObject>> legalTargetClasses = (Collection<Class<? extends IObject>>) object;
response.targets = new ArrayList<String>(legalTargetClasses.size());
for (final Class<? extends IObject> legalTargetClass : legalTargetClasses) {
response.targets.add(legalTargetClass.getName());
}
helper.setResponseIfNull(response);
}
}
@Override
public Response getResponse() {
return helper.getResponse();
}
@Override
public boolean isReadOnly(ReadOnlyStatus readOnly) {
return true;
}
}
| knabar/openmicroscopy | components/blitz/src/omero/cmd/graphs/LegalGraphTargetsI.java | Java | gpl-2.0 | 3,419 |
package com.openlm.userimport.api.xml;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
/**
* This class represents...
*/
@XmlRootElement(name = "GROUP")
public class Group extends AbstractEntity {
public Group() {
}
public Group(String id) {
super(id);
}
@XmlAttribute
@Override
public void setId(String id) {
super.setId(id);
}
@XmlAttribute
@Override
public void setName(String name) {
super.setName(name);
}
@XmlAttribute
@Override
public void setEnabled(Boolean enabled) {
super.setEnabled(enabled);
}
@Override
public String getId() {
return super.getId();
}
@Override
public String getName() {
return super.getName();
}
@Override
public Boolean isEnabled() {
return super.isEnabled();
}
}
| adida/importUsers2OpenLM | src/main/java/com/openlm/userimport/api/xml/Group.java | Java | gpl-2.0 | 911 |
package net.demilich.metastone.game.events;
import net.demilich.metastone.game.GameContext;
import net.demilich.metastone.game.cards.QuestCard;
import net.demilich.metastone.game.entities.Entity;
public class QuestPlayedEvent extends GameEvent {
private final QuestCard questCard;
public QuestPlayedEvent(GameContext context, int playerId, QuestCard questCard) {
super(context, playerId, -1);
this.questCard = questCard;
}
@Override
public Entity getEventTarget() {
return getQuestCard();
}
@Override
public GameEventType getEventType() {
return GameEventType.SECRET_PLAYED;
}
public QuestCard getQuestCard() {
return questCard;
}
}
| doombubbles/metastonething | game/src/main/java/net/demilich/metastone/game/events/QuestPlayedEvent.java | Java | gpl-2.0 | 663 |
import java.awt.geom.Rectangle2D;
import java.awt.*;
import java.util.*;
public class HighlightableWord {
public String word;
public Rectangle2D rect;
public Color color;
public HighlightableWord(String txt, Rectangle2D rectangle){
word = txt;
rect = rectangle;
color = Color.black;
}
} | pallino7/opengazereyetrackingui | HighlightableWord.java | Java | gpl-2.0 | 301 |
package po;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class FarePO implements Serializable{
private OrganizationPO organication;
private ArrayList<EnplaningReceiptPO> enplaningReceiptPOList;
private ArrayList<EntrainingReceiptPO> entrainingReceiptPOList;
private ArrayList<EntruckingReceiptPO> entruckingReceiptPOList;
private double fare_sum;
private String ID;
private String date;
public FarePO(OrganizationPO organication,
ArrayList<EnplaningReceiptPO> enplaningReceiptPOList,
ArrayList<EntrainingReceiptPO> entrainingReceiptPOList,
ArrayList<EntruckingReceiptPO> entruckingReceiptPOList,
double fare_sum) {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
this.date = format.format(date);
this.organication = organication;
this.enplaningReceiptPOList = enplaningReceiptPOList;
this.entrainingReceiptPOList = entrainingReceiptPOList;
this.entruckingReceiptPOList = entruckingReceiptPOList;
this.fare_sum = fare_sum;
}
public double getMoney() {
return fare_sum;
}
public void setMoney(double money) {
this.fare_sum = money;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public ArrayList<EnplaningReceiptPO> getEnplaningReceiptPOList() {
return enplaningReceiptPOList;
}
public void setEnplaningReceiptPOList(
ArrayList<EnplaningReceiptPO> enplaningReceiptPOList) {
this.enplaningReceiptPOList = enplaningReceiptPOList;
}
public ArrayList<EntrainingReceiptPO> getEntrainingReceiptPOList() {
return entrainingReceiptPOList;
}
public void setEntrainingReceiptPOList(
ArrayList<EntrainingReceiptPO> entrainingReceiptPOList) {
this.entrainingReceiptPOList = entrainingReceiptPOList;
}
public ArrayList<EntruckingReceiptPO> getEntruckingReceiptPOList() {
return entruckingReceiptPOList;
}
public void setEntruckingReceiptPOList(
ArrayList<EntruckingReceiptPO> entruckingReceiptPOList) {
this.entruckingReceiptPOList = entruckingReceiptPOList;
}
public String getTime() {
return date;
}
public void setTime(String time) {
this.date = time;
}
public OrganizationPO getOrganication() {
return organication;
}
public void setOrganication(OrganizationPO organication) {
this.organication = organication;
}
}
| Disguiser-w/SE2 | 12.09DDL/ELS_SERVICE/src/main/java/po/FarePO.java | Java | gpl-2.0 | 2,406 |
package pls.analysis;
import java.util.Map;
import java.util.Vector;
import pls.shared.MLFuncs;
import Jama.Matrix;
import com.jmatio.io.MatFileFilter;
import com.jmatio.types.MLArray;
import com.jmatio.types.MLDouble;
import extern.NewMatFileReader;
public class ConcatenateFmriBehavioralDatamat extends ConcatenateDatamat {
public ConcatenateFmriBehavioralDatamat(Vector<String[]> sessionProfiles, int[] conditionSelection, String behaviorFilename) throws Exception {
super(sessionProfiles, conditionSelection);
loadBehavDataList(behaviorFilename);
}
public void stackDatamat() throws Exception {
totalEvents = MLFuncs.sum(subjectGroup) * numConditions;
datamat = new Matrix(totalEvents, winSize * numVoxels);
int firstRow = 0;
int[] firstConditionOrder = null;
int count = 0;
// Go through each subject which is represented by each profile
for(int i = 0; i < numGroups; i++) {
Matrix groupTempNewStDatamat = new Matrix(0, winSize * numVoxels);
int[] groupTempNewEventList = null;
int[] groupFirstConditionOrder = null;
for(int j = 0; j < sessionGroup[i]; j++, count++) {
String datamatFilename = getDatamatFilename(count);
Map<String, MLArray> datamatMap = new NewMatFileReader(datamatFilename, new MatFileFilter(new String[]{"st_datamat"})).getContent();
double[][] stDatamat = ((MLDouble)datamatMap.get("st_datamat")).getArray();
int[] thisCoords = getStCoords(count);
thisCoords = MLFuncs.subtract(thisCoords, 1); // make coords 0-relative
int[] coordIdx = MLFuncs.find(MLFuncs.getItemsAtIndices(M, thisCoords), numProfiles);
int numRuns = getEventList(count).length;
double createVer = getCreateVer(count);
int lastRow = numRuns + firstRow - 1;
int[] behavMask = getBehavMask(stDatamat);
// get subj_name for designPLS
int[] thisSubjOrder = new int[numRuns];
int firstCond = 0;
int jj = 0;
while(firstCond < numRuns) {
thisSubjOrder[firstCond] = 1;
firstCond += numConditions;
if(createVer < 4.0512201) {
subjectName.add("Subj" + (count + 1) + "Run" + (jj + 1));
} else {
subjectName.add("Subj" + (count + 1));
}
jj++;
}
firstConditionOrder = MLFuncs.append(firstConditionOrder, thisSubjOrder);
groupFirstConditionOrder = MLFuncs.append(groupFirstConditionOrder, thisSubjOrder); // For behav pls
// Stack datamat
double[][] tempDatamat = stDatamat;
double[][] tempNewStDatamat = new double[numRuns][winSize * numVoxels];
for(int i2 = 0; i2 < numRuns; i2++) {
int count2 = 0;
for(int j2 = 0; j2 < numVoxels; j2++) {
for(int k2 = 0; k2 < winSize; k2++, count2++) {
tempNewStDatamat[i2][count2] = tempDatamat[i2][(winSize * coordIdx[j2]) + k2];
}
}
}
int[] tempEventList = getEventList(j);
// Intentionally reverse the order to each condition in each run, if behavpls
// because in behavpls, the whole thing will be then re-order again
tempNewStDatamat = MLFuncs.getRows(tempNewStDatamat, behavMask);
tempEventList = MLFuncs.getItemsAtIndices(tempEventList, behavMask);
groupTempNewStDatamat = MLFuncs.append(groupTempNewStDatamat, new Matrix(tempNewStDatamat));
groupTempNewEventList = MLFuncs.append(groupTempNewEventList, tempEventList);
datamat.setMatrix(firstRow, lastRow, 0, winSize * numVoxels - 1, new Matrix(tempNewStDatamat));
eventList = MLFuncs.append(eventList, getEventList(count));
firstRow = lastRow + 1;
}
int[] groupSubjectMask = null;
for(int ii = 0; ii < numConditions; ii++) {
groupSubjectMask = MLFuncs.append(groupSubjectMask, MLFuncs.find(groupFirstConditionOrder, 1));
int end = groupFirstConditionOrder.length - 1;
int[] lastItem = new int[]{groupFirstConditionOrder[end]};
groupFirstConditionOrder = MLFuncs.append(lastItem, MLFuncs.getItemsAtIndices(groupFirstConditionOrder, MLFuncs.range(0, end - 1)));
}
groupTempNewStDatamat = MLFuncs.getRows(groupTempNewStDatamat, groupSubjectMask);
groupTempNewEventList = MLFuncs.getItemsAtIndices(groupTempNewEventList, groupSubjectMask);
newDataList.add(groupTempNewStDatamat);
numSubjectList = MLFuncs.append(numSubjectList, MLFuncs.sum(groupFirstConditionOrder));
eventListList.add(groupTempNewEventList);
}
numBehavSubj = MLFuncs.sum(firstConditionOrder);
}
public void deselectConditions() {
for(int i = 0; i < eventListList.size(); i++) {
int[] tempNewEventList = eventListList.get(i);
MaskEventList fmel = new MaskEventList(tempNewEventList, conditionSelection);
tempNewEventList = fmel.eventList;
mask = fmel.mask;
eventLength = fmel.eventLength;
eventListList.setElementAt(tempNewEventList, i);
datamat = newDataList.get(i);
newDataList.setElementAt(MLFuncs.getRows(datamat, mask), i);
}
datamat = null;
eventList = null;
for(int i = 0; i < numGroups; i++) {
datamat = MLFuncs.append(datamat, newDataList.get(i));
eventList = MLFuncs.append(eventList, eventListList.get(i));
}
}
/**
* Stack behavdata and get behavmask (re-order for each session file
* to make it 'each condition in each run (yes, reversed)'
*/
private int[] getBehavMask(double[][] stDatamat) {
int m = stDatamat.length;
int[] behavMask1 = MLFuncs.range(0, m - 1);
int nrr = m / numConditions;
int[][] behavMask2 = MLFuncs.reshape(new int[][]{behavMask1}, nrr, numConditions);
int[][] behavMask3 = MLFuncs.transpose(behavMask2);
return MLFuncs.flattenHorizontally(behavMask3);
}
private void loadBehavDataList(String behaviorFilename) throws Exception {
double[][] data = MLFuncs.load(behaviorFilename);
if(data == null) {
throw new Exception("Behaviour data is corrupt");
}
behavData = new Matrix(data);
int currentRow = 0;
for(int i = 0; i < numGroups; i++) {
int currBehavDataSize = subjectGroup[i] * numConditions - 1;
int[] currBehavDataRange = MLFuncs.range(currentRow, currentRow + currBehavDataSize);
behavDataList.add(MLFuncs.getRows(behavData, currBehavDataRange));
currentRow += currBehavDataSize + 1;
}
}
}
| Olshansk/PLSNPAIRS-Thesis | pls/analysis/ConcatenateFmriBehavioralDatamat.java | Java | gpl-2.0 | 6,394 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.command;
/**
*
* @author <a href="mailto:[email protected]">DJ Gregor</a>
*/
public class NodeListCommand {
private String m_nodename = null;
private String m_iplike = null;
private String m_maclike = null;
private String m_foreignsource = null;
private Integer m_service = null;
private String m_snmpParm = null;
private String m_snmpParmValue = null;
private String m_snmpParmMatchType = null;
private String[] m_category1 = null;
private String[] m_category2 = null;
private String m_statusViewName = null;
private String m_statusSite = null;
private String m_statusRowLabel = null;
private boolean m_nodesWithOutages = false;
private boolean m_nodesWithDownAggregateStatus = false;
private boolean m_listInterfaces = false;
private int m_nodeId = -1;
public void setNodeId(int nodeId) {
m_nodeId = nodeId;
}
public int getNodeId() {
return m_nodeId;
}
public boolean hasNodeId() {
return m_nodeId >= 0;
}
public void setNodename(String nodename) {
m_nodename = nodename;
}
public String getNodename() {
return m_nodename;
}
public boolean hasNodename() {
return m_nodename != null;
}
public void setIplike(String iplike) {
m_iplike = iplike;
}
public String getIplike() {
return m_iplike;
}
public boolean hasIplike() {
return m_iplike != null;
}
public void setMaclike(String maclike) {
m_maclike = maclike;
}
public String getMaclike() {
return m_maclike;
}
public boolean hasMaclike() {
return m_maclike != null;
}
public void setForeignSource(String foreignSourceLike) {
m_foreignsource = foreignSourceLike;
}
public String getForeignSource() {
return m_foreignsource;
}
public boolean hasForeignSource() {
return m_foreignsource != null;
}
public void setService(Integer service) {
m_service = service;
}
public Integer getService() {
return m_service;
}
public boolean hasService() {
return m_service != null;
}
public void setSnmpParm(String snmpParm) {
m_snmpParm = snmpParm;
}
public String getSnmpParm() {
return m_snmpParm;
}
public boolean hasSnmpParm() {
return m_snmpParm != null;
}
public void setSnmpParmValue(String snmpParmValue) {
m_snmpParmValue = snmpParmValue;
}
public String getSnmpParmValue() {
return m_snmpParmValue;
}
public boolean hasSnmpParmValue() {
return m_snmpParmValue != null;
}
public void setSnmpParmMatchType(String snmpParmMatchType) {
m_snmpParmMatchType = snmpParmMatchType;
}
public String getSnmpParmMatchType() {
return m_snmpParmMatchType;
}
public boolean hasSnmpParmMatchType() {
return m_snmpParmMatchType != null;
}
public void setCategory1(String[] category1) {
m_category1 = category1;
}
public String[] getCategory1() {
return m_category1;
}
public boolean hasCategory1() {
return m_category1 != null && m_category1.length > 0;
}
public void setCategory2(String[] category2) {
m_category2 = category2;
}
public String[] getCategory2() {
return m_category2;
}
public boolean hasCategory2() {
return m_category2 != null && m_category2.length > 0;
}
public void setStatusViewName(String statusViewName) {
m_statusViewName = statusViewName;
}
public String getStatusViewName() {
return m_statusViewName;
}
public boolean hasStatusViewName() {
return m_statusViewName != null;
}
public void setStatusSite(String statusSite) {
m_statusSite = statusSite;
}
public String getStatusSite() {
return m_statusSite;
}
public boolean hasStatusSite() {
return m_statusSite != null;
}
public void setStatusRowLabel(String statusRowLabel) {
m_statusRowLabel = statusRowLabel;
}
public String getStatusRowLabel() {
return m_statusRowLabel;
}
public boolean hasStatusRowLabel() {
return m_statusRowLabel != null;
}
public void setNodesWithOutages(boolean nodesWithOutages) {
m_nodesWithOutages = nodesWithOutages;
}
public boolean getNodesWithOutages() {
return m_nodesWithOutages;
}
public void setNodesWithDownAggregateStatus(boolean nodesWithDownAggregateStatus) {
m_nodesWithDownAggregateStatus = nodesWithDownAggregateStatus;
}
public boolean getNodesWithDownAggregateStatus() {
return m_nodesWithDownAggregateStatus;
}
public void setListInterfaces(boolean listInterfaces) {
m_listInterfaces = listInterfaces;
}
public boolean getListInterfaces() {
return m_listInterfaces;
}
} | tharindum/opennms_dashboard | opennms-webapp/src/main/java/org/opennms/web/command/NodeListCommand.java | Java | gpl-2.0 | 6,256 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao.support;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.opennms.core.utils.InetAddressUtils;
import org.opennms.core.utils.IntSet;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.config.CollectdConfigFactory;
import org.opennms.netmgt.config.DataCollectionConfigDao;
import org.opennms.netmgt.config.StorageStrategy;
import org.opennms.netmgt.config.datacollection.ResourceType;
import org.opennms.netmgt.dao.LocationMonitorDao;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.dao.ResourceDao;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsLocationMonitor;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsResource;
import org.opennms.netmgt.model.OnmsResourceType;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.util.Assert;
/**
* Encapsulates all SNMP performance reporting for the web user interface.
*
* @author <a href="mailto:[email protected]">Seth Leger </a>
* @author <a href="mailto:[email protected]">Lawrence Karnowski </a>
* @author <a href="mailto:[email protected]">DJ Gregor</a>
*/
public class DefaultResourceDao implements ResourceDao, InitializingBean {
/**
* File name to look for in a resource directory for string attributes.
*/
public static final String STRINGS_PROPERTIES_FILE_NAME = "strings.properties";
/** Constant <code>INTERFACE_GRAPH_TYPE="interface"</code> */
public static final String INTERFACE_GRAPH_TYPE = "interface";
/** Constant <code>RESPONSE_DIRECTORY="response"</code> */
public static final String RESPONSE_DIRECTORY = "response";
/** Constant <code>SNMP_DIRECTORY="snmp"</code> */
public static final String SNMP_DIRECTORY = "snmp";
public static final String FOREIGN_SOURCE_DIRECTORY = "fs";
private NodeDao m_nodeDao;
private LocationMonitorDao m_locationMonitorDao;
private File m_rrdDirectory;
private CollectdConfigFactory m_collectdConfig;
private DataCollectionConfigDao m_dataCollectionConfigDao;
private Map<String, OnmsResourceType> m_resourceTypes;
private NodeResourceType m_nodeResourceType;
private DomainResourceType m_domainResourceType;
private NodeSourceResourceType m_nodeSourceResourceType;
/**
* <p>Constructor for DefaultResourceDao.</p>
*/
public DefaultResourceDao() {
}
/**
* <p>setRrdDirectory</p>
*
* @param rrdDirectory a {@link java.io.File} object.
*/
public void setRrdDirectory(File rrdDirectory) {
m_rrdDirectory = rrdDirectory;
}
/**
* <p>getRrdDirectory</p>
*
* @return a {@link java.io.File} object.
*/
@Override
public File getRrdDirectory() {
return m_rrdDirectory;
}
/** {@inheritDoc} */
@Override
public File getRrdDirectory(boolean verify) {
if (verify && !getRrdDirectory().isDirectory()) {
throw new ObjectRetrievalFailureException("RRD directory does not exist: " + getRrdDirectory().getAbsolutePath(), getRrdDirectory());
}
return getRrdDirectory();
}
/**
* <p>getDataCollectionConfig</p>
*
* @return a {@link org.opennms.netmgt.config.DataCollectionConfigDao} object.
*/
public DataCollectionConfigDao getDataCollectionConfigDao() {
return m_dataCollectionConfigDao;
}
/**
* <p>setDataCollectionConfig</p>
*
* @param dataCollectionConfigDao a {@link org.opennms.netmgt.config.DataCollectionConfigDao} object.
*/
public void setDataCollectionConfigDao(DataCollectionConfigDao dataCollectionConfigDao) {
m_dataCollectionConfigDao = dataCollectionConfigDao;
}
/**
* <p>getNodeDao</p>
*
* @return a {@link org.opennms.netmgt.dao.NodeDao} object.
*/
public NodeDao getNodeDao() {
return m_nodeDao;
}
/**
* <p>setNodeDao</p>
*
* @param nodeDao a {@link org.opennms.netmgt.dao.NodeDao} object.
*/
public void setNodeDao(NodeDao nodeDao) {
m_nodeDao = nodeDao;
}
/**
* <p>getCollectdConfig</p>
*
* @return a {@link org.opennms.netmgt.config.CollectdConfigFactory} object.
*/
public CollectdConfigFactory getCollectdConfig() {
return m_collectdConfig;
}
/**
* <p>setCollectdConfig</p>
*
* @param collectdConfig a {@link org.opennms.netmgt.config.CollectdConfigFactory} object.
*/
public void setCollectdConfig(CollectdConfigFactory collectdConfig) {
m_collectdConfig = collectdConfig;
}
/**
* <p>getLocationMonitorDao</p>
*
* @return a {@link org.opennms.netmgt.dao.LocationMonitorDao} object.
*/
public LocationMonitorDao getLocationMonitorDao() {
return m_locationMonitorDao;
}
/**
* <p>setLocationMonitorDao</p>
*
* @param locationMonitorDao a {@link org.opennms.netmgt.dao.LocationMonitorDao} object.
*/
public void setLocationMonitorDao(LocationMonitorDao locationMonitorDao) {
m_locationMonitorDao = locationMonitorDao;
}
/**
* <p>afterPropertiesSet</p>
*
* @throws java.io.IOException if any.
*/
@Override
public void afterPropertiesSet() throws IOException {
if (m_rrdDirectory == null) {
throw new IllegalStateException("rrdDirectory property has not been set");
}
if (m_collectdConfig == null) {
throw new IllegalStateException("collectdConfig property has not been set");
}
if (m_dataCollectionConfigDao == null) {
throw new IllegalStateException("dataCollectionConfig property has not been set");
}
if (m_nodeDao == null) {
throw new IllegalStateException("nodeDao property has not been set");
}
if (m_locationMonitorDao == null) {
throw new IllegalStateException("locationMonitorDao property has not been set");
}
initResourceTypes();
}
private void initResourceTypes() throws IOException {
Map<String, OnmsResourceType> resourceTypes;
resourceTypes = new LinkedHashMap<String, OnmsResourceType>();
OnmsResourceType resourceType;
resourceType = new NodeSnmpResourceType(this);
resourceTypes.put(resourceType.getName(), resourceType);
resourceType = new InterfaceSnmpResourceType(this, m_nodeDao);
resourceTypes.put(resourceType.getName(), resourceType);
resourceType = new ResponseTimeResourceType(this, m_nodeDao);
resourceTypes.put(resourceType.getName(), resourceType);
resourceType = new DistributedStatusResourceType(this, m_locationMonitorDao);
resourceTypes.put(resourceType.getName(), resourceType);
resourceTypes.putAll(getGenericIndexResourceTypes());
m_nodeResourceType = new NodeResourceType(this);
resourceTypes.put(m_nodeResourceType.getName(), m_nodeResourceType);
m_domainResourceType = new DomainResourceType(this);
resourceTypes.put(m_domainResourceType.getName(), m_domainResourceType);
m_nodeSourceResourceType = new NodeSourceResourceType(this, m_nodeDao);
resourceTypes.put(m_nodeSourceResourceType.getName(), m_nodeSourceResourceType);
m_resourceTypes = resourceTypes;
}
private Map<String, GenericIndexResourceType> getGenericIndexResourceTypes() {
Map<String, GenericIndexResourceType> resourceTypes;
resourceTypes = new LinkedHashMap<String, GenericIndexResourceType>();
Map<String, ResourceType> configuredResourceTypes = m_dataCollectionConfigDao.getConfiguredResourceTypes();
List<ResourceType> resourceTypeList = new LinkedList<ResourceType>(configuredResourceTypes.values());
Collections.sort(resourceTypeList, new Comparator<ResourceType>() {
@Override
public int compare(ResourceType r0, ResourceType r1) {
return r0.getLabel().compareTo(r1.getLabel());
}
});
for (ResourceType resourceType : resourceTypeList) {
String className = resourceType.getStorageStrategy().getClazz();
Class<?> cinst;
try {
cinst = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new ObjectRetrievalFailureException(StorageStrategy.class, className,
"Could not load class '" + className + "' for resource type '" + resourceType.getName() + "'", e);
}
StorageStrategy storageStrategy;
try {
storageStrategy = (StorageStrategy) cinst.newInstance();
} catch (InstantiationException e) {
throw new ObjectRetrievalFailureException(StorageStrategy.class, className,
"Could not instantiate class '" + className + "' for resource type '" + resourceType.getName() + "'", e);
} catch (IllegalAccessException e) {
throw new ObjectRetrievalFailureException(StorageStrategy.class, className,
"Could not instantiate class '" + className + "' for resource type '" + resourceType.getName() + "'", e);
}
storageStrategy.setResourceTypeName(resourceType.getName());
GenericIndexResourceType genericIndexResourceType =
new GenericIndexResourceType(this,
resourceType.getName(),
resourceType.getLabel(),
resourceType.getResourceLabel(),
storageStrategy);
resourceTypes.put(genericIndexResourceType.getName(), genericIndexResourceType);
}
return resourceTypes;
}
/**
* <p>getResourceTypes</p>
*
* @return a {@link java.util.Collection} object.
*/
@Override
public Collection<OnmsResourceType> getResourceTypes() {
return m_resourceTypes.values();
}
/**
* Fetch a specific resource by string ID.
* @return Resource or null if resource cannot be found.
* @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern
* @throws ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource
*/
@Override
public OnmsResource getResourceById(String id) {
OnmsResource resource = null;
Pattern p = Pattern.compile("([^\\[]+)\\[([^\\]]*)\\](?:\\.|$)");
Matcher m = p.matcher(id);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String resourceTypeName = DefaultResourceDao.decode(m.group(1));
String resourceName = DefaultResourceDao.decode(m.group(2));
try {
if (resource == null) {
resource = getTopLevelResource(resourceTypeName, resourceName);
} else {
resource = getChildResource(resource, resourceTypeName, resourceName);
}
} catch (Throwable e) {
log().warn("Could not get resource for resource ID \"" + id + "\"", e);
return null;
}
m.appendReplacement(sb, "");
}
m.appendTail(sb);
if (sb.length() > 0) {
log().warn("resource ID '" + id + "' does not match pattern '"
+ p.toString() + "' at '"
+ sb + "'");
return null;
} else {
return resource;
}
}
/**
* Fetch a specific list of resources by string ID.
* @return Resources or null if resources cannot be found.
* @throws IllegalArgumentException When the resource ID string does not match the expected regex pattern
* @throws ObjectRetrievalFailureException If any exceptions are thrown while searching for the resource
*/
@Override
public List<OnmsResource> getResourceListById(String id) throws IllegalArgumentException, ObjectRetrievalFailureException {
OnmsResource topLevelResource = null;
Pattern p = Pattern.compile("([^\\[]+)\\[([^\\]]*)\\](?:\\.|$)");
Matcher m = p.matcher(id);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String resourceTypeName = DefaultResourceDao.decode(m.group(1));
String resourceName = DefaultResourceDao.decode(m.group(2));
try {
if (topLevelResource == null) {
topLevelResource = getTopLevelResource(resourceTypeName, resourceName);
} else {
return getChildResourceList(topLevelResource);
}
} catch (Throwable e) {
throw new ObjectRetrievalFailureException(OnmsResource.class, id, "Could not get resource for resource ID '" + id + "'", e);
}
m.appendReplacement(sb, "");
}
m.appendTail(sb);
if (sb.length() > 0) {
throw new IllegalArgumentException("resource ID '" + id
+ "' does not match pattern '"
+ p.toString() + "' at '"
+ sb + "'");
}
return null;
}
/**
* <p>getTopLevelResource</p>
*
* @param resourceType a {@link java.lang.String} object.
* @param resource a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsResource} object.
*/
protected OnmsResource getTopLevelResource(String resourceType, String resource) throws ObjectRetrievalFailureException {
if ("node".equals(resourceType)) {
return getNodeEntityResource(resource);
} else if ("nodeSource".equals(resourceType)) {
return getForeignSourceNodeEntityResource(resource);
} else if ("domain".equals(resourceType)) {
return getDomainEntityResource(resource);
} else {
throw new ObjectRetrievalFailureException("Top-level resource type of '" + resourceType + "' is unknown", resourceType);
}
}
/**
* <p>getChildResource</p>
*
* @param parentResource a {@link org.opennms.netmgt.model.OnmsResource} object.
* @param resourceType a {@link java.lang.String} object.
* @param resource a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsResource} object.
*/
protected OnmsResource getChildResource(OnmsResource parentResource, String resourceType, String resource) {
for (OnmsResource r : parentResource.getChildResources()) {
if (resourceType.equals(r.getResourceType().getName())
&& resource.equals(r.getName())) {
log().debug("getChildResource: returning resource " + r);
return r;
}
}
throw new ObjectRetrievalFailureException(OnmsResource.class, resourceType + "/" + resource, "Could not find child resource '"
+ resource + "' with resource type '" + resourceType + "' on resource '" + resource + "'", null);
}
/**
* <p>getChildResourceList</p>
*
* @param parentResource a {@link org.opennms.netmgt.model.OnmsResource} object.
* @return a {@link java.util.List} object.
*/
protected List<OnmsResource> getChildResourceList(OnmsResource parentResource) {
if (log().isDebugEnabled()) {
log().debug("DefaultResourceDao: getChildResourceList for " + parentResource.toString());
}
return parentResource.getChildResources();
}
/**
* Returns a list of resources for a node.
*
* XXX It does not currently fully check that an IP address that is found to have
* distributed response time data is in the database on the proper node so it can have false positives.
*
* @return a {@link java.util.List} object.
*/
@Override
public List<OnmsResource> findNodeResources() {
List<OnmsResource> resources = new LinkedList<OnmsResource>();
IntSet snmpNodes = findSnmpNodeDirectories();
Set<String> responseTimeInterfaces = findChildrenMatchingFilter(new File(getRrdDirectory(), RESPONSE_DIRECTORY), RrdFileConstants.INTERFACE_DIRECTORY_FILTER);
Set<String> distributedResponseTimeInterfaces = findChildrenChildrenMatchingFilter(new File(new File(getRrdDirectory(), RESPONSE_DIRECTORY), "distributed"), RrdFileConstants.INTERFACE_DIRECTORY_FILTER);
// Only returns non-deleted nodes to fix NMS-2977
// http://issues.opennms.org/browse/NMS-2977
Collection<Integer> nodeIds = m_nodeDao.getNodeIds();
IntSet nodesFound = new IntSet();
for (Integer nodeId : nodeIds) {
if (nodesFound.contains(nodeId.intValue())) {
continue;
}
boolean found = false;
OnmsNode node = m_nodeDao.get(nodeId);
if (snmpNodes.contains(nodeId)) {
found = true;
} else if ((responseTimeInterfaces.size() > 0 || distributedResponseTimeInterfaces.size() > 0) && (node.getForeignSource() == null || node.getForeignId() == null)) {
for (final OnmsIpInterface ip : m_nodeDao.get(nodeId).getIpInterfaces()) {
final String addr = InetAddressUtils.str(ip.getIpAddress());
if (responseTimeInterfaces.contains(addr) || distributedResponseTimeInterfaces.contains(addr)) {
found = true;
break;
}
}
}
if (found) {
resources.add(m_nodeResourceType.createChildResource(node));
nodesFound.add(nodeId);
}
}
return resources;
}
/**
* Returns a list of resources for a node in a foreign source.
*
* XXX It does not currently fully check that an IP address that is found to have
* distributed response time data is in the database on the proper node so it can have false positives.
*
* @return a {@link java.util.List} object.
*/
public List<OnmsResource> findNodeSourceResources() {
List<OnmsResource> resources = new LinkedList<OnmsResource>();
Set<String> nodeSources = findNodeSourceDirectories();
Set<String> responseTimeInterfaces = findChildrenMatchingFilter(new File(getRrdDirectory(), RESPONSE_DIRECTORY), RrdFileConstants.INTERFACE_DIRECTORY_FILTER);
Set<String> distributedResponseTimeInterfaces = findChildrenChildrenMatchingFilter(new File(new File(getRrdDirectory(), RESPONSE_DIRECTORY), "distributed"), RrdFileConstants.INTERFACE_DIRECTORY_FILTER);
List<OnmsNode> nodes = m_nodeDao.findAll();
IntSet nodesFound = new IntSet();
for (OnmsNode node : nodes) {
if (nodesFound.contains(node.getId())) {
continue;
}
boolean found = false;
if (node.getForeignSource() != null && node.getForeignId() != null) {
if (nodeSources.contains(node.getForeignSource() + ":" + node.getForeignId())) {
found = true;
} else if (responseTimeInterfaces.size() > 0 || distributedResponseTimeInterfaces.size() > 0) {
for (final OnmsIpInterface ip : node.getIpInterfaces()) {
final String addr = InetAddressUtils.str(ip.getIpAddress());
if (responseTimeInterfaces.contains(addr) || distributedResponseTimeInterfaces.contains(addr)) {
found = true;
break;
}
}
}
}
if (found) {
resources.add(m_nodeSourceResourceType.createChildResource(node.getForeignSource() + ":" + node.getForeignId()));
nodesFound.add(node.getId());
log().debug("findNodeSourceResources: adding resource for " + node.getForeignSource() + ":" + node.getForeignId());
}
}
return resources;
}
/**
* Returns a list of resources for domains.
*
* @return a {@link java.util.List} object.
*/
@Override
public List<OnmsResource> findDomainResources() {
List<OnmsResource> resources = new LinkedList<OnmsResource>();
File snmp = new File(getRrdDirectory(), SNMP_DIRECTORY);
// Get all of the non-numeric directory names in the RRD directory; these
// are the names of the domains that have performance data
File[] domainDirs = snmp.listFiles(RrdFileConstants.DOMAIN_DIRECTORY_FILTER);
if (domainDirs != null && domainDirs.length > 0) {
for (File domainDir : domainDirs) {
resources.add(m_domainResourceType.createChildResource(domainDir.getName()));
}
}
return resources;
}
/**
* <p>getNodeEntityResource</p>
*
* @param resource a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsResource} object.
*/
protected OnmsResource getNodeEntityResource(String resource) {
int nodeId;
try {
nodeId = Integer.parseInt(resource);
} catch (NumberFormatException e) {
throw new ObjectRetrievalFailureException(OnmsNode.class, resource, "Top-level resource of resource type node is not numeric: " + resource, null);
}
OnmsNode node = m_nodeDao.get(nodeId);
if (node == null) {
throw new ObjectRetrievalFailureException(OnmsNode.class, resource, "Top-level resource of resource type node could not be found: " + resource, null);
}
OnmsResource onmsResource = getResourceForNode(node);
return onmsResource;
}
/**
* <p>getForeignSourceNodeEntityResource</p>
*
* @param resource a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsResource} object.
*/
protected OnmsResource getForeignSourceNodeEntityResource(String resource) {
File idDir = new File(getRrdDirectory(), SNMP_DIRECTORY + File.separator + ResourceTypeUtils.getRelativeNodeSourceDirectory(resource).toString());
if (idDir.isDirectory() && RrdFileConstants.NODESOURCE_DIRECTORY_FILTER.accept(idDir)) {
return m_nodeSourceResourceType.createChildResource(resource);
} else {
log().debug("resource " + resource + " not found by foreign source/foreignId. Trying as a node resource instead...");
String[] ident = resource.split(":");
OnmsNode node = m_nodeDao.findByForeignId(ident[0], ident[1]);
if (node == null) {
throw new ObjectRetrievalFailureException(OnmsNode.class, resource, "Top-level resource of resource type node could not be found: " + resource, null);
}
OnmsResource onmsResource = getResourceForNode(node);
return onmsResource;
}
}
/**
* <p>getDomainEntityResource</p>
*
* @param domain a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsResource} object.
*/
protected OnmsResource getDomainEntityResource(String domain) {
File directory = new File(getRrdDirectory(), SNMP_DIRECTORY);
File domainDir = new File(directory, domain);
if (!domainDir.isDirectory()) {
throw new ObjectRetrievalFailureException(OnmsResource.class, domain, "Domain not found due to domain RRD directory not existing or not a directory: " + domainDir.getAbsolutePath(), null);
}
if (!RrdFileConstants.DOMAIN_DIRECTORY_FILTER.accept(domainDir)) {
throw new ObjectRetrievalFailureException(OnmsResource.class, domain, "Domain not found due to domain RRD directory not matching the domain directory filter: " + domainDir.getAbsolutePath(), null);
}
return m_domainResourceType.createChildResource(domain);
}
private IntSet findSnmpNodeDirectories() {
IntSet nodes = new IntSet();
File directory = new File(getRrdDirectory(), SNMP_DIRECTORY);
File[] nodeDirs = directory.listFiles(RrdFileConstants.NODE_DIRECTORY_FILTER);
if (nodeDirs == null || nodeDirs.length == 0) {
return nodes;
}
for (File nodeDir : nodeDirs) {
try {
int nodeId = Integer.parseInt(nodeDir.getName());
nodes.add(nodeId);
} catch (NumberFormatException e) {
// skip... don't add
}
}
return nodes;
}
/**
* <p>findNodeSourceDirectories</p>
*
* @return a Set<String> of directory names.
*/
public Set<String> findNodeSourceDirectories() {
Set<String> nodeSourceDirectories = new HashSet<String>();
File snmpDir = new File(getRrdDirectory(), SNMP_DIRECTORY);
File forSrcDir = new File(snmpDir, FOREIGN_SOURCE_DIRECTORY);
File[] sourceDirs = forSrcDir.listFiles(RrdFileConstants.SOURCE_DIRECTORY_FILTER);
if (sourceDirs != null) {
for (File sourceDir : sourceDirs) {
File [] ids = sourceDir.listFiles(RrdFileConstants.NODESOURCE_DIRECTORY_FILTER);
for (File id : ids) {
nodeSourceDirectories.add(sourceDir.getName() + ":" + id.getName());
}
}
}
return nodeSourceDirectories;
}
private static Set<String> findChildrenMatchingFilter(File directory, FileFilter filter) {
Set<String> children = new HashSet<String>();
File[] nodeDirs = directory.listFiles(filter);
if (nodeDirs == null || nodeDirs.length == 0) {
return children;
}
for (File nodeDir : nodeDirs) {
children.add(nodeDir.getName());
}
return children;
}
/**
*
* @param directory
* @param filter
* @return
*
* XXX should include the location monitor in the returned data
*/
private static Set<String> findChildrenChildrenMatchingFilter(File directory, FileFilter filter) {
Set<String> children = new HashSet<String>();
File[] locationMonitorDirs = directory.listFiles();
if (locationMonitorDirs == null) {
return children;
}
for (File locationMonitorDir : locationMonitorDirs) {
File[] intfDirs = locationMonitorDir.listFiles(filter);
if (intfDirs == null || intfDirs.length == 0) {
continue;
}
for (File intfDir : intfDirs) {
children.add(intfDir.getName());
}
}
return children;
}
/**
* Encapsulate the deprecated decode method to fix it in one place.
*
* @param string
* string to be decoded
* @return decoded string
*/
public static String decode(String string) {
try {
return URLDecoder.decode(string, "UTF-8");
} catch (UnsupportedEncodingException e) {
// UTF-8 should *never* throw this
throw new UndeclaredThrowableException(e);
}
}
/** {@inheritDoc} */
@Override
public OnmsResource getResourceForNode(OnmsNode node) {
Assert.notNull(node, "node argument must not be null");
return m_nodeResourceType.createChildResource(node);
}
private OnmsResource getChildResourceForNode(OnmsNode node, String resourceTypeName, String resourceName) {
OnmsResource nodeResource = getResourceForNode(node);
if (nodeResource == null) {
return null;
}
List<OnmsResource> childResources = nodeResource.getChildResources();
for (OnmsResource childResource : childResources) {
if (!resourceTypeName.equals(childResource.getResourceType().getName())) {
continue;
}
if (resourceName.equals(childResource.getName())) {
return childResource;
}
}
return null;
}
/**
* @return OnmsResource for the <code>responseTime</code> resource on the interface or
* null if the <code>responseTime</code> resource cannot be found for the given IP interface.
*/
@Override
public OnmsResource getResourceForIpInterface(OnmsIpInterface ipInterface) {
Assert.notNull(ipInterface, "ipInterface argument must not be null");
Assert.notNull(ipInterface.getNode(), "getNode() on ipInterface must not return null");
final String ipAddress = InetAddressUtils.str(ipInterface.getIpAddress());
return getChildResourceForNode(ipInterface.getNode(), "responseTime", ipAddress);
}
/**
* @return OnmsResource for the <code>distributedStatus</code> resource on the interface or
* null if the <code>distributedStatus</code> resource cannot be found for the given IP interface.
*/
@Override
public OnmsResource getResourceForIpInterface(OnmsIpInterface ipInterface, OnmsLocationMonitor locMon) {
Assert.notNull(ipInterface, "ipInterface argument must not be null");
Assert.notNull(locMon, "locMon argument must not be null");
Assert.notNull(ipInterface.getNode(), "getNode() on ipInterface must not return null");
final String ipAddress = InetAddressUtils.str(ipInterface.getIpAddress());
return getChildResourceForNode(ipInterface.getNode(), "distributedStatus", locMon.getId() + File.separator + ipAddress);
}
/**
* <p>findTopLevelResources</p>
*
* @return a {@link java.util.List} object.
*/
@Override
public List<OnmsResource> findTopLevelResources() {
List<OnmsResource> resources = new ArrayList<OnmsResource>();
resources.addAll(findNodeResources());
resources.addAll(findNodeSourceResources());
resources.addAll(findDomainResources());
return resources;
}
private static ThreadCategory log() {
return ThreadCategory.getInstance(DefaultResourceDao.class);
}
}
| peternixon/opennms-mirror | opennms-dao/src/main/java/org/opennms/netmgt/dao/support/DefaultResourceDao.java | Java | gpl-2.0 | 32,679 |
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.java;
import com.caucho.loader.EnvironmentLocal;
import com.caucho.util.Alarm;
import com.caucho.vfs.MemoryPath;
import com.caucho.vfs.MergePath;
import com.caucho.vfs.Path;
import com.caucho.vfs.Vfs;
import javax.annotation.PostConstruct;
public class WorkDir {
private static final EnvironmentLocal<Path> _localWorkDir
= new EnvironmentLocal<Path>("caucho.work-dir");
private Path _path;
public WorkDir()
{
}
/**
* Returns the local work directory.
*/
public static Path getLocalWorkDir()
{
return getLocalWorkDir(Thread.currentThread().getContextClassLoader());
}
/**
* Returns the local work directory.
*/
public static Path getLocalWorkDir(ClassLoader loader)
{
Path path = _localWorkDir.get(loader);
if (path != null)
return path;
path = getTmpWorkDir();
_localWorkDir.setGlobal(path);
try {
path.mkdirs();
} catch (java.io.IOException e) {
}
return path;
}
/**
* Returns the user directory from /tmp/
*/
public static Path getTmpWorkDir()
{
String userName = System.getProperty("user.name");
Path path;
// Windows uses /temp as a work dir
if (com.caucho.server.util.CauchoSystem.isWindows() && ! Alarm.isTest())
path = Vfs.lookup("file:/c:/tmp/" + userName);
else
path = Vfs.lookup("file:/tmp/" + userName);
return path;
}
/**
* Sets the work dir.
*/
public static void setLocalWorkDir(Path path)
{
setLocalWorkDir(path, Thread.currentThread().getContextClassLoader());
}
/**
* Sets the work dir.
*/
public static void setLocalWorkDir(Path path, ClassLoader loader)
{
try {
if (path instanceof MergePath)
path = ((MergePath) path).getWritePath();
if (path instanceof MemoryPath) {
String pathName = path.getPath();
path = WorkDir.getTmpWorkDir().lookup("qa/" + pathName);
}
// path.mkdirs();
} catch (Exception e) {
throw new RuntimeException(e);
}
_localWorkDir.set(path, loader);
}
/**
* Sets the value.
*/
public void setValue(Path path)
{
_path = path;
}
/**
* @deprecated
*/
public void setId(Path path)
throws java.io.IOException
{
setValue(path);
}
/**
* Stores self.
*/
@PostConstruct
public void init()
{
setLocalWorkDir(_path);
}
}
| dwango/quercus | src/main/java/com/caucho/java/WorkDir.java | Java | gpl-2.0 | 3,463 |
/*
* Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.apertum.qsystem.client.forms;
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
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.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Random;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DropMode;
import javax.swing.ImageIcon;
import javax.swing.InputVerifier;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.FontUIResource;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.BCodec;
import org.apache.commons.lang3.ArrayUtils;
import org.dom4j.DocumentException;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import org.springframework.transaction.TransactionStatus;
import ru.apertum.qsystem.QSystem;
import ru.apertum.qsystem.client.Locales;
import ru.apertum.qsystem.client.common.WysiwygDlg;
import ru.apertum.qsystem.client.help.Helper;
import ru.apertum.qsystem.client.model.PropsTableModel;
import ru.apertum.qsystem.client.model.QTray;
import ru.apertum.qsystem.common.GsonPool;
import ru.apertum.qsystem.common.NetCommander;
import ru.apertum.qsystem.common.QConfig;
import ru.apertum.qsystem.common.QLog;
import ru.apertum.qsystem.common.Uses;
import ru.apertum.qsystem.common.cmd.RpcGetServerState.ServiceInfo;
import ru.apertum.qsystem.common.exceptions.ClientException;
import ru.apertum.qsystem.common.exceptions.ClientWarning;
import ru.apertum.qsystem.common.model.ATalkingClock;
import ru.apertum.qsystem.common.model.INetProperty;
import ru.apertum.qsystem.common.model.QCustomer;
import ru.apertum.qsystem.extra.IDataExchange;
import ru.apertum.qsystem.extra.IPing;
import ru.apertum.qsystem.hibernate.AnnotationSessionFactoryBean;
import ru.apertum.qsystem.reports.model.QReportsList;
import ru.apertum.qsystem.server.MainBoard;
import ru.apertum.qsystem.server.ServerProps;
import ru.apertum.qsystem.server.Spring;
import ru.apertum.qsystem.server.controller.IIndicatorBoard;
import ru.apertum.qsystem.server.model.ATreeModel;
import ru.apertum.qsystem.server.model.QAdvanceCustomer;
import ru.apertum.qsystem.server.model.QOffice;
import ru.apertum.qsystem.server.model.QOfficeList;
import ru.apertum.qsystem.server.model.QPlanService;
import ru.apertum.qsystem.server.model.QProperty;
import ru.apertum.qsystem.server.model.QService;
import ru.apertum.qsystem.server.model.QServiceLang;
import ru.apertum.qsystem.server.model.QServiceTree;
import ru.apertum.qsystem.server.model.QUser;
import ru.apertum.qsystem.server.model.QUserList;
import ru.apertum.qsystem.server.model.calendar.CalendarTableModel;
import ru.apertum.qsystem.server.model.calendar.FreeDay;
import ru.apertum.qsystem.server.model.calendar.QCalendar;
import ru.apertum.qsystem.server.model.calendar.QCalendarList;
import ru.apertum.qsystem.server.model.calendar.TableCell;
import ru.apertum.qsystem.server.model.infosystem.QInfoItem;
import ru.apertum.qsystem.server.model.infosystem.QInfoTree;
import ru.apertum.qsystem.server.model.postponed.QPostponedList;
import ru.apertum.qsystem.server.model.response.QRespItem;
import ru.apertum.qsystem.server.model.response.QResponseTree;
import ru.apertum.qsystem.server.model.results.QResult;
import ru.apertum.qsystem.server.model.results.QResultList;
import ru.apertum.qsystem.server.model.schedule.QBreaks;
import ru.apertum.qsystem.server.model.schedule.QBreaksList;
import ru.apertum.qsystem.server.model.schedule.QSchedule;
import ru.apertum.qsystem.server.model.schedule.QScheduleList;
import ru.apertum.qsystem.server.model.schedule.QSpecSchedule;
/**
* Created on 1 Декабрь 2008 г., 18:51
*
* @author Evgeniy Egorov
*/
public class FAdmin extends javax.swing.JFrame {
/**
* Константы хранения параметров в файле.
*/
private static final String SERVER_ADRESS = "server_adress";
private static final String SERVER_PORT = "server_port";
private static final String SERVER_AUTO_REQUEST = "server_auto_request";
private static final String CLIENT_ADRESS = "client_adress";
private static final String CLIENT_PORT = "client_port";
private static final String CLIENT_AUTO_REQUEST = "client_auto_request";
//******************************************************************************************************************
//******************************************************************************************************************
//***************************************** таймер автоматического запроса******************************************
private static final int DELAY_BLINK = 30000;
private final static SecureRandom RANDOM = new SecureRandom();
private static final String PAGER_URL = "http://localhost:8080";
private static final String REGEXP_URL = "\\b(https?|ftp|file|mailto):(//|[-a-zA-Z0-9_\\.]+@)+[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
private static final Pattern P = Pattern.compile(REGEXP_URL);
private static ResourceMap localeMap = null;
private static FAdmin form = null;
;
private static Answer forPager = null;
//***************************************** таймер автоматического запроса *************************************************
private static String adr;
private static Integer port;
private final QTray tray;
/**
* Таймер опроса компонент системы.
*/
private final StartTimer timer = new StartTimer(DELAY_BLINK, new TimerPrinter());
String serverPluginStat = "";
/**
* вспомогательные для отсечения событий сохранения
*/
private boolean changeSite = true;
private boolean changeUser = true;
private boolean forHidehide = false;
private long ancorPager = new Date().getTime();
private int inGrid = 0;
private QService serviceForCopy = null;
private QService serviceForCut = null;
/**
* Редоктор для главного табло. Singleton.
*/
private AFBoardRedactor board = null;
private String pagerUrl = null;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup bgBoards;
private javax.swing.ButtonGroup bgPager;
private javax.swing.JButton btnAddProp;
private javax.swing.JButton btnAddSection;
private javax.swing.JButton btnDeleteSection;
private javax.swing.JButton btnReloadProps;
private javax.swing.JButton btnRemoveProp;
private javax.swing.JButton btnWysResp1;
private javax.swing.JButton butAddSpecSced;
private javax.swing.JButton butDeleteSpecSced;
private javax.swing.JButton butEditSpecSced;
private javax.swing.JButton butWysInfo1;
private javax.swing.JButton buttonAddCalendar;
private javax.swing.JButton buttonCheckZoneBoardServ;
private javax.swing.JButton buttonClientRequest;
private javax.swing.JButton buttonCloudTest;
private javax.swing.JButton buttonDeleteCalendar;
private javax.swing.JButton buttonExportToCSV;
private javax.swing.ButtonGroup buttonGroupKindNum;
private javax.swing.ButtonGroup buttonGroupPoint;
//private static final String PAGER_URL = "http://dev.apertum.ru:8080";
//private static final String PAGER_URL = "http://109.120.172.108:8080";
private javax.swing.ButtonGroup buttonGroupSource;
private javax.swing.ButtonGroup buttonGroupVoice;
private javax.swing.JButton buttonLock;
private javax.swing.JButton buttonPagerEdit;
private javax.swing.JButton buttonRefreshBan;
private javax.swing.JButton buttonResetMainTablo;
private javax.swing.JButton buttonRestart;
private javax.swing.JButton buttonRestartServer;
private javax.swing.JButton buttonScheduleAdd;
private javax.swing.JButton buttonSchedulleDelete;
private javax.swing.JButton buttonSendDataToSky;
private javax.swing.JButton buttonServerRequest;
private javax.swing.JButton buttonShutDown;
private javax.swing.JButton buttonUnlock;
private javax.swing.JCheckBox cbCommentForResp;
private javax.swing.JCheckBox cbDropTicketsCnt;
private javax.swing.JComboBox cbSeparateCSV;
private javax.swing.JCheckBox chBoxBtnFreeDsn;
private javax.swing.JCheckBox checkBoxAdmin;
private javax.swing.JCheckBox checkBoxClientAuto;
private javax.swing.JCheckBox checkBoxReport;
private javax.swing.JCheckBox checkBoxServerAuto;
private javax.swing.JComboBox comboBoxPager;
private com.toedter.calendar.JDateChooser dateChooserFinishCsv;
private com.toedter.calendar.JDateChooser dateChooserStartCsv;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton18;
private javax.swing.JButton jButton19;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton20;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel36;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem10;
private javax.swing.JMenuItem jMenuItem11;
private javax.swing.JMenuItem jMenuItem12;
private javax.swing.JMenuItem jMenuItem13;
private javax.swing.JMenuItem jMenuItem14;
private javax.swing.JMenuItem jMenuItem15;
private javax.swing.JMenuItem jMenuItem16;
private javax.swing.JMenuItem jMenuItem17;
private javax.swing.JMenuItem jMenuItem18;
private javax.swing.JMenuItem jMenuItem19;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem20;
private javax.swing.JMenuItem jMenuItem21;
private javax.swing.JMenuItem jMenuItem22;
private javax.swing.JMenuItem jMenuItem23;
private javax.swing.JMenuItem jMenuItem24;
private javax.swing.JMenuItem jMenuItem25;
private javax.swing.JMenuItem jMenuItem26;
private javax.swing.JMenuItem jMenuItem27;
private javax.swing.JMenuItem jMenuItem28;
private javax.swing.JMenuItem jMenuItem29;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem30;
private javax.swing.JMenuItem jMenuItem31;
private javax.swing.JMenuItem jMenuItem32;
private javax.swing.JMenuItem jMenuItem33;
private javax.swing.JMenuItem jMenuItem34;
private javax.swing.JMenuItem jMenuItem35;
private javax.swing.JMenuItem jMenuItem36;
private javax.swing.JMenuItem jMenuItem37;
private javax.swing.JMenuItem jMenuItem38;
private javax.swing.JMenuItem jMenuItem39;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem40;
private javax.swing.JMenuItem jMenuItem41;
private javax.swing.JMenuItem jMenuItem42;
private javax.swing.JMenuItem jMenuItem43;
private javax.swing.JMenuItem jMenuItem44;
private javax.swing.JMenuItem jMenuItem45;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JMenuItem jMenuItem9;
private javax.swing.JMenuItem jMenuItemBagtracker;
private javax.swing.JMenuItem jMenuItemEditUser;
private javax.swing.JMenuItem jMenuItemForum;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel22;
private javax.swing.JPanel jPanel23;
private javax.swing.JPanel jPanel24;
private javax.swing.JPanel jPanel25;
private javax.swing.JPanel jPanel26;
private javax.swing.JPanel jPanel27;
private javax.swing.JPanel jPanel28;
private javax.swing.JPanel jPanel29;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel30;
private javax.swing.JPanel jPanel31;
private javax.swing.JPanel jPanel32;
private javax.swing.JPanel jPanel33;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane10;
private javax.swing.JScrollPane jScrollPane11;
private javax.swing.JScrollPane jScrollPane12;
private javax.swing.JScrollPane jScrollPane13;
private javax.swing.JScrollPane jScrollPane14;
private javax.swing.JScrollPane jScrollPane15;
private javax.swing.JScrollPane jScrollPane16;
private javax.swing.JScrollPane jScrollPane17;
private javax.swing.JScrollPane jScrollPane18;
private javax.swing.JScrollPane jScrollPane19;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane20;
private javax.swing.JScrollPane jScrollPane21;
private javax.swing.JScrollPane jScrollPane22;
private javax.swing.JScrollPane jScrollPane23;
private javax.swing.JScrollPane jScrollPane24;
private javax.swing.JScrollPane jScrollPane25;
private javax.swing.JScrollPane jScrollPane26;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JScrollPane jScrollPane9;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparator10;
private javax.swing.JPopupMenu.Separator jSeparator11;
private javax.swing.JPopupMenu.Separator jSeparator12;
private javax.swing.JPopupMenu.Separator jSeparator13;
private javax.swing.JPopupMenu.Separator jSeparator14;
private javax.swing.JPopupMenu.Separator jSeparator15;
private javax.swing.JPopupMenu.Separator jSeparator16;
private javax.swing.JPopupMenu.Separator jSeparator17;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JSeparator jSeparator7;
private javax.swing.JSeparator jSeparator8;
private javax.swing.JPopupMenu.Separator jSeparator9;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JSplitPane jSplitPane10;
private javax.swing.JSplitPane jSplitPane2;
private javax.swing.JSplitPane jSplitPane3;
private javax.swing.JSplitPane jSplitPane4;
private javax.swing.JSplitPane jSplitPane5;
private javax.swing.JSplitPane jSplitPane6;
private javax.swing.JSplitPane jSplitPane7;
private javax.swing.JSplitPane jSplitPane8;
private javax.swing.JSplitPane jSplitPane9;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTabbedPane jTabbedPane2;
private javax.swing.JPanel keyvaluePanel;
private javax.swing.JLabel labExtPrior;
private javax.swing.JLabel labHidePic;
private javax.swing.JLabel labelButtonCaption;
private javax.swing.JLabel labelInfoItem;
private javax.swing.JLabel labelPager;
private javax.swing.JLabel labelPagerCaptionCombo;
private javax.swing.JLabel labelPagerCaptionEdit;
private javax.swing.JLabel labelRespinse;
private javax.swing.JLabel labelSchedule;
private javax.swing.JLabel labelServerState;
private javax.swing.JLabel labelServiceInfo;
private javax.swing.JLabel labelWelcomeState;
private javax.swing.JList listBan;
private javax.swing.JList listBreaks;
private javax.swing.JList listCalendar;
private javax.swing.JList listPostponed;
private javax.swing.JList listReposts;
private javax.swing.JList listResults;
private javax.swing.JList listSchedule;
private javax.swing.JList listSpecSced;
private javax.swing.JList listUserService;
private javax.swing.JList listUsers;
private javax.swing.JMenu menuAbout;
private javax.swing.JMenu menuBoards;
private javax.swing.JMenu menuFile;
private javax.swing.JMenuItem menuItemAbout;
private javax.swing.JMenuItem menuItemHelp;
private javax.swing.JMenu menuLangs;
private javax.swing.JMenu menuServices;
private javax.swing.JMenu menuUsers;
private javax.swing.JMenuItem miAddSection;
private javax.swing.JMenuItem miCopyService;
private javax.swing.JMenuItem miCutService;
private javax.swing.JMenuItem miDeleteSection;
private javax.swing.JMenuItem miPasteService;
private javax.swing.JMenuItem muAddProp;
private javax.swing.JMenuItem muDeleteProp;
private javax.swing.JPanel panelEditPager;
private javax.swing.JPanel panelPager;
private javax.swing.JPanel panelPagerCombo;
private javax.swing.JPanel panelPagerRadio;
private javax.swing.JPanel panelSpecSc;
private javax.swing.JPasswordField passwordFieldUser;
private javax.swing.JPopupMenu popupBreaks;
private javax.swing.JPopupMenu popupCalendar;
private javax.swing.JPopupMenu popupInfo;
private javax.swing.JPopupMenu popupPlans;
private javax.swing.JPopupMenu popupProps;
private javax.swing.JPopupMenu popupResponse;
private javax.swing.JPopupMenu popupResults;
private javax.swing.JPopupMenu popupSections;
private javax.swing.JPopupMenu popupServiceUser;
private javax.swing.JPopupMenu popupServices;
private javax.swing.JPopupMenu popupUser;
private javax.swing.JPanel propsPanel;
private javax.swing.JTable propsTable;
private javax.swing.JRadioButton rbKindCommon;
private javax.swing.JRadioButton rbKindPersonal;
private javax.swing.JRadioButton rbPager1;
private javax.swing.JRadioButton rbPager2;
private javax.swing.JRadioButton rbPager3;
private javax.swing.JRadioButtonMenuItem rbmClassic;
private javax.swing.JRadioButtonMenuItem rbmHtml;
private javax.swing.JPanel sectionPanel;
private javax.swing.JList<ServerProps.Section> sectionsList;
private javax.swing.JSpinner spinCalendarYear;
private javax.swing.JSpinner spinExtPrior;
private javax.swing.JSpinner spinnerBlackListTimeMin;
private javax.swing.JSpinner spinnerBranchId;
private javax.swing.JSpinner spinnerClientPort;
private javax.swing.JSpinner spinnerDowntimeNax;
private javax.swing.JSpinner spinnerFirstNumber;
private javax.swing.JSpinner spinnerLastNumber;
private javax.swing.JSpinner spinnerLineServiceMax;
private javax.swing.JSpinner spinnerLineTotalMax;
private javax.swing.JSpinner spinnerPropClientPort;
private javax.swing.JSpinner spinnerPropServerPort;
private javax.swing.JSpinner spinnerRelocation;
private javax.swing.JSpinner spinnerRemoveRecall;
private javax.swing.JSpinner spinnerServerPort;
private javax.swing.JSpinner spinnerUserRS;
private javax.swing.JSpinner spinnerWaitMax;
private javax.swing.JSpinner spinnerWebServerPort;
private javax.swing.JSpinner spinnerWorkMax;
private javax.swing.JSpinner spinnerZonBoadrServPort;
private javax.swing.JPanel tabHide;
private javax.swing.JTabbedPane tabbedPaneMain;
private javax.swing.JTable tableCalendar;
private javax.swing.JTextField textFieldCalendarName;
private javax.swing.JTextField textFieldClientAdress;
private javax.swing.JTextField textFieldExtPoint;
private javax.swing.JTextField textFieldFinishTime;
private javax.swing.JTextField textFieldInfoItemName;
private javax.swing.JTextField textFieldPager;
private javax.swing.JTextField textFieldResponse;
private javax.swing.JTextField textFieldScheduleName;
private javax.swing.JTextField textFieldSearchService;
private javax.swing.JTextField textFieldServerAddr;
private javax.swing.JTextField textFieldStartTime;
private javax.swing.JTextField textFieldURLWebService;
private javax.swing.JTextField textFieldUserIdent;
private javax.swing.JTextField textFieldUserName;
private javax.swing.JTextField textFieldZonBoadrServAddr;
/**
* Ограничение ввода время начала и конце работы системы.
*/
private InputVerifier DateVerifier = new InputVerifier() {
@Override
public boolean verify(JComponent input) {
final DateFormat dateFormat = new SimpleDateFormat("HH:mm");
try {
if (input == textFieldStartTime) {
dateFormat.parse(textFieldStartTime.getText());
}
if (input == textFieldFinishTime) {
dateFormat.parse(textFieldFinishTime.getText());
}
} catch (ParseException ex) {
System.err.println(
"Незапарсилась дата " + textFieldStartTime.getText() + " или"
+ textFieldFinishTime
.getText());
return false;
}
saveNet();
return true;
}
};
private javax.swing.JTextPane textPaneInfoItem;
private javax.swing.JTextPane textPaneInfoPrint;
private javax.swing.JTextPane textPaneResponse;
private javax.swing.JTextField tfHeaderCmtResp;
private javax.swing.JTextField tfRespID;
private javax.swing.JTextField tfUserId;
private javax.swing.JTree treeInfo;
private javax.swing.JTree treeResp;
private javax.swing.JTree treeServices;
private javax.swing.JList userServsList;
private javax.swing.JSplitPane jUserOfficePane;
private javax.swing.JPopupMenu popupOffice;
private javax.swing.JPanel jOfficePanel;
private javax.swing.JList listOffices;
private javax.swing.JScrollPane jOfficeScrollPane;
private javax.swing.JButton jAddOfficeButton;
private javax.swing.JButton jDeleteOfficeButton;
/**
* Creates new form FAdmin
*/
public FAdmin() {
initComponents();
init();
tabbedPaneMain.remove(tabHide);
// Поставим эконку
final JFrame fr = this;
tray = QTray.getInstance(fr, "/ru/apertum/qsystem/client/forms/resources/admin.png",
getLocaleMessage("tray.caption"));
tray.addItem(getLocaleMessage("tray.caption"), (ActionEvent e) -> {
setVisible(true);
setState(JFrame.NORMAL);
});
tray.addItem("-", (ActionEvent e) -> {
});
tray.addItem(getLocaleMessage("tray.exit"), (ActionEvent e) -> {
dispose();
System.exit(0);
});
int ii = 1;
final ButtonGroup bg = new ButtonGroup();
final String currLng = Locales.getInstance().getLangCurrName();
for (String lng : Locales.getInstance().getAvailableLocales()) {
final JRadioButtonMenuItem item = new JRadioButtonMenuItem(
org.jdesktop.application.Application.getInstance(ru.apertum.qsystem.QSystem.class)
.getContext().getActionMap(FAdmin.class, fr).get("setCurrentLang"));
bg.add(item);
item.setSelected(lng.equals(currLng));
item.setText(lng); // NOI18N
item.setName("QRadioButtonMenuItem" + (ii++)); // NOI18N
menuLangs.add(item);
}
// Определим события выбора итемов в списках.
listUsers.addListSelectionListener((ListSelectionEvent e) -> {
userListChange();
});
listUsers.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
final QUser user = (QUser) listUsers.getSelectedValue();
if (user != null) {
FUserChangeDialog.changeUser(form, true, user);
}
}
}
});
listOffices.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
final QOffice office = (QOffice) listOffices.getSelectedValue();
if (office != null) {
FOfficeChangeDialog.changeOffice(form, true, office);
}
}
}
});
jPanel11.setVisible(false);// убрали редактирование юзера на форме
final ListCellRenderer userRenderer = new ListCellRenderer() {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel renderer = (JLabel) defaultRenderer
.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
final QUser user = (QUser) value;
renderer.setText(
(user.getAdminAccess() ? "*" : "") + user.getName() + " (" + user.getPoint()
+ " / "
+ user.getAdressRS() + ")");
return renderer;
}
};
listUsers.setCellRenderer(userRenderer);
// Определим события выбора итемов в списках.
treeResp.addTreeSelectionListener((TreeSelectionEvent e) -> {
responseListChange();
});
listSchedule.addListSelectionListener((ListSelectionEvent e) -> {
scheduleListChange();
});
listCalendar.addListSelectionListener(new ListSelectionListener() {
private int oldSelectedValue = 0;
private int tmp = 0;
private boolean canceled = false;
public int getOldSelectedValue() {
return oldSelectedValue;
}
public void setOldSelectedValue(int oldSelectedValue) {
this.oldSelectedValue = tmp;
this.tmp = oldSelectedValue;
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (canceled) {
canceled = false;
} else if (tableCalendar.getModel() instanceof CalendarTableModel) {
final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel();
if (!model.isSaved()) {
final int res = JOptionPane
.showConfirmDialog(null, getLocaleMessage("calendar.change.title"),
getLocaleMessage("calendar.change.caption"),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
switch (res) {
case 0: // сохранить и переключиться
model.save();
calendarListChange();
setOldSelectedValue(listCalendar.getSelectedIndex());
break;
case 1: // переключаемся без сохранения
calendarListChange();
setOldSelectedValue(listCalendar.getSelectedIndex());
break;
case 2: // не сохранять и остаться на прежнем уровне
canceled = true;
listCalendar.setSelectedIndex(getOldSelectedValue());
break;
}
} else {
calendarListChange();
setOldSelectedValue(listCalendar.getSelectedIndex());
}
} else {
calendarListChange();
setOldSelectedValue(listCalendar.getSelectedIndex());
}
}
});
// Определим события выбора сайта в списках.
treeServices.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
treeInfo.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
treeResp.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
/*
treeServices.setCellRenderer(new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
setText(((Element) value).attributeValue(Uses.TAG_NAME));
return this;
}
});*/
treeServices.addTreeSelectionListener((TreeSelectionEvent e) -> {
serviceListChange();
});
final MouseListener ml = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
int selRow = treeServices.getRowForLocation(e.getX(), e.getY());
TreePath selPath = treeServices.getPathForLocation(e.getX(), e.getY());
treeServices.setSelectionPath(selPath);
if (selRow > -1) {
treeServices.setSelectionRow(selRow);
}
}
}
};
treeServices.addMouseListener(ml);
treeInfo.addTreeSelectionListener((TreeSelectionEvent e) -> {
infoListChange();
});
sectionsList
.setModel(new DefaultComboBoxModel(ServerProps.getInstance().getSections().toArray()));
sectionsList.addListSelectionListener((ListSelectionEvent e) -> {
if (sectionsList.getLastVisibleIndex() == -1) {
return;
}
final ServerProps.Section item = sectionsList.getSelectedValue();
if (item == null) {
return;
}
propsTable.setModel(new PropsTableModel(item));
});
propsTable.getColumnModel().getColumn(0).setMaxWidth(180);
propsTable.getColumnModel().getColumn(0).setPreferredWidth(180);
propsTable.getColumnModel().getColumn(0).setWidth(180);
propsTable.getColumnModel().getColumn(0).setMaxWidth(1920);
if (!ServerProps.getInstance().getSections().isEmpty()) {
sectionsList.setSelectedIndex(0);
}
textFieldStartTime.setInputVerifier(DateVerifier);
textFieldFinishTime.setInputVerifier(DateVerifier);
//Загрузим настройки
loadSettings();
// Старт таймера автоматических запросов.
startTimer();
// Грузим конфигурацию
loadConfig();
spinnerPropServerPort.getModel().addChangeListener(new ChangeNet());
spinnerPropClientPort.getModel().addChangeListener(new ChangeNet());
spinnerWebServerPort.getModel().addChangeListener(new ChangeNet());
spinnerServerPort.getModel().addChangeListener(new ChangeSettings());
spinnerClientPort.getModel().addChangeListener(new ChangeSettings());
spinnerUserRS.getModel().addChangeListener(new ChangeUser());
//привязка помощи к форме.
final Helper helper = Helper.getHelp("ru/apertum/qsystem/client/help/admin.hs");
helper.setHelpListener(menuItemHelp);
helper.enableHelpKey(jPanel1, "introduction");
helper.enableHelpKey(jPanel3, "monitoring");
helper.enableHelpKey(jPanel4, "configuring");
helper.enableHelpKey(jPanel8, "net");
helper.enableHelpKey(jPanel17, "schedulers");
helper.enableHelpKey(jPanel19, "calendars");
helper.enableHelpKey(jPanel2, "infoSystem");
helper.enableHelpKey(jPanel13, "responses");
helper.enableHelpKey(jPanel18, "results");
treeServices.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport info) {
final JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation();
if (dl.getChildIndex() == -1) {
return false;
}
// Get the string that is being dropped.
final Transferable t = info.getTransferable();
final QService data;
try {
data = (QService) t.getTransferData(DataFlavor.stringFlavor);
return (data.getParent().getId()
.equals(((QService) dl.getPath().getLastPathComponent()).getId()));
} catch (UnsupportedFlavorException | IOException e) {
return false;
}
}
@Override
public boolean importData(TransferHandler.TransferSupport info) {
if (!info.isDrop()) {
return false;
}
final QService data;
try {
data = QServiceTree.getInstance().getById(
((QService) info.getTransferable().getTransferData(DataFlavor.stringFlavor))
.getId());
} catch (UnsupportedFlavorException | IOException e) {
System.err.println(e);
return false;
}
final JTree.DropLocation dl = (JTree.DropLocation) info.getDropLocation();
final TreePath tp = dl.getPath();
final QService parent = (QService) tp.getLastPathComponent();
((QServiceTree) treeServices.getModel()).moveNode(data, parent, dl.getChildIndex());
return true;
}
@Override
public int getSourceActions(JComponent c) {
return MOVE;
}
@Override
protected Transferable createTransferable(JComponent c) {
return (QService) ((JTree) c).getLastSelectedPathComponent();
}
});
treeServices.setDropMode(DropMode.INSERT);
// типо переключалка серверов
final AnnotationSessionFactoryBean as = (AnnotationSessionFactoryBean) Spring.getInstance()
.getFactory().getBean("conf");
if (as.getServers().size() > 1) {
final JMenu menu = new JMenu(getLocaleMessage("admin.servers"));
as.getServers().stream().map((ser) -> {
final JMenuItem mi1 = new JMenuItem(as);
mi1.setText(
ser.isCurrent() ? "<html><u><i>" + ser.getName() + "</i></u>" : ser.getName());
return mi1;
}).forEach((mi1) -> {
menu.add(mi1);
});
jMenuBar1.add(menu, 4);
jMenuBar1.add(new JLabel(
"<html><span style='font-size:13.0pt;color:red'> ["
+ as.getName() + "]"));
}
// Доп. приоритты
spinExtPrior.setVisible(QConfig.cfg().useExtPriorities());
labExtPrior.setVisible(QConfig.cfg().useExtPriorities());
}
public static String getLocaleMessage(String key) {
if (localeMap == null) {
localeMap = Application.getInstance(QSystem.class).getContext()
.getResourceMap(FAdmin.class);
}
return localeMap.getString(key);
}
public static String nextRes(int i) {
return new BigInteger(i, RANDOM).toString(32);
}
private static String getStat() {
final Properties settings = new Properties();
FileInputStream in1 = null;
try {
in1 = new FileInputStream("config" + File.separator + "admin.properties");
} catch (FileNotFoundException ex) {
throw new ClientException(getLocaleMessage("error.file_not_read") + ". " + ex);
}
try {
settings.load(in1);
} catch (IOException ex) {
return "err";
}
String server_plugin_stat = settings.getProperty("server_plugin_stat", "");
if (server_plugin_stat.length() < 4 || QConfig.cfg().isIDE()) {
server_plugin_stat = QConfig.cfg().isIDE() ? "dev" : nextRes(40);
FileOutputStream out = null;
try {
out = new FileOutputStream("config" + File.separator + "admin.properties");
} catch (FileNotFoundException ex) {
throw new ClientException(getLocaleMessage("error.file_not_save") + ". " + ex);
}
settings.put("server_plugin_stat", server_plugin_stat);
try {
settings.store(out, "Settings of admining and monitoring");
} catch (IOException ex) {
return "err";
}
}
return server_plugin_stat;
}
private static String getMac() {
String server_plugin_mac = "no";
try {
final Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
while (networks.hasMoreElements()) {
final NetworkInterface network = networks.nextElement();
final byte[] mac = network.getHardwareAddress();
if (mac != null) {
StringBuilder sb1 = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb1.append(String.format("%02X", mac[i]));
}
server_plugin_mac = sb1.toString();
sb1.setLength(0);
if (mac.length == 6) {
break;
}
}
}
} catch (Exception e) {
}
return server_plugin_mac;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) throws Exception {
QLog.initial(args, 3);
Locale.setDefault(Locales.getInstance().getLangCurrent());
//проверим готовность БД
String checkdb = "0";
String checkdb2 = "no";
try {
Class.forName(Spring.getInstance().getDriverClassName());
final ResultSet rs = DriverManager
.getConnection(Spring.getInstance().getUrl(), Spring.getInstance().getUsername(),
Spring.getInstance().getPassword()).prepareStatement(
"select (select count(1) from clients) c0, (select count(1) from users where deleted is null) c1, (select count(1) from services where deleted is null) c2, (select name from services where prent_id is null) c3")
.executeQuery();
while (rs.next()) {
checkdb = rs.getInt(1) + "-" + rs.getInt(2) + "-" + rs.getInt(3);
checkdb2 = rs.getString(4);
}
} catch (ClassNotFoundException | SQLException e) {
throw new ClientException(
e.getLocalizedMessage() + "\n" + e.getCause().getLocalizedMessage());
}
final String cdb = checkdb;
final String cdb2 = new BCodec().encode(URLEncoder.encode(checkdb2, "utf8"));
QLog.l().logger().info("DB is OK.");
//запустим поток обновления пейджера, пусть поработает
final Thread tPager = new Thread(() -> {
FAbout.loadVersionSt();
String result = "";
try {
final URL url = new URL(
PAGER_URL + "/qskyapi/getpagerdata?qsysver=" + FAbout.VERSION_ + "&qplugins="
+ getMac()
+ "-" + getStat() + "&checkdb=" + cdb + "&checkdb2=" + cdb2);
//System.out.println(url.toString());
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "Java bot");
conn.connect();
final int code = conn.getResponseCode();
if (code == 200) {
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf8"))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
}
}
conn.disconnect();
} catch (Exception e) {
System.err.println("Pager not enabled. " + e);
return;
}
final Gson gson = GsonPool.getInstance().borrowGson();
try {
final Answer answer = gson.fromJson(result, Answer.class);
forPager = answer;
if (answer.getData().size() > 0) {
forPager.start();
}
} catch (Exception e) {
System.err.println("Pager not enabled but working. " + e);
} finally {
GsonPool.getInstance().returnGson(gson);
}
});
tPager.setDaemon(true);
tPager.start();
Uses.startSplash();
// Загрузка плагинов из папки plugins
Uses.loadPlugins("./plugins/");
// Определим кто работает на данном месте.
FLogin.logining(QUserList.getInstance(), null, true, 3, FLogin.LEVEL_ADMIN);
Uses.showSplash();
java.awt.EventQueue.invokeLater(() -> {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
.getInstalledLookAndFeels()) {
System.out.println(info.getName());
/*Metal Nimbus CDE/Motif Windows Windows Classic //GTK+*/
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
if ("/".equals(File.separator)) {
final FontUIResource f = new FontUIResource(new Font("Serif", Font.PLAIN, 10));
final Enumeration<Object> keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
final Object key = keys.nextElement();
final Object value = UIManager.get(key);
if (value instanceof FontUIResource) {
final FontUIResource orig = (FontUIResource) value;
final Font font1 = new Font(f.getFontName(), orig.getStyle(),
f.getSize());
UIManager.put(key, new FontUIResource(font1));
}
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
form = new FAdmin();
if (forPager != null) {
forPager.showData(false);
} else {
form.panelPager.setVisible(false);
form.tabbedPaneMain.remove(form.tabHide);
}
form.setVisible(true);
} catch (Exception ex) {
QLog.l().logger().error("Проблемы с ссозданием формы админки. ", ex);
} finally {
Uses.closeSplash();
}
});
}
/**
* Этим методом запускаем таймер автоматического опроса
*/
private void startTimer() {
if (checkBoxServerAuto.isSelected() || checkBoxClientAuto.isSelected()) {
if (!timer.isRunning()) {
timer.startTimer();
}
} else {
timer.stop();
}
}
private void init() {
addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
timer.stop();
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
Uses.closeSplash();
}
@Override
public void windowDeactivated(WindowEvent e) {
}
});
setTitle(getTitle() + " " + Uses.getLocaleMessage("project.name" + FAbout.getCMRC_SUFF()));
try {
setIconImage(ImageIO
.read(FAdmin.class
.getResource("/ru/apertum/qsystem/client/forms/resources/admin.png")));
} catch (IOException ex) {
System.err.println(ex);
}
// Отцентирируем
final Toolkit kit = Toolkit.getDefaultToolkit();
setLocation((Math.round(kit.getScreenSize().width - getWidth()) / 2),
(Math.round(kit.getScreenSize().height - getHeight()) / 2));
}
/**
* Действия по смене выбранного итема в списке пользоватеолей.
*/
private void userListChange() {
QLog.l().logger().info("userListChanging");
if (listUsers.getLastVisibleIndex() == -1) {
listUserService.setListData(new Object[0]);
textFieldUserName.setText("");
textFieldUserIdent.setText("");
passwordFieldUser.setText("");
textFieldExtPoint.setText("");
tfUserId.setText("");
return;
}
final QUser user = (QUser) listUsers.getSelectedValue();
if (user == null) {
return;
}
changeUser = false;
try {
textFieldUserName.setText(user.getName());
textFieldUserIdent.setText(user.getPoint());
passwordFieldUser.setText(user.getPassword());
spinnerUserRS.setValue(user.getAdressRS());
textFieldExtPoint.setText(user.getPointExt());
checkBoxAdmin.setSelected(user.getAdminAccess());
checkBoxReport.setSelected(user.getReportAccess());
listUserService.setModel(user.getPlanServiceList());
if (listUserService.getLastVisibleIndex() != -1) {
listUserService.setSelectedIndex(0);
}
tfUserId.setText(user.getId() == null ? "--" : user.getId().toString());
} finally {
changeUser = true;
}
}
/**
* x Действия по смене выбранного итема в списке отзывов.
*/
private void responseListChange() {
final TreePath selectedPath = treeResp.getSelectionPath();
if (selectedPath != null) {
final QRespItem item = (QRespItem) selectedPath.getLastPathComponent();
if (item == null) {
return;
}
textFieldResponse.setText(item.getName());
textPaneResponse.setText(item.getHTMLText());
labelRespinse.setText(item.getHTMLText());
tfHeaderCmtResp.setText(item.getInput_caption());
cbCommentForResp.setSelected(item.isInput_required());
tfRespID.setText(item.getId() == null ? "--" : item.getId().toString());
} else {
textFieldResponse.setText("");
textPaneResponse.setText("");
labelRespinse.setText("");
tfHeaderCmtResp.setText("");
tfRespID.setText("");
}
}
/**
* Действия по смене выбранного итема в списке планов расписания.
*/
private void scheduleListChange() {
if (listSchedule.getLastVisibleIndex() == -1) {
textFieldScheduleName.setText("");
labelSchedule.setText("");
return;
}
final QSchedule item = (QSchedule) listSchedule.getSelectedValue();
if (item == null) {
return;
}
textFieldScheduleName.setText(item.getName());
String str = "<HTML>"
+ "<span style='font-size:12.0pt;color:blue;'>"
+ "<b>" + getLocaleMessage("calendar.plan_params") + ":</b>"
+ "<table border='0'>"
+ (item.getType() == 0
? (((item.getTime_begin_1() == null || item.getTime_end_1() == null) ? ""
: "<tr><td>" + getLocaleMessage("calendar.day.monday") + "</td><td><NOBR>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_1()) + "</NOBR></td><td><NOBR>" + getLocaleMessage(
"calendar.time.to") + " " + Uses.FORMAT_HH_MM.format(item.getTime_end_1())
+ "</NOBR></td><td>" + (item.getBreaks_1() == null ? getLocaleMessage("breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_1()) + "</td></tr>")
+ ((item.getTime_begin_2() == null || item.getTime_end_2() == null) ? ""
: "<tr><td>" + getLocaleMessage("calendar.day.tuesday") + "</td><td><NOBR>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_2()) + "</NOBR></td><td><NOBR>" + getLocaleMessage(
"calendar.time.to") + " " + Uses.FORMAT_HH_MM.format(item.getTime_end_2())
+ "</NOBR></td><td>" + (item.getBreaks_2() == null ? getLocaleMessage("breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_2()) + "</td></tr>")
+ ((item.getTime_begin_3() == null || item.getTime_end_3() == null) ? ""
: "<tr><td>" + getLocaleMessage("calendar.day.wednesday") + "</td><td><NOBR>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_3()) + "</NOBR></td><td><NOBR>" + getLocaleMessage(
"calendar.time.to") + " " + Uses.FORMAT_HH_MM.format(item.getTime_end_3())
+ "</NOBR></td><td>" + (item.getBreaks_3() == null ? getLocaleMessage("breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_3()) + "</td></tr>")
+ ((item.getTime_begin_4() == null || item.getTime_end_4() == null) ? ""
: "<tr><td>" + getLocaleMessage("calendar.day.thursday") + "</td><td><NOBR>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_4()) + "</NOBR></td><td><NOBR>" + getLocaleMessage(
"calendar.time.to") + " " + Uses.FORMAT_HH_MM.format(item.getTime_end_4())
+ "</NOBR></td><td>" + (item.getBreaks_4() == null ? getLocaleMessage("breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_4()) + "</td></tr>")
+ ((item.getTime_begin_5() == null || item.getTime_end_5() == null) ? ""
: "<tr><td>" + getLocaleMessage("calendar.day.friday") + "</td><td><NOBR>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_5()) + "</NOBR></td><td><NOBR>" + getLocaleMessage(
"calendar.time.to") + " " + Uses.FORMAT_HH_MM.format(item.getTime_end_5())
+ "</NOBR></td><td>" + (item.getBreaks_5() == null ? getLocaleMessage("breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_5()) + "</td></tr>")
+ ((item.getTime_begin_6() == null || item.getTime_end_6() == null) ? ""
: "<tr><td>" + getLocaleMessage("calendar.day.saturday") + "</td><td><NOBR>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_6()) + "</NOBR></td><td><NOBR>" + getLocaleMessage(
"calendar.time.to") + " " + Uses.FORMAT_HH_MM.format(item.getTime_end_6())
+ "</NOBR></td><td>" + (item.getBreaks_6() == null ? getLocaleMessage("breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_6()) + "</td></tr>")
+ ((item.getTime_begin_7() == null || item.getTime_end_7() == null) ? ""
: "<tr><td>" + getLocaleMessage("calendar.day.sunday") + "</td><td><NOBR>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_7()) + "</NOBR></td><td><NOBR>" + getLocaleMessage(
"calendar.time.to") + " " + Uses.FORMAT_HH_MM.format(item.getTime_end_7())
+ "</NOBR></td><td>" + (item.getBreaks_7() == null ? getLocaleMessage("breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_7()) + "</td></tr>"))
: ((item.getTime_begin_1() == null || item.getTime_end_1() == null) ? ""
: "<tr><td><NOBR>" + getLocaleMessage("calendar.even") + "</NOBR></td><td>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_1()) + "</td><td>" + getLocaleMessage(
"calendar.time.to")
+ " " + Uses.FORMAT_HH_MM.format(item.getTime_end_1()) + "</td><td>" + (
item.getBreaks_1() == null ? getLocaleMessage("breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_1())
+ "</td></tr>"
+ ((item.getTime_begin_2() == null || item.getTime_end_2() == null) ? ""
: "<tr><td><NOBR>" + getLocaleMessage("calendar.odd") + "</NOBR></td><td><NOBR>"
+ getLocaleMessage("calendar.time.from") + " " + Uses.FORMAT_HH_MM
.format(item.getTime_begin_2()) + "</NOBR></td><td><NOBR>"
+ getLocaleMessage(
"calendar.time.to") + " " + Uses.FORMAT_HH_MM.format(item.getTime_end_2())
+ "</NOBR></td><td>" + (item.getBreaks_2() == null ? getLocaleMessage(
"breaks.no")
: getLocaleMessage("breaks.breaks") + ": " + item.getBreaks_2())
+ "</td></tr>"))) + "</table>" + "</span>";
labelSchedule.setText(str);
}
/**
* Действия по смене выбранного итема в списке планов расписания.
*/
private void calendarListChange() {
if (listCalendar.getLastVisibleIndex() == -1) {
textFieldCalendarName.setText("");
return;
}
final QCalendar item = (QCalendar) listCalendar.getSelectedValue();
if (item == null) {
return;
}
textFieldCalendarName.setText(item.getName());
tableCalendar.setModel(new CalendarTableModel(item.getId()));
tableCalendar
.setDefaultRenderer(FreeDay.class,
new TableCell((Integer) (spinCalendarYear.getValue())));
tableCalendar
.setDefaultRenderer(Object.class,
new TableCell((Integer) (spinCalendarYear.getValue())));
tableCalendar.getColumnModel().getColumn(0).setPreferredWidth(500);
listSpecSced.setModel(new DefaultComboBoxModel(item.getSpecSchedules().toArray()));
}
/**
* Действия по смене выбранного итема в списке услуг.
*/
private void serviceListChange() {
final TreePath selectedPath = treeServices.getSelectionPath();
if (selectedPath != null) {
showServiceInfo((QService) selectedPath.getLastPathComponent());
}
}
private void showServiceInfo(QService service) {
String s = "";
for (QServiceLang sl : service.getLangs()) {
s = s + ", " + sl.getLang();
}
s = s.length() > 1 ? "[" + s.substring(2) + "]" : "";
labelServiceInfo.setText("<html><body text=\"#336699\"> "
+ "<font color=\"#"
+ (service.getStatus() == 1
? "00AA00\">" + getLocaleMessage("service.kind.active")
: (service.getStatus() == 0 ? "CCAA00\">" + getLocaleMessage("service.kind.not_active")
: "DD0000\">" + getLocaleMessage("service.kind.unavailable"))) + "/" + service
.getPoint()
+ "</font>"
+ "; "
+ getLocaleMessage("service.prefix") + ": " + "<font color=\"#DD0000\">" + service
.getPrefix() + "</font>" + "; "
+ (service.getEnable() == 1 ? "" : "<font color=\"#FF0000\">!*** </font>")
+ s + " " + getLocaleMessage("service.service") + service.getSeqId() + ": \""
+ "<font color=\"#000000\">"
+ service.getName() + "\" "
+ "</font>"
+ getLocaleMessage("service.description") + ": " + service.getDescription()
+ ";<br>" + getLocaleMessage("service.restrict_day_reg") + ": " + (
service.getDayLimit() == 0 ? getLocaleMessage("service.work_calendar.no")
: service.getDayLimit())
+ ";<br>" + getLocaleMessage("service.restrict_adv_reg") + " " + service
.getAdvanceTimePeriod() + " " + getLocaleMessage("service.min") + ": " + service
.getAdvanceLimit()
+ ";<br> " + getLocaleMessage("service.restrict_adv_period") + ": " + service
.getAdvanceLimitPeriod()
+ ";<br>" + getLocaleMessage("service.work_calendar") + ": " + "<font color=\"#" + (
service.getCalendar() == null ? "DD0000\">" + getLocaleMessage(
"service.work_calendar.no")
: "000000\">" + service.getCalendar().toString()) + "</font>" + "; "
+ getLocaleMessage("service.work_calendar.plan") + ": " + "<font color=\"#" + (
service.getSchedule() == null ? "DD0000\">" + getLocaleMessage(
"service.work_calendar.no")
: "000000\">" + service.getSchedule().toString()) + "</font>" + ";<br>"
+ (service.getInput_required() ? getLocaleMessage("service.required_client_data")
+ ": \""
+ service.getInput_caption().replaceAll("<[^>]*>", "") + "\"(" + service
.getPersonDayLimit()
+ ")" : getLocaleMessage("service.required_client_data.not")) + ";<br> "
+ (service.getResult_required() ? getLocaleMessage("service.required_result")
: getLocaleMessage("service.required_result.not")) + ";");
labelButtonCaption.setText(service.getButtonText());
final LinkedList<QUser> usrs = new LinkedList<>();
for (QUser user : QUserList.getInstance().getItems()) {
for (QPlanService plan : user.getPlanServices()) {
if (plan.getService().getId().equals(service.getId())) {
usrs.add(user);
break;
}
}
}
userServsList.setModel(new DefaultComboBoxModel(usrs.toArray()));
}
/**
* Действия по смене выбранного итема в дереве инфоузлов.
*/
private void infoListChange() {
final TreePath selectedPath = treeInfo.getSelectionPath();
if (selectedPath != null) {
showInfoInfo((QInfoItem) selectedPath.getLastPathComponent());
}
}
private void showInfoInfo(QInfoItem item) {
textFieldInfoItemName.setText(item.getName());
labelInfoItem.setText(item.getHTMLText());
textPaneInfoItem.setText(item.getHTMLText());
textPaneInfoPrint.setText(item.getTextPrint());
}
/**
* Загрузим настройки.
*/
private void loadSettings() {
final Properties settings = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream("config" + File.separator + "admin.properties");
} catch (FileNotFoundException ex) {
throw new ClientException(getLocaleMessage("error.file_not_read") + ". " + ex);
}
try {
settings.load(in);
} catch (IOException ex) {
throw new ClientException(getLocaleMessage("error.params_not_read") + ". " + ex);
}
textFieldServerAddr.setText(settings.getProperty(SERVER_ADRESS));
spinnerServerPort.setValue(Integer.parseInt(settings.getProperty(SERVER_PORT)));
checkBoxServerAuto.setSelected("1".equals(settings.getProperty(SERVER_AUTO_REQUEST)));
textFieldClientAdress.setText(settings.getProperty(CLIENT_ADRESS));
spinnerClientPort.setValue(Integer.parseInt(settings.getProperty(CLIENT_PORT)));
checkBoxClientAuto.setSelected("1".equals(settings.getProperty(CLIENT_AUTO_REQUEST)));
serverPluginStat = settings.getProperty("server_plugin_stat", "");
}
/**
* Сохраним настройки.
*/
private void saveSettings() {
final Properties settings = new Properties();
FileOutputStream out = null;
try {
out = new FileOutputStream("config" + File.separator + "admin.properties");
} catch (FileNotFoundException ex) {
throw new ClientException(getLocaleMessage("error.file_not_save") + ". " + ex);
}
settings.put(SERVER_ADRESS, textFieldServerAddr.getText());
settings.put(SERVER_PORT, String.valueOf(spinnerServerPort.getValue()));
settings.put(SERVER_AUTO_REQUEST, checkBoxServerAuto.isSelected() ? "1" : "0");
settings.put(CLIENT_ADRESS, textFieldClientAdress.getText());
settings.put(CLIENT_PORT, String.valueOf(spinnerClientPort.getValue()));
settings.put(CLIENT_AUTO_REQUEST, checkBoxClientAuto.isSelected() ? "1" : "0");
settings.put("server_plugin_stat", serverPluginStat);
try {
settings.store(out, "Settings of admining and monitoring");
} catch (IOException ex) {
throw new ClientException(getLocaleMessage("error.file_output") + ". " + ex);
}
}
/**
* Загрузим конфигурацию системы.
*/
private void loadConfig() {
listUsers.setModel(QUserList.getInstance());
listOffices.setModel(QOfficeList.getInstance());
treeResp.setModel(QResponseTree.getInstance());
listResults.setModel(QResultList.getInstance());
treeServices.setModel(QServiceTree.getInstance());
treeInfo.setModel(QInfoTree.getInstance());
listSchedule.setModel(QScheduleList.getInstance());
listBreaks.setModel(QBreaksList.getInstance());
listCalendar.setModel(QCalendarList.getInstance());
listReposts.setModel(QReportsList.getInstance());
spinnerPropServerPort.setValue(ServerProps.getInstance().getProps().getServerPort());
spinnerPropClientPort.setValue(ServerProps.getInstance().getProps().getClientPort());
spinnerWebServerPort.setValue(ServerProps.getInstance().getProps().getWebServerPort());
textFieldStartTime
.setText(Uses.FORMAT_HH_MM.format(ServerProps.getInstance().getProps().getStartTime()));
textFieldFinishTime
.setText(
Uses.FORMAT_HH_MM.format(ServerProps.getInstance().getProps().getFinishTime()));
textFieldURLWebService.setText(ServerProps.getInstance().getProps().getSkyServerUrl());
spinnerWaitMax.setValue(ServerProps.getInstance().getStandards().getWaitMax());
spinnerWorkMax.setValue(ServerProps.getInstance().getStandards().getWorkMax());
spinnerDowntimeNax.setValue(ServerProps.getInstance().getStandards().getDowntimeMax());
spinnerLineServiceMax
.setValue(ServerProps.getInstance().getStandards().getLineServiceMax());
spinnerLineTotalMax.setValue(ServerProps.getInstance().getStandards().getLineTotalMax());
spinnerRelocation.setValue(ServerProps.getInstance().getStandards().getRelocation());
textFieldZonBoadrServAddr
.setText(ServerProps.getInstance().getProps().getZoneBoardServAddr());
spinnerZonBoadrServPort
.setValue(ServerProps.getInstance().getProps().getZoneBoardServPort());
spinnerBranchId.setValue(ServerProps.getInstance().getProps().getBranchOfficeId());
spinnerFirstNumber.setValue(ServerProps.getInstance().getProps().getFirstNumber());
spinnerLastNumber.setValue(ServerProps.getInstance().getProps().getLastNumber());
spinExtPrior.setValue(ServerProps.getInstance().getProps().getExtPriorNumber());
rbKindCommon.setSelected(!ServerProps.getInstance().getProps().getNumering());
rbKindPersonal.setSelected(ServerProps.getInstance().getProps().getNumering());
spinnerRemoveRecall.getModel()
.setValue(ServerProps.getInstance().getProps().getLimitRecall());
chBoxBtnFreeDsn.setSelected(ServerProps.getInstance().getProps().getButtonFreeDesign());
spinnerBlackListTimeMin.setValue(ServerProps.getInstance().getProps().getBlackTime());
// выставим начальные позиции в списках
if (listUsers.getLastVisibleIndex() != -1) {
listUsers.setSelectedIndex(0);
}
if (treeResp.getModel().getRoot() != null) {
treeResp.setSelectionPath(new TreePath(treeResp.getModel().getRoot()));
}
if (listSchedule.getLastVisibleIndex() != -1) {
listSchedule.setSelectedIndex(0);
}
if (listCalendar.getLastVisibleIndex() != -1) {
listCalendar.setSelectedIndex(0);
}
if (treeServices.getModel().getRoot() != null) {
treeServices.setSelectionPath(new TreePath(treeServices.getModel().getRoot()));
}
if (treeInfo.getModel().getRoot() != null) {
treeInfo.setSelectionPath(new TreePath(treeInfo.getModel().getRoot()));
}
if (listUserService.getLastVisibleIndex() != -1) {
listUserService.setSelectedIndex(0);
}
final boolean bClassicType = IIndicatorBoard.CLASSIC
.equalsIgnoreCase(ServerProps.getInstance()
.getProperty(IIndicatorBoard.SECTION, IIndicatorBoard.PARAMETER,
IIndicatorBoard.CLASSIC));
rbmClassic.setSelected(bClassicType);
rbmHtml.setSelected(!bClassicType);
}
protected boolean checkServer() {
QLog.l().logger().info("Запрос о состоянии на сервер.");
//элемент ответа.
final LinkedList<ServiceInfo> srvs;
try {
final ServerNetProperty snp = new ServerNetProperty();
srvs = NetCommander.getServerState(snp);
listPostponed.setModel(
QPostponedList.getInstance()
.loadPostponedList(NetCommander.getPostponedPoolInfo(snp)));
} catch (Exception ex) {
listPostponed
.setModel(QPostponedList.getInstance().loadPostponedList(new LinkedList<>()));
labelServerState.setText(
"<HTML><b><span style='font-size:20.0pt;color:red;'>" + getLocaleMessage(
"admin.message.server_not_start") + "</span></b>");
QLog.l().logger().error("Сервер ответил на запрос о состоянии: \"" + ex + "\"");
tray.showMessageTray(getLocaleMessage("tray.server"),
getLocaleMessage("tray.message.stop_server"), QTray.MessageType.WARNING);
return false;
}
//Сформируем ответ
final String red = "<td align=\"center\"><span style='font-size:12.0pt;color:red;'>";
final String green = "<td align=\"center\"><span style='font-size:12.0pt;color:green;'>";
int col = 0;
String html = "";
for (ServiceInfo inf : srvs) {
col += inf.getCountWait();
html = html
+ "<tr>"
+ "" + (0 == inf.getCountWait() ? green : red) + inf.getCountWait() + "</span></td>"
+ "<td align=\"center\">" + inf.getFirstNumber() + "</td>"
+ "<td>" + (inf.getServiceName().length() > 80 ?
inf.getServiceName().substring(0, 80)
+ "..." : inf.getServiceName()) + "</td>"
+ "</tr>";
}
final String first =
"<html>" + getLocaleMessage("admin.info.total_clients") + ": " + (0 == col
? "<span style='font-size:12.0pt;color:green;'>"
: "<span style='font-size:12.0pt;color:red;'>") + col + "</span>";
labelServerState.setText(first
+ "<table border=\"1\">"
+ "<tr>"
+ " <td align=\"center\"<span style='font-size:16.0pt;color:red;'>"
+ getLocaleMessage("admin.info.total_wait")
+ "</span></td> "
+ "<td align=\"center\"><span style='font-size:16.0pt;color:red;'>"
+ getLocaleMessage("admin.info.next_number")
+ "</span></td>"
+ " <td align=\"center\"><span style='font-size:16.0pt;color:red;'>"
+ getLocaleMessage("service.service")
+ "</span></td>"
+ "</tr>"
+ html
+ "</table></html>");
return true;
}
protected boolean checkWelcome(String command) {
QLog.l().logger().info("Запрос о состоянии на пункт регистрации.");
command = command == null ? "Empty" : command;
final String result;
try {
result = NetCommander
.getWelcomeState(netPropWelcome(), command, cbDropTicketsCnt.isSelected());
} catch (Exception ex) {
labelWelcomeState.setText(
"<HTML><b><span style='font-size:20.0pt;color:red;'>" + getLocaleMessage(
"admin.message.welcome_not_start") + "</span></b>");
QLog.l().logger().error(
"Пункт регистрации не ответил на запрос о состоянии или поризошла ошибка. \"" + ex
+ "\"");
tray.showMessageTray(getLocaleMessage("tray.message_stop_server.title"),
getLocaleMessage("tray.message_stop_server.caption"), QTray.MessageType.WARNING);
return false;
}
labelWelcomeState.setText(
"<HTML><span style='font-size:20.0pt;color:green;'>" + getLocaleMessage("admin.welcome")
+ " \"" + result + "\"</span>");
cbDropTicketsCnt.setSelected(false);
return true;
}
protected INetProperty netPropWelcome() {
return new INetProperty() {
@Override
public Integer getPort() {
return (Integer) spinnerClientPort.getValue();
}
@Override
public InetAddress getAddress() {
InetAddress adr = null;
try {
adr = InetAddress.getByName(textFieldClientAdress.getText());
} catch (UnknownHostException ex) {
throw new ClientException("Error! " + ex);
}
return adr;
}
};
}
/**
* Сохранение данных о юзере, повесим на потерю фокуса элементов ввода.
*/
public void saveUser() {
if (changeUser) {
final QUser user = (QUser) listUsers.getSelectedValue();
user.setName(textFieldUserName.getText());
user.setPoint(textFieldUserIdent.getText());
user.setPassword(new String(passwordFieldUser.getPassword()));
user.setAdressRS((Integer) spinnerUserRS.getValue());
user.setPointExt(textFieldExtPoint.getText());
user.setAdminAccess(checkBoxAdmin.isSelected());
user.setReportAccess(checkBoxReport.isSelected());
}
}
/**
* Сохранение данных о сетевых настройках, повесим на нажатие кнопок элементов ввода.
*/
public void saveNet() {
ServerProps.getInstance().getProps()
.setServerPort((Integer) spinnerPropServerPort.getValue());
ServerProps.getInstance().getProps()
.setClientPort((Integer) spinnerPropClientPort.getValue());
ServerProps.getInstance().getProps()
.setWebServerPort((Integer) spinnerWebServerPort.getValue());
if ((Integer) spinnerFirstNumber.getValue() > (Integer) spinnerLastNumber.getValue()) {
spinnerFirstNumber.setValue(1);
spinnerLastNumber.setValue(999);
}
ServerProps.getInstance().getProps()
.setZoneBoardServPort((Integer) spinnerZonBoadrServPort.getValue());
ServerProps.getInstance().getProps()
.setZoneBoardServAddr(textFieldZonBoadrServAddr.getText());
ServerProps.getInstance().getProps()
.setFirstNumber((Integer) spinnerFirstNumber.getValue());
ServerProps.getInstance().getProps().setBranchOfficeId((Long) spinnerBranchId.getValue());
ServerProps.getInstance().getProps().setSkyServerUrl(textFieldURLWebService.getText());
ServerProps.getInstance().getProps().setLastNumber((Integer) spinnerLastNumber.getValue());
ServerProps.getInstance().getProps().setExtPriorNumber((Integer) spinExtPrior.getValue());
ServerProps.getInstance().getProps().setNumering(rbKindPersonal.isSelected());
ServerProps.getInstance().getProps().setBlackTime((int) spinnerBlackListTimeMin.getValue());
ServerProps.getInstance().getProps().setLimitRecall((int) spinnerRemoveRecall.getValue());
ServerProps.getInstance().getProps().setButtonFreeDesign(chBoxBtnFreeDsn.isSelected());
ServerProps.getInstance().getStandards().setWaitMax((Integer) spinnerWaitMax.getValue());
ServerProps.getInstance().getStandards().setWorkMax((Integer) spinnerWorkMax.getValue());
ServerProps.getInstance().getStandards()
.setDowntimeMax((Integer) spinnerDowntimeNax.getValue());
ServerProps.getInstance().getStandards()
.setLineServiceMax((Integer) spinnerLineServiceMax.getValue());
ServerProps.getInstance().getStandards()
.setLineTotalMax((Integer) spinnerLineTotalMax.getValue());
ServerProps.getInstance().getStandards()
.setRelocation((Integer) spinnerRelocation.getValue());
try {
ServerProps.getInstance().getProps()
.setStartTime(Uses.FORMAT_HH_MM.parse(textFieldStartTime.getText()));
ServerProps.getInstance().getProps()
.setFinishTime(Uses.FORMAT_HH_MM.parse(textFieldFinishTime.getText()));
} catch (ParseException ex) {
QLog.l().logger().error("Проблемы с сохранение сетевых настроек. ", ex);
}
}
@Action
public void hideWindow() {
}
@Action
public void addOffice() {
// Запросим название юзера и если оно уникально, то примем
String officeName = "";
boolean flag = true;
while (flag) {
officeName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_office_dialog.title"),
getLocaleMessage("admin.add_office_dialog.caption"), 3, null, null, officeName);
if (officeName == null) {
return;
}
if ("".equals(officeName)) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_service_dialog.err1.title"),
getLocaleMessage("admin.add_service_dialog.err1.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (officeName.indexOf('\"') != -1) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_service_dialog.err3.title"),
getLocaleMessage("admin.add_service_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (officeName.length() > 100) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_service_dialog.err4.title"),
getLocaleMessage("admin.add_service_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
QLog.l().logger().debug("Adding a user \"" + officeName + "\"");
final QOffice office = new QOffice();
office.setName(officeName);
office.setSmartboardType("callbyticket");
QOfficeList.getInstance().addElement(office);
listOffices.setSelectedValue(office, true);
}
@Action
public void deleteOffice() {
QLog.l().logger().debug("Delete Office");
if (listOffices.getSelectedIndex() != -1) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.remove_office_dialog.title") + " \""
+ ((QOffice) listOffices
.getSelectedValue()).getName() + "\"?",
getLocaleMessage("admin.remove_user_dialog.caption"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
final int del = listOffices.getSelectedIndex();
final QOfficeList m = (QOfficeList) listOffices.getModel();
final int col = m.getSize();
final QOffice office = (QOffice) listOffices.getSelectedValue();
QOfficeList.getInstance().removeElement(office);
if (col != 1) {
if (col == del + 1) {
listOffices.setSelectedValue(m.getElementAt(del - 1), true);
} else if (col > del + 1) {
listOffices.setSelectedValue(m.getElementAt(del), true);
}
}
}
}
@Action
public void addUser() {
// Запросим название юзера и если оно уникально, то примем
String userName = "";
QOffice office = null;
boolean flag = true;
List<QOffice> offices = Spring.getInstance().getHt().findByCriteria(
DetachedCriteria.forClass(QOffice.class)
.add(Property.forName("deleted").isNull())
.setFetchMode("services", FetchMode.EAGER)
.setResultTransformer((Criteria.DISTINCT_ROOT_ENTITY))
);
while (flag) {
JTextField userNameTextField = new JTextField();
JComboBox officeDropdown = new JComboBox();
for (QOffice dropdownOffice : offices) {
officeDropdown.addItem(dropdownOffice);
}
Object[] message = {
"Username:", userNameTextField,
"Office:", officeDropdown
};
int option = JOptionPane
.showConfirmDialog(this, message, getLocaleMessage("admin.add_user_dialog.title"),
JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
userName = userNameTextField.getText();
office = (QOffice) officeDropdown.getSelectedItem();
if ("".equals(userName)) {
flag = true;
} else if (QUserList.getInstance().hasByName(userName)) {
flag = true;
} else if (userName.indexOf('\"') != -1) {
flag = true;
} else if (userName.length() > 150) {
flag = true;
} else {
flag = false;
}
} else if (option == JOptionPane.CANCEL_OPTION) {
return;
}
}
QLog.l().logger().debug("Adding a user \"" + userName + "\"");
final QUser user = new QUser();
user.setPlanServices(new LinkedList<>());
user.setName(userName);
user.setOffice(office);
user.setPassword("");
user.setPoint("");
user.setAdressRS(32);
user.addPlanServiceByOffice();
QUserList.getInstance().addElement(user);
listUsers.setSelectedValue(user, true);
}
@Action
public void addNewUserByCopy() {
if (listUsers.getSelectedIndex() != -1) {
final QUser user = (QUser) listUsers.getSelectedValue();
// Запросим название юзера и если оно уникально, то примем
String userName = "";
boolean flag = true;
while (flag) {
userName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_user_dialog.title"),
getLocaleMessage("admin.add_user_dialog.caption"), 3, null, null, userName);
if (userName == null) {
return;
}
if ("".equals(userName)) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_user_dialog.err1.title"),
getLocaleMessage("admin.add_user_dialog.err1.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (QUserList.getInstance().hasByName(userName)) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_user_dialog.err2.title"),
getLocaleMessage("admin.add_user_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (userName.indexOf('\"') != -1) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_user_dialog.err3.title"),
getLocaleMessage("admin.add_user_dialog.err3.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (userName.length() > 150) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_user_dialog.err4.title"),
getLocaleMessage("admin.add_user_dialog.err4.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
QLog.l().logger().debug("delete user \"" + userName + "\"");
final QUser newUser = new QUser();
LinkedList<QPlanService> plan = new LinkedList<>();
user.getPlanServices().stream().forEach((pl) -> {
plan.add(new QPlanService(pl.getService(), pl.getUser(), pl.getCoefficient()));
});
newUser.setPlanServices(plan);
newUser.setName(userName);
newUser.setPassword("");
newUser.setPoint(user.getPoint());
newUser.setAdressRS(user.getAdressRS());
newUser.setPointExt(user.getPointExt());
newUser.setReportAccess(user.getReportAccess());
newUser.setAdminAccess(user.getAdminAccess());
newUser.setAdminAccess(user.getAdminAccess());
QUserList.getInstance().addElement(newUser);
listUsers.setSelectedValue(newUser, true);
}
}
@Action
public void renameUser() {
if (listUsers.getSelectedIndex() != -1) {
final QUser user = (QUser) listUsers.getSelectedValue();
String userName = user.getName();
boolean flag = true;
while (flag) {
userName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.rename_user_dialog.title"),
getLocaleMessage("admin.rename_user_dialog.caption"), 3, null, null,
userName);
if (userName == null) {
return;
}
if ("".equals(userName)) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.rename_user_dialog.err1.title"),
getLocaleMessage("admin.rename_user_dialog.err1.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (QUserList.getInstance().hasByName(userName)) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.rename_user_dialog.err2.title"),
getLocaleMessage("admin.rename_user_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (userName.indexOf('\"') != -1) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.rename_user_dialog.err3.title"),
getLocaleMessage("admin.rename_user_dialog.err3.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (userName.length() > 150) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.rename_user_dialog.err4.title"),
getLocaleMessage("admin.rename_user_dialog.err4.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
user.setName(userName);
textFieldUserName.setText(userName);
listUsers.setSelectedValue(user, true);
}
}
@Action
public void deleteUser() {
if (listUsers.getSelectedIndex() != -1) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.remove_user_dialog.title") + " \"" + ((QUser) listUsers
.getSelectedValue()).getName() + "\"?",
getLocaleMessage("admin.remove_user_dialog.caption"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
QLog.l().logger().debug(
"Удаляем пользователя \"" + ((QUser) listUsers.getSelectedValue()).getName()
+ "\"");
final int del = listUsers.getSelectedIndex();
final QUserList m = (QUserList) listUsers.getModel();
final int col = m.getSize();
final QUser user = (QUser) listUsers.getSelectedValue();
//проверим не последний ли это админ
if (user.getAdminAccess()) {
int cnt = 0;
for (int i = 0; i < listUsers.getModel().getSize(); i++) {
if (((QUser) listUsers.getModel().getElementAt(i)).getAdminAccess()) {
cnt++;
}
}
if (cnt == 1) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.remove_user_dialog.err.title"),
getLocaleMessage("admin.remove_user_dialog.err.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
return;
}
}
QUserList.getInstance().removeElement(user);
if (col != 1) {
if (col == del + 1) {
listUsers.setSelectedValue(m.getElementAt(del - 1), true);
} else if (col > del + 1) {
listUsers.setSelectedValue(m.getElementAt(del), true);
}
}
}
}
@Action
public void addService() throws DocumentException {
// We will request the name of the service and if it is unique and not empty, then we will accept
String serviceName = "";
boolean flag = true;
while (flag) {
serviceName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_service_dialog.title"),
getLocaleMessage("admin.add_service_dialog.caption"), 3, null, null,
serviceName);
if (serviceName == null) {
return;
}
if ("".equals(serviceName)) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_service_dialog.err1.title"),
getLocaleMessage("admin.add_service_dialog.err1.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (QServiceTree.getInstance().hasByName(serviceName)) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_service_dialog.err2.title"),
getLocaleMessage("admin.add_service_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (serviceName.indexOf('\"') != -1) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_service_dialog.err3.title"),
getLocaleMessage("admin.add_service_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (serviceName.length() > 2001) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.add_service_dialog.err4.title"),
getLocaleMessage("admin.add_service_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
// Create a new service and add it to the model
final QService newService = new QService();
newService.setName(serviceName);
newService.setDescription(serviceName);
newService.setStatus(1);
newService.setSoundTemplate("021111");
newService.setAdvanceTimePeriod(60);
newService.setSmartboard("Y");
newService.setCalendar(QCalendarList.getInstance().getById(1));
if (QScheduleList.getInstance().getSize() != 0) {
newService.setSchedule(QScheduleList.getInstance().getElementAt(0));
}
newService.setButtonText(
"<html><b><p align=center><span style='font-size:20.0pt;color:red'>" + serviceName
+ "</span></b>");
//проставим букавку
newService.setPrefix("A");
QServiceTree.sailToStorm(QServiceTree.getInstance().getRoot(), (TreeNode service) -> {
if (service.isLeaf()) {
String pr = ((QService) service).getPrefix();
if (!pr.isEmpty()) {
if (pr.substring(pr.length() - 1).compareToIgnoreCase(
newService.getPrefix().substring(newService.getPrefix().length() - 1))
>= 0) {
newService.setPrefix(
String.valueOf((char) (pr.substring(pr.length() - 1).charAt(0) + 1))
.toUpperCase());
}
}
}
});
final QService parentService = (QService) treeServices.getLastSelectedPathComponent();
QServiceTree.getInstance()
.insertNodeInto(newService, parentService, parentService.getChildCount());
final TreeNode[] nodes = QServiceTree.getInstance().getPathToRoot(newService);
final TreePath path = new TreePath(nodes);
treeServices.scrollPathToVisible(path);
treeServices.setSelectionPath(path);
// Parent service to the new service should be excluded from the list of users tied to users. She became a group
deleteServiceFromUsers(parentService);
QLog.l().logger().debug(
"Добавлена услуга \"" + serviceName + "\" в группу \"" + parentService.getName()
+ "\"");
}
@Action
public void renameService() {
final QService service = (QService) treeServices.getLastSelectedPathComponent();
if (service != null) {
String serviceName = service.getName();
boolean flag = true;
while (flag) {
serviceName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.rename_service_dialog.title"),
getLocaleMessage("admin.rename_service_dialog.caption"), 3, null, null,
serviceName);
if (serviceName == null) {
return;
}
if ("".equals(serviceName)) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.rename_service_dialog.err1.title"),
getLocaleMessage("admin.rename_service_dialog.err1.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (QServiceTree.getInstance().hasByName(serviceName)) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.rename_service_dialog.err2.title"),
getLocaleMessage("admin.rename_service_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (serviceName.indexOf('\"') != -1) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.rename_service_dialog.err3.title"),
getLocaleMessage("admin.rename_service_dialog.err3.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (serviceName.length() > 2001) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.rename_service_dialog.err4.title"),
getLocaleMessage("admin.rename_service_dialog.err4.caption"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
service.setName(serviceName);
}
}
/**
* Из привязок к услугам всех юзеров убрать привязку к данной услуге и всех ее вложенных.
*
* @param service удаляемая услуга
*/
private void deleteServicesFromUsers(QService service) {
QServiceTree.sailToStorm(service, (TreeNode service1) -> {
deleteServiceFromUsers((QService) service1);
});
}
/**
* Из привязок к услугам всех юзеров убрать привязку к данной услуге.
*
* @param service удаляемая услуга
*/
private void deleteServiceFromUsers(QService service) {
QUserList.getInstance().getItems().stream()
.filter((user) -> (user.hasService(service.getId())))
.forEach((user) -> {
user.deletePlanService(service.getId());
});
}
@Action
public void deleteService() {
final QService service = (QService) treeServices.getLastSelectedPathComponent();
if (service != null && !service.isRoot()) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.remove_service_dialog.title") + " " + (service.isLeaf()
? getLocaleMessage("admin.remove_service_dialog.title_1")
: getLocaleMessage("admin.remove_service_dialog.title_2")) + "\n\"" + (
service.getName().length() > 85 ? service.getName().substring(0, 85) + " ..."
: service.getName()) + "\"?",
getLocaleMessage("admin.remove_service_dialog.caption"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
// Remove this service from users
deleteServicesFromUsers(service);
// Remove the service itself
final int del = service.getParent().getIndex(service);
final int col = service.getParent().getChildCount();
((QServiceTree) treeServices.getModel()).removeNodeFromParent(service);
// Remove this service tied as a shortcut
QServiceTree
.sailToStorm(((QServiceTree) treeServices.getModel()).getRoot(), (TreeNode srv) -> {
final QService serv = (QService) srv;
if (serv.getLink() != null && serv.getLink().getId().equals(service.getId())) {
serv.setLink(null);
}
});
// Выделение в услуги в дереве
if (col == 1) {
treeServices.setSelectionPath(new TreePath(
((QServiceTree) treeServices.getModel()).getPathToRoot(service.getParent())));
} else if (col == del + 1) {
treeServices.setSelectionPath(new TreePath(((QServiceTree) treeServices.getModel())
.getPathToRoot(service.getParent().getChildAt(del - 1))));
} else if (col > del + 1) {
treeServices.setSelectionPath(new TreePath(((QServiceTree) treeServices.getModel())
.getPathToRoot(service.getParent().getChildAt(del))));
}
QLog.l().logger().debug(
"Service deleted \"" + service.getName() + "\" from the group \"" + service
.getParent()
.getName() + "\"");
}
}
@Action
public void addInfoItem() {
// Запросим название инфоузла и если оно уникально и не пусто, то примем
String infoName = getLocaleMessage("admin.add_info_dialog.info");
boolean flag = true;
while (flag) {
infoName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_info_dialog.title"),
getLocaleMessage("admin.add_info_dialog.caption"), 3, null, null, infoName);
if (infoName == null) {
return;
}
if ("".equals(infoName)) {
JOptionPane
.showConfirmDialog(this, getLocaleMessage("admin.add_info_dialog.err1.title"),
getLocaleMessage("admin.add_info_dialog.err1.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (infoName.indexOf('\"') != -1) {
JOptionPane
.showConfirmDialog(this, getLocaleMessage("admin.add_info_dialog.err2.title"),
getLocaleMessage("admin.add_info_dialog.err2.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (infoName.length() > 100) {
JOptionPane
.showConfirmDialog(this, getLocaleMessage("admin.add_info_dialog.err3.title"),
getLocaleMessage("admin.add_info_dialog.err3.caption"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
// Созданим новую услугу и добавим ее в модель
final QInfoItem newItem = new QInfoItem();
newItem.setName(infoName);
newItem.setHTMLText(
"<html><b><p align=center><span style='font-size:20.0pt;color:green'>" + infoName
+ "</span></b>");
newItem.setTextPrint("");
final QInfoItem parentItem = (QInfoItem) treeInfo.getLastSelectedPathComponent();
((QInfoTree) treeInfo.getModel())
.insertNodeInto(newItem, parentItem, parentItem.getChildCount());
final TreeNode[] nodes = ((QInfoTree) treeInfo.getModel()).getPathToRoot(newItem);
final TreePath path = new TreePath(nodes);
treeInfo.scrollPathToVisible(path);
treeInfo.setSelectionPath(path);
textFieldInfoItemName.setEnabled(true);
//textPaneInfoItem.setEnabled(true);
//textPaneInfoPrint.setEnabled(true);
QLog.l().logger()
.debug("Added node\"" + infoName + "\" to group \"" + parentItem.getName() + "\"");
}
@Action
public void deleteInfoItem() {
final QInfoItem item = (QInfoItem) treeInfo.getLastSelectedPathComponent();
if (item != null && !item.isRoot()) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.remove_info_dialog.title") + " " + (item.isLeaf()
? getLocaleMessage("admin.remove_info_dialog.title_1")
: getLocaleMessage("admin.remove_info_dialog.title_2")) + "\"" + (
item.getName().length() > 85 ? item.getName().substring(0, 85) + " ..."
: item.getName()) + "\"?",
getLocaleMessage("admin.remove_info_dialog.caption"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
// Удалим сам узел
final int del = item.getParent().getIndex(item);
final int col = item.getParent().getChildCount();
QInfoTree.getInstance().removeNodeFromParent(item);
// Выделение в узла в дереве
if (col == 1) {
treeInfo.setSelectionPath(
new TreePath(
((QInfoTree) treeInfo.getModel()).getPathToRoot(item.getParent())));
} else if (col == del + 1) {
treeInfo.setSelectionPath(new TreePath(
((QInfoTree) treeInfo.getModel())
.getPathToRoot(item.getParent().getChildAt(del - 1))));
} else if (col > del + 1) {
treeInfo.setSelectionPath(new TreePath(
((QInfoTree) treeInfo.getModel())
.getPathToRoot(item.getParent().getChildAt(del))));
}
QLog.l().logger().debug(
"Removed node \"" + item.getName() + "\" from group \"" + item.getParent().getName()
+ "\"");
}
}
/*
* @see http://static.springsource.org/spring/docs/3.0.x/reference/transaction.html#transaction-programmatic
*/
@Action
public void saveConfiguration() {
saveNet();
final Exception res;
try {
res = (Exception) Spring.getInstance().getTt().execute((TransactionStatus status) -> {
try {
//сохраним системные настройки
final Collection<QProperty> col = new ArrayList<>();
ServerProps.getInstance().getSections().forEach(sec -> {
col.addAll(sec.getProperties().values());
});
Spring.getInstance().getHt().saveOrUpdateAll(col);
//Сохраняем сетевые настройки
Spring.getInstance().getHt().saveOrUpdate(ServerProps.getInstance().getProps());
//Сохраняем нормативные параметры
Spring.getInstance().getHt()
.saveOrUpdate(ServerProps.getInstance().getStandards());
// Сохраняем перерывы в расписании, тут теперь стоит, а то в календаре появились расписания.
QBreaksList.getInstance().save();
// Сохраняем планы расписания
QScheduleList.getInstance().save();
// хз что за коммент: Сохраняем календари услуг, главное раньше расписаний, не то спец расписания будут ругаться.
QCalendarList.getInstance().save();
// Сохраняем услуги
QServiceTree.getInstance().save();
// Сохраняем пользователей
QUserList.getInstance().save();
// Сохраняем инфоузлы
QInfoTree.getInstance().save();
// Сохраняем отзывы
QResponseTree.getInstance().save();
// Сохраняем результаты работы пользователя с клиентами
QResultList.getInstance().save();
QOfficeList.getInstance().save();
} catch (Exception ex) {
QLog.l().logger().error(
"Error while saving \n" + ex.toString() + "\n" + Arrays
.toString(ex.getStackTrace()));
status.setRollbackOnly();
return ex;
}
return null;
});
} catch (RuntimeException ex) {
throw new ClientException(
"Error performing the operation of modifying data in the database(JDBC). Perhaps the parameters you entered can not be saved. \n("
+ ex.toString() + ")");
}
if (res == null) {
JOptionPane.showMessageDialog(this, getLocaleMessage("admin.save.title"),
getLocaleMessage("admin.save.caption"), JOptionPane.INFORMATION_MESSAGE);
} else {
throw new ClientException(
"Error performing the operation of modifying data in the database(JDBC). Perhaps the parameters you entered can not be saved.\n["
+ res.getLocalizedMessage() + "]\n(" + res.toString() + ")\nSQL: ");
}
}
@Action
public void addServiceToUser() {
// вот эта строчка не понятно зачем добавлена. дело в том что после сохранения вновь добавленные услуги юзеру не отображаются в списке. т.е. listUsers.getSelectedIndex() == -1
listUserService.setModel(((QUser) listUsers.getSelectedValue()).getPlanServiceList());
final QUser user = (QUser) listUsers.getSelectedValue();
final QService service = (QService) treeServices.getLastSelectedPathComponent();
if (service != null && service.isLeaf() && listUsers.getSelectedIndex() != -1 && !(user
.hasService(service))) {
user.addPlanService(service);
if (listUserService.getLastVisibleIndex() != -1) {
listUserService.setSelectedIndex(listUserService.getLastVisibleIndex());
QLog.l().logger().debug(
"User \"" + user.getName() + "\" appointed a service \"" + service.getName()
+ "\".");
}
}
if (service != null && !service.isLeaf() && listUsers.getSelectedIndex() != -1 && !(user
.hasService(service))) {
QServiceTree.sailToStorm(service, (TreeNode service1) -> {
if (service1.isLeaf() && !user.hasService((QService) service1)) {
user.addPlanService((QService) service1);
QLog.l().logger()
.debug("User \"" + ((QUser) listUsers.getSelectedValue()).getName()
+ "\" appointed a service \"" + ((QService) service1).getName()
+ "\".");
}
});
if (listUserService.getLastVisibleIndex() != -1) {
listUserService.setSelectedIndex(listUserService.getLastVisibleIndex());
}
}
}
@Action
public void deleteServiseFromUser() {
if (listUserService.getSelectedIndex() != -1) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.remove_service_from_user.title") + " \"" + listUserService
.getSelectedValue().toString() + "\" " + getLocaleMessage(
"admin.remove_service_from_user.title_1") + " \"" + listUsers.getSelectedValue()
.toString() + "\"?",
getLocaleMessage("admin.remove_service_from_user.caption"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
final int ind = listUserService.getSelectedIndex();
((QUser) listUsers.getSelectedValue()).deletePlanService(
((QPlanService) listUserService.getSelectedValue()).getService().getId());
if (listUserService.getLastVisibleIndex() != -1) {
listUserService.setSelectedIndex(
listUserService.getLastVisibleIndex() < ind ? listUserService
.getLastVisibleIndex()
: ind);
}
}
}
@Action
public void getTicket() {
final QService service = (QService) treeServices.getLastSelectedPathComponent();
if (service != null && service.isLeaf()) {
//Если услуга требует ввода данных пользователем, то нужно получить эти данные из диалога ввода
String inputData = null;
if (service.getInput_required()) {
inputData = (String) JOptionPane
.showInputDialog(this, service.getInput_caption().replaceAll("<[^>]*>", ""),
"***", 3,
null, null, "");
if (inputData == null || inputData.isEmpty()) {
return;
}
}
final QCustomer customer;
try {
customer = NetCommander
.standInService(new ServerNetProperty(), service.getId(), "1", 1, inputData);
} catch (Exception ex) {
throw new ClientException(getLocaleMessage("admin.print_ticket_error") + " " + ex);
}
FWelcome
.printTicket(customer, ((QService) treeServices.getModel().getRoot()).getName());
String pref = customer.getPrefix();
pref = "".equals(pref) ? "" : pref + "-";
JOptionPane.showMessageDialog(this,
getLocaleMessage("admin.print_ticket.title") + " \"" + service.getName() + "\". "
+ getLocaleMessage("admin.print_ticket.title_1") + " \"" + pref + customer
.getNumber()
+ "\".", getLocaleMessage("admin.print_ticket.caption"),
JOptionPane.INFORMATION_MESSAGE);
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupSource = new javax.swing.ButtonGroup();
popupUser = new javax.swing.JPopupMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem45 = new javax.swing.JMenuItem();
jMenuItem20 = new javax.swing.JMenuItem();
jMenuItemEditUser = new javax.swing.JMenuItem();
jSeparator7 = new javax.swing.JSeparator();
jMenuItem10 = new javax.swing.JMenuItem();
popupServices = new javax.swing.JPopupMenu();
jMenuItem11 = new javax.swing.JMenuItem();
jMenuItem21 = new javax.swing.JMenuItem();
miCopyService = new javax.swing.JMenuItem();
miCutService = new javax.swing.JMenuItem();
miPasteService = new javax.swing.JMenuItem();
jMenuItem13 = new javax.swing.JMenuItem();
jSeparator8 = new javax.swing.JSeparator();
jMenuItem22 = new javax.swing.JMenuItem();
jMenuItem42 = new javax.swing.JMenuItem();
jMenuItem12 = new javax.swing.JMenuItem();
jSeparator5 = new javax.swing.JSeparator();
jMenuItem16 = new javax.swing.JMenuItem();
jMenuItem24 = new javax.swing.JMenuItem();
jMenuItem44 = new javax.swing.JMenuItem();
popupServiceUser = new javax.swing.JPopupMenu();
jMenuItem14 = new javax.swing.JMenuItem();
jMenuItem38 = new javax.swing.JMenuItem();
jMenuItem17 = new javax.swing.JMenuItem();
jMenuItem18 = new javax.swing.JMenuItem();
jSeparator6 = new javax.swing.JSeparator();
jMenuItem15 = new javax.swing.JMenuItem();
popupInfo = new javax.swing.JPopupMenu();
jMenuItem26 = new javax.swing.JMenuItem();
jSeparator9 = new javax.swing.JPopupMenu.Separator();
jMenuItem27 = new javax.swing.JMenuItem();
popupResponse = new javax.swing.JPopupMenu();
jMenuItem28 = new javax.swing.JMenuItem();
jSeparator10 = new javax.swing.JPopupMenu.Separator();
jMenuItem29 = new javax.swing.JMenuItem();
popupResults = new javax.swing.JPopupMenu();
jMenuItem30 = new javax.swing.JMenuItem();
jSeparator11 = new javax.swing.JPopupMenu.Separator();
jMenuItem31 = new javax.swing.JMenuItem();
popupPlans = new javax.swing.JPopupMenu();
jMenuItem32 = new javax.swing.JMenuItem();
jMenuItem33 = new javax.swing.JMenuItem();
jSeparator12 = new javax.swing.JPopupMenu.Separator();
jMenuItem34 = new javax.swing.JMenuItem();
popupCalendar = new javax.swing.JPopupMenu();
jMenuItem35 = new javax.swing.JMenuItem();
jSeparator13 = new javax.swing.JPopupMenu.Separator();
jMenuItem36 = new javax.swing.JMenuItem();
buttonGroupKindNum = new javax.swing.ButtonGroup();
buttonGroupPoint = new javax.swing.ButtonGroup();
buttonGroupVoice = new javax.swing.ButtonGroup();
popupBreaks = new javax.swing.JPopupMenu();
jMenuItem39 = new javax.swing.JMenuItem();
jMenuItem40 = new javax.swing.JMenuItem();
jSeparator16 = new javax.swing.JPopupMenu.Separator();
jMenuItem41 = new javax.swing.JMenuItem();
bgPager = new javax.swing.ButtonGroup();
popupProps = new javax.swing.JPopupMenu();
muAddProp = new javax.swing.JMenuItem();
muDeleteProp = new javax.swing.JMenuItem();
popupSections = new javax.swing.JPopupMenu();
miAddSection = new javax.swing.JMenuItem();
miDeleteSection = new javax.swing.JMenuItem();
bgBoards = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
tabbedPaneMain = new javax.swing.JTabbedPane();
jPanel3 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
textFieldClientAdress = new javax.swing.JTextField();
spinnerClientPort = new javax.swing.JSpinner();
jLabel5 = new javax.swing.JLabel();
labelWelcomeState = new javax.swing.JLabel();
checkBoxClientAuto = new javax.swing.JCheckBox();
buttonClientRequest = new javax.swing.JButton();
buttonLock = new javax.swing.JButton();
buttonUnlock = new javax.swing.JButton();
buttonRestart = new javax.swing.JButton();
buttonShutDown = new javax.swing.JButton();
cbDropTicketsCnt = new javax.swing.JCheckBox();
jPanel6 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
textFieldServerAddr = new javax.swing.JTextField();
spinnerServerPort = new javax.swing.JSpinner();
jLabel2 = new javax.swing.JLabel();
checkBoxServerAuto = new javax.swing.JCheckBox();
buttonServerRequest = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
labelServerState = new javax.swing.JLabel();
buttonRestartServer = new javax.swing.JButton();
jScrollPane5 = new javax.swing.JScrollPane();
listPostponed = new javax.swing.JList();
buttonResetMainTablo = new javax.swing.JButton();
jScrollPane20 = new javax.swing.JScrollPane();
listBan = new javax.swing.JList();
buttonRefreshBan = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
jSplitPane1 = new javax.swing.JSplitPane();
jSplitPane2 = new javax.swing.JSplitPane();
jPanel25 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
treeServices = new javax.swing.JTree();
jButton5 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
textFieldSearchService = new javax.swing.JTextField();
jPanel26 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
listUserService = new javax.swing.JList();
jButton6 = new javax.swing.JButton();
jSplitPane3 = new javax.swing.JSplitPane();
jPanel11 = new javax.swing.JPanel();
jLabel17 = new javax.swing.JLabel();
textFieldUserName = new javax.swing.JTextField();
jLabel18 = new javax.swing.JLabel();
textFieldUserIdent = new javax.swing.JTextField();
jLabel19 = new javax.swing.JLabel();
spinnerUserRS = new javax.swing.JSpinner();
jLabel20 = new javax.swing.JLabel();
passwordFieldUser = new javax.swing.JPasswordField();
checkBoxReport = new javax.swing.JCheckBox();
checkBoxAdmin = new javax.swing.JCheckBox();
jLabel34 = new javax.swing.JLabel();
textFieldExtPoint = new javax.swing.JTextField();
tfUserId = new javax.swing.JTextField();
jPanel27 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
listUsers = new javax.swing.JList();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jScrollPane18 = new javax.swing.JScrollPane();
labelServiceInfo = new javax.swing.JLabel();
jScrollPane19 = new javax.swing.JScrollPane();
jScrollPane6 = new javax.swing.JScrollPane();
labelButtonCaption = new javax.swing.JLabel();
jPanel28 = new javax.swing.JPanel();
jScrollPane22 = new javax.swing.JScrollPane();
userServsList = new javax.swing.JList();
jPanel19 = new javax.swing.JPanel();
jScrollPane14 = new javax.swing.JScrollPane();
listCalendar = new javax.swing.JList();
jScrollPane15 = new javax.swing.JScrollPane();
tableCalendar = new javax.swing.JTable();
jLabel23 = new javax.swing.JLabel();
textFieldCalendarName = new javax.swing.JTextField();
buttonAddCalendar = new javax.swing.JButton();
buttonDeleteCalendar = new javax.swing.JButton();
jButton18 = new javax.swing.JButton();
jButton16 = new javax.swing.JButton();
jButton17 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jLabel36 = new javax.swing.JLabel();
spinCalendarYear = new javax.swing.JSpinner();
panelSpecSc = new javax.swing.JPanel();
jScrollPane23 = new javax.swing.JScrollPane();
listSpecSced = new javax.swing.JList();
butAddSpecSced = new javax.swing.JButton();
butEditSpecSced = new javax.swing.JButton();
butDeleteSpecSced = new javax.swing.JButton();
jPanel17 = new javax.swing.JPanel();
jScrollPane12 = new javax.swing.JScrollPane();
listSchedule = new javax.swing.JList();
jLabel21 = new javax.swing.JLabel();
textFieldScheduleName = new javax.swing.JTextField();
buttonScheduleAdd = new javax.swing.JButton();
buttonSchedulleDelete = new javax.swing.JButton();
labelSchedule = new javax.swing.JLabel();
jScrollPane21 = new javax.swing.JScrollPane();
listBreaks = new javax.swing.JList();
jButton13 = new javax.swing.JButton();
jButton14 = new javax.swing.JButton();
jButton19 = new javax.swing.JButton();
jButton20 = new javax.swing.JButton();
jPanel10 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
textFieldStartTime = new javax.swing.JTextField();
textFieldFinishTime = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
jSplitPane7 = new javax.swing.JSplitPane();
jPanel30 = new javax.swing.JPanel();
jScrollPane8 = new javax.swing.JScrollPane();
treeInfo = new javax.swing.JTree();
jButton9 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jPanel31 = new javax.swing.JPanel();
textFieldInfoItemName = new javax.swing.JTextField();
jSplitPane5 = new javax.swing.JSplitPane();
jScrollPane16 = new javax.swing.JScrollPane();
textPaneInfoPrint = new javax.swing.JTextPane();
jPanel29 = new javax.swing.JPanel();
butWysInfo1 = new javax.swing.JButton();
jSplitPane6 = new javax.swing.JSplitPane();
jScrollPane9 = new javax.swing.JScrollPane();
textPaneInfoItem = new javax.swing.JTextPane();
jPanel14 = new javax.swing.JPanel();
jScrollPane17 = new javax.swing.JScrollPane();
labelInfoItem = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jPanel13 = new javax.swing.JPanel();
jSplitPane8 = new javax.swing.JSplitPane();
jPanel32 = new javax.swing.JPanel();
jButton8 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jScrollPane25 = new javax.swing.JScrollPane();
treeResp = new javax.swing.JTree();
jSplitPane9 = new javax.swing.JSplitPane();
jPanel15 = new javax.swing.JPanel();
labelRespinse = new javax.swing.JLabel();
jPanel33 = new javax.swing.JPanel();
jLabel16 = new javax.swing.JLabel();
textFieldResponse = new javax.swing.JTextField();
btnWysResp1 = new javax.swing.JButton();
jScrollPane11 = new javax.swing.JScrollPane();
textPaneResponse = new javax.swing.JTextPane();
cbCommentForResp = new javax.swing.JCheckBox();
tfHeaderCmtResp = new javax.swing.JTextField();
jLabel37 = new javax.swing.JLabel();
tfRespID = new javax.swing.JTextField();
jPanel18 = new javax.swing.JPanel();
jButton11 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jPanel7 = new javax.swing.JPanel();
jLabel26 = new javax.swing.JLabel();
spinnerWaitMax = new javax.swing.JSpinner();
jLabel27 = new javax.swing.JLabel();
spinnerWorkMax = new javax.swing.JSpinner();
jLabel28 = new javax.swing.JLabel();
spinnerDowntimeNax = new javax.swing.JSpinner();
jLabel29 = new javax.swing.JLabel();
spinnerLineServiceMax = new javax.swing.JSpinner();
jLabel30 = new javax.swing.JLabel();
spinnerLineTotalMax = new javax.swing.JSpinner();
spinnerRelocation = new javax.swing.JSpinner();
jLabel35 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
spinnerBlackListTimeMin = new javax.swing.JSpinner();
spinnerRemoveRecall = new javax.swing.JSpinner();
jSplitPane4 = new javax.swing.JSplitPane();
jScrollPane7 = new javax.swing.JScrollPane();
listReposts = new javax.swing.JList();
jScrollPane13 = new javax.swing.JScrollPane();
listResults = new javax.swing.JList();
jPanel12 = new javax.swing.JPanel();
dateChooserStartCsv = new com.toedter.calendar.JDateChooser();
jLabel31 = new javax.swing.JLabel();
jLabel32 = new javax.swing.JLabel();
dateChooserFinishCsv = new com.toedter.calendar.JDateChooser();
jLabel33 = new javax.swing.JLabel();
cbSeparateCSV = new javax.swing.JComboBox();
buttonExportToCSV = new javax.swing.JButton();
jLabel25 = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
spinnerPropServerPort = new javax.swing.JSpinner();
spinnerWebServerPort = new javax.swing.JSpinner();
spinnerPropClientPort = new javax.swing.JSpinner();
jPanel16 = new javax.swing.JPanel();
spinnerFirstNumber = new javax.swing.JSpinner();
spinnerLastNumber = new javax.swing.JSpinner();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jPanel22 = new javax.swing.JPanel();
rbKindPersonal = new javax.swing.JRadioButton();
rbKindCommon = new javax.swing.JRadioButton();
chBoxBtnFreeDsn = new javax.swing.JCheckBox();
labExtPrior = new javax.swing.JLabel();
spinExtPrior = new javax.swing.JSpinner();
jTabbedPane2 = new javax.swing.JTabbedPane();
jPanel23 = new javax.swing.JPanel();
textFieldURLWebService = new javax.swing.JTextField();
spinnerBranchId = new javax.swing.JSpinner();
jLabel7 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
buttonCloudTest = new javax.swing.JButton();
buttonSendDataToSky = new javax.swing.JButton();
jPanel24 = new javax.swing.JPanel();
jLabel15 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
textFieldZonBoadrServAddr = new javax.swing.JTextField();
spinnerZonBoadrServPort = new javax.swing.JSpinner();
buttonCheckZoneBoardServ = new javax.swing.JButton();
propsPanel = new javax.swing.JPanel();
jSplitPane10 = new javax.swing.JSplitPane();
sectionPanel = new javax.swing.JPanel();
jScrollPane10 = new javax.swing.JScrollPane();
sectionsList = new javax.swing.JList<>();
btnDeleteSection = new javax.swing.JButton();
btnAddSection = new javax.swing.JButton();
keyvaluePanel = new javax.swing.JPanel();
jScrollPane26 = new javax.swing.JScrollPane();
propsTable = new javax.swing.JTable();
btnRemoveProp = new javax.swing.JButton();
btnAddProp = new javax.swing.JButton();
btnReloadProps = new javax.swing.JButton();
tabHide = new javax.swing.JPanel();
jScrollPane24 = new javax.swing.JScrollPane();
labHidePic = new javax.swing.JLabel();
panelPager = new javax.swing.JPanel();
labelPager = new javax.swing.JLabel();
panelPagerRadio = new javax.swing.JPanel();
rbPager1 = new javax.swing.JRadioButton();
rbPager2 = new javax.swing.JRadioButton();
rbPager3 = new javax.swing.JRadioButton();
panelPagerCombo = new javax.swing.JPanel();
labelPagerCaptionCombo = new javax.swing.JLabel();
comboBoxPager = new javax.swing.JComboBox();
panelEditPager = new javax.swing.JPanel();
labelPagerCaptionEdit = new javax.swing.JLabel();
textFieldPager = new javax.swing.JTextField();
buttonPagerEdit = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
menuFile = new javax.swing.JMenu();
menuLangs = new javax.swing.JMenu();
jSeparator15 = new javax.swing.JPopupMenu.Separator();
jMenuItem25 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
jMenuItem3 = new javax.swing.JMenuItem();
jMenu1 = new javax.swing.JMenu();
jMenuItem19 = new javax.swing.JMenuItem();
menuBoards = new javax.swing.JMenu();
rbmClassic = new javax.swing.JRadioButtonMenuItem();
rbmHtml = new javax.swing.JRadioButtonMenuItem();
menuUsers = new javax.swing.JMenu();
jMenuItem5 = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
jMenuItem2 = new javax.swing.JMenuItem();
jSeparator14 = new javax.swing.JPopupMenu.Separator();
jMenuItem37 = new javax.swing.JMenuItem();
jMenuItem43 = new javax.swing.JMenuItem();
menuServices = new javax.swing.JMenu();
jMenuItem7 = new javax.swing.JMenuItem();
jSeparator3 = new javax.swing.JSeparator();
jMenuItem6 = new javax.swing.JMenuItem();
jSeparator4 = new javax.swing.JSeparator();
jMenuItem9 = new javax.swing.JMenuItem();
jMenuItem23 = new javax.swing.JMenuItem();
menuAbout = new javax.swing.JMenu();
menuItemHelp = new javax.swing.JMenuItem();
menuItemAbout = new javax.swing.JMenuItem();
jSeparator17 = new javax.swing.JPopupMenu.Separator();
jMenuItemBagtracker = new javax.swing.JMenuItem();
jMenuItemForum = new javax.swing.JMenuItem();
popupUser.setName("popupUser"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application
.getInstance(ru.apertum.qsystem.QSystem.class).getContext()
.getActionMap(FAdmin.class, this);
jMenuItem1.setAction(actionMap.get("addUser")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
popupUser.add(jMenuItem1);
jMenuItem45.setAction(actionMap.get("addNewUserByCopy")); // NOI18N
jMenuItem45.setName("jMenuItem45"); // NOI18N
popupUser.add(jMenuItem45);
jMenuItem20.setAction(actionMap.get("renameUser")); // NOI18N
jMenuItem20.setName("jMenuItem20"); // NOI18N
popupUser.add(jMenuItem20);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application
.getInstance(ru.apertum.qsystem.QSystem.class).getContext()
.getResourceMap(FAdmin.class);
jMenuItemEditUser.setText(resourceMap.getString("jMenuItemEditUser.text")); // NOI18N
jMenuItemEditUser.setName("jMenuItemEditUser"); // NOI18N
jMenuItemEditUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemEditUserActionPerformed(evt);
}
});
popupUser.add(jMenuItemEditUser);
jSeparator7.setName("jSeparator7"); // NOI18N
popupUser.add(jSeparator7);
jMenuItem10.setAction(actionMap.get("deleteUser")); // NOI18N
jMenuItem10.setName("jMenuItem10"); // NOI18N
popupUser.add(jMenuItem10);
popupServices.setComponentPopupMenu(popupServices);
popupServices.setName("popupServices"); // NOI18N
popupServices.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
}
public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
}
public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
popupServicesPopupMenuWillBecomeVisible(evt);
}
});
jMenuItem11.setAction(actionMap.get("addService")); // NOI18N
jMenuItem11.setName("jMenuItem11"); // NOI18N
popupServices.add(jMenuItem11);
jMenuItem21.setAction(actionMap.get("renameService")); // NOI18N
jMenuItem21.setName("jMenuItem21"); // NOI18N
popupServices.add(jMenuItem21);
miCopyService.setText(resourceMap.getString("miCopyService.text")); // NOI18N
miCopyService.setName("miCopyService"); // NOI18N
miCopyService.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miCopyServiceActionPerformed(evt);
}
});
popupServices.add(miCopyService);
miCutService.setText(resourceMap.getString("miCutService.text")); // NOI18N
miCutService.setName("miCutService"); // NOI18N
miCutService.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miCutServiceActionPerformed(evt);
}
});
popupServices.add(miCutService);
miPasteService.setText(resourceMap.getString("miPasteService.text")); // NOI18N
miPasteService.setName("miPasteService"); // NOI18N
miPasteService.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miPasteServiceActionPerformed(evt);
}
});
popupServices.add(miPasteService);
jMenuItem13.setAction(actionMap.get("deleteService")); // NOI18N
jMenuItem13.setName("jMenuItem13"); // NOI18N
popupServices.add(jMenuItem13);
jSeparator8.setName("jSeparator8"); // NOI18N
popupServices.add(jSeparator8);
jMenuItem22.setAction(actionMap.get("editService")); // NOI18N
jMenuItem22.setName("jMenuItem22"); // NOI18N
popupServices.add(jMenuItem22);
jMenuItem42.setAction(actionMap.get("editLangs")); // NOI18N
jMenuItem42.setName("jMenuItem42"); // NOI18N
popupServices.add(jMenuItem42);
jMenuItem12.setAction(actionMap.get("addServiceToUser")); // NOI18N
jMenuItem12.setName("jMenuItem12"); // NOI18N
popupServices.add(jMenuItem12);
jSeparator5.setName("jSeparator5"); // NOI18N
popupServices.add(jSeparator5);
jMenuItem16.setAction(actionMap.get("getTicket")); // NOI18N
jMenuItem16.setName("jMenuItem16"); // NOI18N
popupServices.add(jMenuItem16);
jMenuItem24.setAction(actionMap.get("standAdvance")); // NOI18N
jMenuItem24.setName("jMenuItem24"); // NOI18N
popupServices.add(jMenuItem24);
jMenuItem44.setAction(actionMap.get("setDisableService")); // NOI18N
jMenuItem44.setName("jMenuItem44"); // NOI18N
popupServices.add(jMenuItem44);
popupServiceUser.setName("popupServiceUser"); // NOI18N
jMenuItem14.setAction(actionMap.get("changeServicePriority")); // NOI18N
jMenuItem14.setName("jMenuItem14"); // NOI18N
popupServiceUser.add(jMenuItem14);
jMenuItem38.setAction(actionMap.get("changeFlexiblePriorityAbility")); // NOI18N
jMenuItem38.setName("jMenuItem38"); // NOI18N
popupServiceUser.add(jMenuItem38);
jMenuItem17.setAction(actionMap.get("setUpdateServiceFire")); // NOI18N
jMenuItem17.setName("jMenuItem17"); // NOI18N
popupServiceUser.add(jMenuItem17);
jMenuItem18.setAction(actionMap.get("deleteUpdateServiceFire")); // NOI18N
jMenuItem18.setName("jMenuItem18"); // NOI18N
popupServiceUser.add(jMenuItem18);
jSeparator6.setName("jSeparator6"); // NOI18N
popupServiceUser.add(jSeparator6);
jMenuItem15.setAction(actionMap.get("deleteServiseFromUser")); // NOI18N
jMenuItem15.setName("jMenuItem15"); // NOI18N
popupServiceUser.add(jMenuItem15);
popupInfo.setName("popupInfo"); // NOI18N
jMenuItem26.setAction(actionMap.get("addInfoItem")); // NOI18N
jMenuItem26.setName("jMenuItem26"); // NOI18N
popupInfo.add(jMenuItem26);
jSeparator9.setName("jSeparator9"); // NOI18N
popupInfo.add(jSeparator9);
jMenuItem27.setAction(actionMap.get("deleteInfoItem")); // NOI18N
jMenuItem27.setName("jMenuItem27"); // NOI18N
popupInfo.add(jMenuItem27);
popupResponse.setName("popupResponse"); // NOI18N
jMenuItem28.setAction(actionMap.get("addRespItem")); // NOI18N
jMenuItem28.setName("jMenuItem28"); // NOI18N
popupResponse.add(jMenuItem28);
jSeparator10.setName("jSeparator10"); // NOI18N
popupResponse.add(jSeparator10);
jMenuItem29.setAction(actionMap.get("deleteRespItem")); // NOI18N
jMenuItem29.setName("jMenuItem29"); // NOI18N
popupResponse.add(jMenuItem29);
popupResults.setName("popupResults"); // NOI18N
jMenuItem30.setAction(actionMap.get("addResult")); // NOI18N
jMenuItem30.setName("jMenuItem30"); // NOI18N
popupResults.add(jMenuItem30);
jSeparator11.setName("jSeparator11"); // NOI18N
popupResults.add(jSeparator11);
jMenuItem31.setAction(actionMap.get("deleteResult")); // NOI18N
jMenuItem31.setName("jMenuItem31"); // NOI18N
popupResults.add(jMenuItem31);
popupPlans.setName("popupPlans"); // NOI18N
jMenuItem32.setAction(actionMap.get("addSchedule")); // NOI18N
jMenuItem32.setName("jMenuItem32"); // NOI18N
popupPlans.add(jMenuItem32);
jMenuItem33.setAction(actionMap.get("editSchedule")); // NOI18N
jMenuItem33.setName("jMenuItem33"); // NOI18N
popupPlans.add(jMenuItem33);
jSeparator12.setName("jSeparator12"); // NOI18N
popupPlans.add(jSeparator12);
jMenuItem34.setAction(actionMap.get("deleteSchedule")); // NOI18N
jMenuItem34.setName("jMenuItem34"); // NOI18N
popupPlans.add(jMenuItem34);
popupCalendar.setName("popupCalendar"); // NOI18N
jMenuItem35.setAction(actionMap.get("addCalendar")); // NOI18N
jMenuItem35.setName("jMenuItem35"); // NOI18N
popupCalendar.add(jMenuItem35);
jSeparator13.setName("jSeparator13"); // NOI18N
popupCalendar.add(jSeparator13);
jMenuItem36.setAction(actionMap.get("deleteCalendar")); // NOI18N
jMenuItem36.setName("jMenuItem36"); // NOI18N
popupCalendar.add(jMenuItem36);
popupBreaks.setName("popupBreaks"); // NOI18N
jMenuItem39.setAction(actionMap.get("addBreakToList")); // NOI18N
jMenuItem39.setName("jMenuItem39"); // NOI18N
popupBreaks.add(jMenuItem39);
jMenuItem40.setAction(actionMap.get("editBreak")); // NOI18N
jMenuItem40.setName("jMenuItem40"); // NOI18N
popupBreaks.add(jMenuItem40);
jSeparator16.setName("jSeparator16"); // NOI18N
popupBreaks.add(jSeparator16);
jMenuItem41.setAction(actionMap.get("deleteBreakFromList")); // NOI18N
jMenuItem41.setName("jMenuItem41"); // NOI18N
popupBreaks.add(jMenuItem41);
popupProps.setName("popupProps"); // NOI18N
muAddProp.setText(resourceMap.getString("muAddProp.text")); // NOI18N
muAddProp.setName("muAddProp"); // NOI18N
muAddProp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
muAddPropActionPerformed(evt);
}
});
popupProps.add(muAddProp);
muDeleteProp.setText(resourceMap.getString("muDeleteProp.text")); // NOI18N
muDeleteProp.setName("muDeleteProp"); // NOI18N
muDeleteProp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
muDeletePropActionPerformed(evt);
}
});
popupProps.add(muDeleteProp);
popupSections.setName("popupSections"); // NOI18N
miAddSection.setText(resourceMap.getString("miAddSection.text")); // NOI18N
miAddSection.setName("miAddSection"); // NOI18N
miAddSection.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miAddSectionActionPerformed(evt);
}
});
popupSections.add(miAddSection);
miDeleteSection.setText(resourceMap.getString("miDeleteSection.text")); // NOI18N
miDeleteSection.setName("miDeleteSection"); // NOI18N
miDeleteSection.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miDeleteSectionActionPerformed(evt);
}
});
popupSections.add(miDeleteSection);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(resourceMap.getString("Form.title")); // NOI18N
setName("Form"); // NOI18N
jPanel1.setBackground(resourceMap.getColor("jPanel1.background")); // NOI18N
jPanel1.setBorder(new javax.swing.border.MatteBorder(null));
jPanel1.setName("jPanel1"); // NOI18N
jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS));
tabbedPaneMain.setName("tabbedPaneMain"); // NOI18N
tabbedPaneMain.setPreferredSize(new java.awt.Dimension(1050, 550));
tabbedPaneMain.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
tabbedPaneMainStateChanged(evt);
}
});
tabbedPaneMain.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
tabbedPaneMainFocusLost(evt);
}
});
jPanel3.setBorder(new javax.swing.border.MatteBorder(null));
jPanel3.setAutoscrolls(true);
jPanel3.setName("jPanel3"); // NOI18N
jPanel5.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel5.border.title"))); // NOI18N
jPanel5.setName("jPanel5"); // NOI18N
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
textFieldClientAdress
.setText(resourceMap.getString("textFieldClientAdress.text")); // NOI18N
textFieldClientAdress.setName("textFieldClientAdress"); // NOI18N
textFieldClientAdress.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
textFieldClientAdressFocusLost(evt);
}
});
spinnerClientPort.setName("spinnerClientPort"); // NOI18N
spinnerClientPort.setValue(3128);
jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
jLabel5.setName("jLabel5"); // NOI18N
labelWelcomeState.setText(resourceMap.getString("labelWelcomeState.text")); // NOI18N
labelWelcomeState.setName("labelWelcomeState"); // NOI18N
checkBoxClientAuto.setText(resourceMap.getString("checkBoxClientAuto.text")); // NOI18N
checkBoxClientAuto.setName("checkBoxClientAuto"); // NOI18N
checkBoxClientAuto.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
checkBoxClientAutoStateChanged(evt);
}
});
checkBoxClientAuto.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
checkBoxClientAutoFocusLost(evt);
}
});
buttonClientRequest.setText(resourceMap.getString("buttonClientRequest.text")); // NOI18N
buttonClientRequest.setName("buttonClientRequest"); // NOI18N
buttonClientRequest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonClientRequestActionPerformed(evt);
}
});
buttonLock.setText(resourceMap.getString("buttonLock.text")); // NOI18N
buttonLock.setName("buttonLock"); // NOI18N
buttonLock.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonLockActionPerformed(evt);
}
});
buttonUnlock.setText(resourceMap.getString("buttonUnlock.text")); // NOI18N
buttonUnlock.setName("buttonUnlock"); // NOI18N
buttonUnlock.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonUnlockActionPerformed(evt);
}
});
buttonRestart.setText(resourceMap.getString("buttonRestart.text")); // NOI18N
buttonRestart.setName("buttonRestart"); // NOI18N
buttonRestart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRestartActionPerformed(evt);
}
});
buttonShutDown.setText(resourceMap.getString("buttonShutDown.text")); // NOI18N
buttonShutDown.setName("buttonShutDown"); // NOI18N
buttonShutDown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonShutDownActionPerformed(evt);
}
});
cbDropTicketsCnt.setText(resourceMap.getString("cbDropTicketsCnt.text")); // NOI18N
cbDropTicketsCnt.setName("cbDropTicketsCnt"); // NOI18N
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(spinnerClientPort)
.addComponent(textFieldClientAdress,
javax.swing.GroupLayout.PREFERRED_SIZE, 102,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(checkBoxClientAuto)
.addComponent(buttonClientRequest))
.addGap(18, 18, 18)
.addGroup(jPanel5Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
false)
.addComponent(buttonUnlock,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonRestart,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonShutDown,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonLock, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbDropTicketsCnt)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(labelWelcomeState, javax.swing.GroupLayout.DEFAULT_SIZE,
835,
Short.MAX_VALUE))
.addGap(119, 119, 119))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(textFieldClientAdress,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spinnerClientPort,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(checkBoxClientAuto)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonClientRequest))
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(buttonLock)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonUnlock)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonRestart)
.addComponent(cbDropTicketsCnt))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonShutDown)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelWelcomeState, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel6.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel6.border.title"))); // NOI18N
jPanel6.setName("jPanel6"); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
textFieldServerAddr.setText(resourceMap.getString("textFieldServerAddr.text")); // NOI18N
textFieldServerAddr.setName("textFieldServerAddr"); // NOI18N
textFieldServerAddr.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
textFieldServerAddrFocusLost(evt);
}
});
spinnerServerPort.setName("spinnerServerPort"); // NOI18N
spinnerServerPort.setValue(3128);
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
checkBoxServerAuto.setText(resourceMap.getString("checkBoxServerAuto.text")); // NOI18N
checkBoxServerAuto.setName("checkBoxServerAuto"); // NOI18N
checkBoxServerAuto.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
checkBoxServerAutoStateChanged(evt);
}
});
checkBoxServerAuto.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
checkBoxServerAutoFocusLost(evt);
}
});
buttonServerRequest.setText(resourceMap.getString("buttonServerRequest.text")); // NOI18N
buttonServerRequest.setName("buttonServerRequest"); // NOI18N
buttonServerRequest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonServerRequestActionPerformed(evt);
}
});
jScrollPane2.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("server_info"))); // NOI18N
jScrollPane2.setName("jScrollPane2"); // NOI18N
labelServerState.setText(resourceMap.getString("labelServerState.text")); // NOI18N
labelServerState.setVerticalAlignment(javax.swing.SwingConstants.TOP);
labelServerState.setName("labelServerState"); // NOI18N
jScrollPane2.setViewportView(labelServerState);
buttonRestartServer.setText(resourceMap.getString("buttonRestartServer.text")); // NOI18N
buttonRestartServer.setName("buttonRestartServer"); // NOI18N
buttonRestartServer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRestartServerActionPerformed(evt);
}
});
jScrollPane5.setName("jScrollPane5"); // NOI18N
listPostponed.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("listPostponed.border.title"))); // NOI18N
listPostponed.setName("listPostponed"); // NOI18N
jScrollPane5.setViewportView(listPostponed);
buttonResetMainTablo.setText(resourceMap.getString("buttonResetMainTablo.text")); // NOI18N
buttonResetMainTablo.setName("buttonResetMainTablo"); // NOI18N
buttonResetMainTablo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonResetMainTabloActionPerformed(evt);
}
});
jScrollPane20.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jScrollPane20.border.title"))); // NOI18N
jScrollPane20.setName("jScrollPane20"); // NOI18N
listBan.setName("listBan"); // NOI18N
jScrollPane20.setViewportView(listBan);
buttonRefreshBan.setText(resourceMap.getString("buttonRefreshBan.text")); // NOI18N
buttonRefreshBan.setName("buttonRefreshBan"); // NOI18N
buttonRefreshBan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRefreshBanActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
false)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(textFieldServerAddr,
javax.swing.GroupLayout.PREFERRED_SIZE, 100,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel6Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(spinnerServerPort)))
.addGap(18, 18, 18)
.addGroup(jPanel6Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(checkBoxServerAuto)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(buttonServerRequest)
.addGap(18, 18, 18)
.addComponent(buttonRestartServer)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(buttonResetMainTablo))))
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE,
237,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE,
516,
Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel6Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(buttonRefreshBan)
.addComponent(jScrollPane20, javax.swing.GroupLayout.PREFERRED_SIZE,
189,
javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(textFieldServerAddr,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkBoxServerAuto))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel6Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(spinnerServerPort, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonServerRequest)
.addComponent(buttonRestartServer)
.addComponent(buttonResetMainTablo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel6Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE,
193,
Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel6Layout.createSequentialGroup()
.addComponent(jScrollPane20)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonRefreshBan))
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE,
193,
Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
tabbedPaneMain
.addTab(resourceMap.getString("jPanel3.TabConstraints.tabTitle"), jPanel3); // NOI18N
jPanel4.setBorder(new javax.swing.border.MatteBorder(null));
jPanel4.setAutoscrolls(true);
jPanel4.setName("jPanel4"); // NOI18N
jSplitPane1.setDividerLocation(380);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setName("jSplitPane1"); // NOI18N
jSplitPane2.setDividerLocation(210);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setName("jSplitPane2"); // NOI18N
jPanel25.setName("jPanel25"); // NOI18N
jScrollPane3.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jScrollPane3.border.title"))); // NOI18N
jScrollPane3.setName("jScrollPane3"); // NOI18N
treeServices.setModel(null);
treeServices.setAutoscrolls(true);
treeServices.setComponentPopupMenu(popupServices);
treeServices.setDragEnabled(true);
treeServices.setDropMode(javax.swing.DropMode.ON);
treeServices.setName("treeServices"); // NOI18N
treeServices.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
treeServicesMouseClicked(evt);
}
});
treeServices.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
treeServicesKeyReleased(evt);
}
});
jScrollPane3.setViewportView(treeServices);
jButton5.setAction(actionMap.get("addServiceToUser")); // NOI18N
jButton5.setName("jButton5"); // NOI18N
jButton3.setAction(actionMap.get("deleteService")); // NOI18N
jButton3.setName("jButton3"); // NOI18N
jButton4.setAction(actionMap.get("addService")); // NOI18N
jButton4.setName("jButton4"); // NOI18N
textFieldSearchService
.setText(resourceMap.getString("textFieldSearchService.text")); // NOI18N
textFieldSearchService.setBorder(javax.swing.BorderFactory.createTitledBorder(
resourceMap.getString("textFieldSearchService.border.title"))); // NOI18N
textFieldSearchService.setName("textFieldSearchService"); // NOI18N
textFieldSearchService.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textFieldSearchServiceKeyReleased(evt);
}
});
javax.swing.GroupLayout jPanel25Layout = new javax.swing.GroupLayout(jPanel25);
jPanel25.setLayout(jPanel25Layout);
jPanel25Layout.setHorizontalGroup(
jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel25Layout.createSequentialGroup()
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45,
Short.MAX_VALUE)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3))
.addComponent(textFieldSearchService, javax.swing.GroupLayout.DEFAULT_SIZE, 374,
Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 374,
Short.MAX_VALUE)
);
jPanel25Layout.setVerticalGroup(
jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel25Layout.createSequentialGroup()
.addComponent(textFieldSearchService,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 227,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel25Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton5)
.addComponent(jButton3)
.addComponent(jButton4)))
);
jSplitPane2.setRightComponent(jPanel25);
jPanel26.setName("jPanel26"); // NOI18N
jScrollPane4.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jScrollPane4.border.title"))); // NOI18N
jScrollPane4.setName("jScrollPane4"); // NOI18N
listUserService.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
listUserService.setComponentPopupMenu(popupServiceUser);
listUserService.setName("listUserService"); // NOI18N
listUserService.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
listUserServiceMouseClicked(evt);
}
});
jScrollPane4.setViewportView(listUserService);
jButton6.setAction(actionMap.get("deleteServiseFromUser")); // NOI18N
jButton6.setName("jButton6"); // NOI18N
javax.swing.GroupLayout jPanel26Layout = new javax.swing.GroupLayout(jPanel26);
jPanel26.setLayout(jPanel26Layout);
jPanel26Layout.setHorizontalGroup(
jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel26Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton6)
.addGap(10, 10, 10))
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 209,
Short.MAX_VALUE)
);
jPanel26Layout.setVerticalGroup(
jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel26Layout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 272,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton6))
);
jSplitPane2.setLeftComponent(jPanel26);
jSplitPane1.setRightComponent(jSplitPane2);
jSplitPane3.setDividerLocation(170);
jSplitPane3.setDividerSize(0);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setName("jSplitPane3"); // NOI18N
jSplitPane3.setPreferredSize(new java.awt.Dimension(40, 25));
jPanel11.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel11.border.title"))); // NOI18N
jPanel11.setMinimumSize(new java.awt.Dimension(5, 5));
jPanel11.setName("jPanel11"); // NOI18N
jLabel17.setText(resourceMap.getString("jLabel17.text")); // NOI18N
jLabel17.setName("jLabel17"); // NOI18N
textFieldUserName.setEditable(false);
textFieldUserName.setText(resourceMap.getString("textFieldUserName.text")); // NOI18N
textFieldUserName.setName("textFieldUserName"); // NOI18N
jLabel18.setText(resourceMap.getString("jLabel18.text")); // NOI18N
jLabel18.setName("jLabel18"); // NOI18N
textFieldUserIdent.setText(resourceMap.getString("textFieldUserIdent.text")); // NOI18N
textFieldUserIdent.setName("textFieldUserIdent"); // NOI18N
textFieldUserIdent.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textFieldUserIdentKeyReleased(evt);
}
});
jLabel19.setText(resourceMap.getString("jLabel19.text")); // NOI18N
jLabel19.setName("jLabel19"); // NOI18N
spinnerUserRS.setEditor(new javax.swing.JSpinner.NumberEditor(spinnerUserRS, ""));
spinnerUserRS.setName("spinnerUserRS"); // NOI18N
jLabel20.setText(resourceMap.getString("jLabel20.text")); // NOI18N
jLabel20.setName("jLabel20"); // NOI18N
passwordFieldUser.setText(resourceMap.getString("passwordFieldUser.text")); // NOI18N
passwordFieldUser.setName("passwordFieldUser"); // NOI18N
passwordFieldUser.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
passwordFieldUserKeyReleased(evt);
}
});
checkBoxReport.setText(resourceMap.getString("checkBoxReport.text")); // NOI18N
checkBoxReport.setName("checkBoxReport"); // NOI18N
checkBoxReport.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
checkBoxReportMouseClicked(evt);
}
});
checkBoxAdmin.setText(resourceMap.getString("checkBoxAdmin.text")); // NOI18N
checkBoxAdmin.setName("checkBoxAdmin"); // NOI18N
checkBoxAdmin.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
checkBoxAdminMouseClicked(evt);
}
});
jLabel34.setText(resourceMap.getString("jLabel34.text")); // NOI18N
jLabel34.setName("jLabel34"); // NOI18N
textFieldExtPoint.setText(resourceMap.getString("textFieldExtPoint.text")); // NOI18N
textFieldExtPoint.setName("textFieldExtPoint"); // NOI18N
textFieldExtPoint.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textFieldExtPointKeyReleased(evt);
}
});
tfUserId.setEditable(false);
tfUserId.setFont(resourceMap.getFont("tfUserId.font")); // NOI18N
tfUserId.setText(resourceMap.getString("tfUserId.text")); // NOI18N
tfUserId.setName("tfUserId"); // NOI18N
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel11Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, 61,
Short.MAX_VALUE)
.addGap(86, 86, 86))
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(textFieldUserIdent,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
.addComponent(spinnerUserRS,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE))
.addGap(72, 72, 72))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(passwordFieldUser,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 137,
Short.MAX_VALUE)
.addComponent(textFieldUserName,
javax.swing.GroupLayout.DEFAULT_SIZE, 137,
Short.MAX_VALUE))
.addContainerGap())
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jLabel17)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfUserId))
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(checkBoxAdmin)
.addComponent(checkBoxReport)
.addComponent(jLabel20)
.addComponent(jLabel18))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())))
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(
jPanel11Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(textFieldExtPoint, javax.swing.GroupLayout.DEFAULT_SIZE,
147,
Short.MAX_VALUE)
.addGroup(jPanel11Layout.createSequentialGroup()
.addComponent(jLabel34)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(
jPanel11Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(tfUserId, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textFieldUserName, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel20)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(passwordFieldUser, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(checkBoxAdmin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(checkBoxReport)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textFieldUserIdent, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerUserRS, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel34)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textFieldExtPoint, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(3, Short.MAX_VALUE))
);
jSplitPane3.setLeftComponent(jPanel11);
jUserOfficePane = new javax.swing.JSplitPane();
popupOffice = new javax.swing.JPopupMenu();
jOfficePanel = new javax.swing.JPanel();
listOffices = new javax.swing.JList();
jOfficeScrollPane = new javax.swing.JScrollPane();
jAddOfficeButton = new javax.swing.JButton();
jDeleteOfficeButton = new javax.swing.JButton();
jOfficePanel.setName("jOfficePanel"); // NOI18N
jOfficeScrollPane.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanelOffices.scrollPane.title"))); // NOI18N
jOfficeScrollPane.setName("jScrollPane1"); // NOI18N
listOffices.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
listOffices.setComponentPopupMenu(popupOffice);
listOffices.setName("listOffices"); // NOI18N
jOfficeScrollPane.setViewportView(listOffices);
jAddOfficeButton.setAction(actionMap.get("addOffice")); // NOI18N
jAddOfficeButton.setName("jAddOfficeButton"); // NOI18N
jAddOfficeButton.setText(resourceMap.getString("jAddOfficeButton.text"));
jDeleteOfficeButton.setAction(actionMap.get("deleteOffice")); // NOI18N
jDeleteOfficeButton.setName("jDeleteOfficeButton"); // NOI18N
jDeleteOfficeButton.setText(resourceMap.getString("jDeleteOfficeButton.text"));
javax.swing.GroupLayout jOfficePanelLayout = new javax.swing.GroupLayout(jOfficePanel);
jOfficePanel.setLayout(jOfficePanelLayout);
jOfficePanelLayout.setHorizontalGroup(
jOfficePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jOfficePanelLayout.createSequentialGroup()
.addComponent(jAddOfficeButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48,
Short.MAX_VALUE)
.addComponent(jDeleteOfficeButton))
.addComponent(jOfficeScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 208,
Short.MAX_VALUE)
);
jOfficePanelLayout.setVerticalGroup(
jOfficePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jOfficePanelLayout.createSequentialGroup()
.addComponent(jOfficeScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 272,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jOfficePanelLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jAddOfficeButton)
.addComponent(jDeleteOfficeButton)))
);
jPanel27.setName("jPanel27"); // NOI18N
jScrollPane1.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jScrollPane1.border.title"))); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
listUsers.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
listUsers.setComponentPopupMenu(popupUser);
listUsers.setName("listUsers"); // NOI18N
jScrollPane1.setViewportView(listUsers);
jButton1.setAction(actionMap.get("addUser")); // NOI18N
jButton1.setName("jButton1"); // NOI18N
jButton2.setAction(actionMap.get("deleteUser")); // NOI18N
jButton2.setName("jButton2"); // NOI18N
javax.swing.GroupLayout jPanel27Layout = new javax.swing.GroupLayout(jPanel27);
jPanel27.setLayout(jPanel27Layout);
jPanel27Layout.setHorizontalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48,
Short.MAX_VALUE)
.addComponent(jButton2))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 208,
Short.MAX_VALUE)
);
jPanel27Layout.setVerticalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel27Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 272,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel27Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)))
);
jUserOfficePane.setLeftComponent(jOfficePanel);
jUserOfficePane.setRightComponent(jPanel27);
jSplitPane3.setRightComponent(jUserOfficePane);
jSplitPane1.setLeftComponent(jSplitPane3);
jTabbedPane1.setName("jTabbedPane1"); // NOI18N
jScrollPane18.setName("jScrollPane18"); // NOI18N
labelServiceInfo.setText(resourceMap.getString("labelServiceInfo.text")); // NOI18N
labelServiceInfo.setVerticalAlignment(javax.swing.SwingConstants.TOP);
labelServiceInfo.setName("labelServiceInfo"); // NOI18N
jScrollPane18.setViewportView(labelServiceInfo);
jTabbedPane1.addTab(resourceMap.getString("jScrollPane18.TabConstraints.tabTitle"),
jScrollPane18); // NOI18N
jScrollPane19.setName("jScrollPane19"); // NOI18N
jScrollPane6.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jScrollPane6.border.title"))); // NOI18N
jScrollPane6.setName("jScrollPane6"); // NOI18N
labelButtonCaption.setText(resourceMap.getString("labelButtonCaption.text")); // NOI18N
labelButtonCaption.setVerticalAlignment(javax.swing.SwingConstants.TOP);
labelButtonCaption.setName("labelButtonCaption"); // NOI18N
jScrollPane6.setViewportView(labelButtonCaption);
jScrollPane19.setViewportView(jScrollPane6);
jTabbedPane1.addTab(resourceMap.getString("jScrollPane19.TabConstraints.tabTitle"),
jScrollPane19); // NOI18N
jPanel28.setName("jPanel28"); // NOI18N
jScrollPane22.setName("jScrollPane22"); // NOI18N
userServsList.setName("userServsList"); // NOI18N
jScrollPane22.setViewportView(userServsList);
javax.swing.GroupLayout jPanel28Layout = new javax.swing.GroupLayout(jPanel28);
jPanel28.setLayout(jPanel28Layout);
jPanel28Layout.setHorizontalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 971,
Short.MAX_VALUE)
);
jPanel28Layout.setVerticalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 125,
Short.MAX_VALUE)
);
jTabbedPane1
.addTab(resourceMap.getString("jPanel28.TabConstraints.tabTitle"), jPanel28); // NOI18N
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jSplitPane1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jTabbedPane1.getAccessibleContext().setAccessibleName(
resourceMap.getString("jTabbedPane1.AccessibleContext.accessibleName")); // NOI18N
tabbedPaneMain
.addTab(resourceMap.getString("jPanel4.TabConstraints.tabTitle"), jPanel4); // NOI18N
jPanel19.setAutoscrolls(true);
jPanel19.setName("jPanel19"); // NOI18N
jScrollPane14.setName("jScrollPane14"); // NOI18N
listCalendar.setModel(new javax.swing.AbstractListModel() {
String[] strings = {"Общий календарь", " "};
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
listCalendar.setComponentPopupMenu(popupCalendar);
listCalendar.setName("listCalendar"); // NOI18N
jScrollPane14.setViewportView(listCalendar);
jScrollPane15.setName("jScrollPane15"); // NOI18N
tableCalendar.setModel(new javax.swing.table.DefaultTableModel(
new Object[][]{
{"Январь", null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null},
{"Февраль", null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null},
{"Март", null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null},
{"Апрель", null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null},
{"Май", null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null},
{"Июнь", null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null},
{"Июль", null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null},
{"Август", null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null},
{"Сентябрь", null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null},
{"Октябрь", null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null},
{"Ноябрь", null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null},
{"Декабрь", null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null, null, null, null}
},
new String[]{
" ", " 1", " 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9", " 10", " 11", " 12",
" 13",
" 14", " 15", " 16", " 17", " 18", " 19", " 20", " 21", " 22", " 23", " 24", " 25",
" 26", " 27", " 28", " 29", " 30", "31"
}
) {
Class[] types = new Class[]{
java.lang.String.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class,
java.lang.Object.class, java.lang.Object.class
};
boolean[] canEdit = new boolean[]{
false, true, true, true, true, true, true, true, true, true, true, true, true, true,
true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true,
true, true
};
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
tableCalendar.setCellSelectionEnabled(true);
tableCalendar.setName("tableCalendar"); // NOI18N
tableCalendar.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
tableCalendar.getTableHeader().setReorderingAllowed(false);
tableCalendar.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
tableCalendarFocusGained(evt);
}
});
jScrollPane15.setViewportView(tableCalendar);
jLabel23.setText(resourceMap.getString("jLabel23.text")); // NOI18N
jLabel23.setName("jLabel23"); // NOI18N
textFieldCalendarName
.setText(resourceMap.getString("textFieldCalendarName.text")); // NOI18N
textFieldCalendarName.setName("textFieldCalendarName"); // NOI18N
textFieldCalendarName.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textFieldCalendarNameKeyReleased(evt);
}
});
buttonAddCalendar.setAction(actionMap.get("addCalendar")); // NOI18N
buttonAddCalendar.setText(resourceMap.getString("buttonAddCalendar.text")); // NOI18N
buttonAddCalendar.setName("buttonAddCalendar"); // NOI18N
buttonDeleteCalendar.setAction(actionMap.get("deleteCalendar")); // NOI18N
buttonDeleteCalendar.setText(resourceMap.getString("buttonDeleteCalendar.text")); // NOI18N
buttonDeleteCalendar.setName("buttonDeleteCalendar"); // NOI18N
jButton18.setAction(actionMap.get("checkSundays")); // NOI18N
jButton18.setName("jButton18"); // NOI18N
jButton16.setAction(actionMap.get("checkSaturday")); // NOI18N
jButton16.setName("jButton16"); // NOI18N
jButton17.setAction(actionMap.get("dropCalendarSelection")); // NOI18N
jButton17.setText(resourceMap.getString("jButton17.text")); // NOI18N
jButton17.setName("jButton17"); // NOI18N
jButton15.setAction(actionMap.get("saveCalendar")); // NOI18N
jButton15.setText(resourceMap.getString("jButton15.text")); // NOI18N
jButton15.setName("jButton15"); // NOI18N
jLabel36.setText(resourceMap.getString("jLabel36.text")); // NOI18N
jLabel36.setName("jLabel36"); // NOI18N
spinCalendarYear.setModel(new javax.swing.SpinnerNumberModel(2015, 2014, 2050, 1));
spinCalendarYear.setEditor(new javax.swing.JSpinner.NumberEditor(spinCalendarYear, ""));
spinCalendarYear.setFocusable(false);
spinCalendarYear.setName("spinCalendarYear"); // NOI18N
spinCalendarYear.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
spinCalendarYearStateChanged(evt);
}
});
panelSpecSc.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("panelSpecSc.border.title"))); // NOI18N
panelSpecSc.setName("panelSpecSc"); // NOI18N
jScrollPane23.setName("jScrollPane23"); // NOI18N
listSpecSced.setModel(new javax.swing.AbstractListModel() {
String[] strings = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
listSpecSced.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
listSpecSced.setName("listSpecSced"); // NOI18N
listSpecSced.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
listSpecScedMouseClicked(evt);
}
});
jScrollPane23.setViewportView(listSpecSced);
butAddSpecSced.setText(resourceMap.getString("butAddSpecSced.text")); // NOI18N
butAddSpecSced.setName("butAddSpecSced"); // NOI18N
butAddSpecSced.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butAddSpecScedActionPerformed(evt);
}
});
butEditSpecSced.setText(resourceMap.getString("butEditSpecSced.text")); // NOI18N
butEditSpecSced.setName("butEditSpecSced"); // NOI18N
butEditSpecSced.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butEditSpecScedActionPerformed(evt);
}
});
butDeleteSpecSced.setText(resourceMap.getString("butDeleteSpecSced.text")); // NOI18N
butDeleteSpecSced.setName("butDeleteSpecSced"); // NOI18N
butDeleteSpecSced.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butDeleteSpecScedActionPerformed(evt);
}
});
javax.swing.GroupLayout panelSpecScLayout = new javax.swing.GroupLayout(panelSpecSc);
panelSpecSc.setLayout(panelSpecScLayout);
panelSpecScLayout.setHorizontalGroup(
panelSpecScLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
panelSpecScLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(butDeleteSpecSced)
.addGap(18, 18, 18)
.addComponent(butEditSpecSced)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(butAddSpecSced)
.addContainerGap())
.addComponent(jScrollPane23)
);
panelSpecScLayout.setVerticalGroup(
panelSpecScLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelSpecScLayout.createSequentialGroup()
.addComponent(jScrollPane23, javax.swing.GroupLayout.DEFAULT_SIZE, 81,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelSpecScLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(butAddSpecSced)
.addComponent(butEditSpecSced)
.addComponent(butDeleteSpecSced)))
);
javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
jPanel19.setLayout(jPanel19Layout);
jPanel19Layout.setHorizontalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel19Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addComponent(buttonAddCalendar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonDeleteCalendar,
javax.swing.GroupLayout.PREFERRED_SIZE, 87,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel19Layout.createSequentialGroup()
.addComponent(jScrollPane14, javax.swing.GroupLayout.PREFERRED_SIZE,
215, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel19Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane15,
javax.swing.GroupLayout.DEFAULT_SIZE,
757, Short.MAX_VALUE)
.addGroup(jPanel19Layout.createSequentialGroup()
.addComponent(jLabel23)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(textFieldCalendarName,
javax.swing.GroupLayout.DEFAULT_SIZE, 515,
Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jLabel36)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinCalendarYear,
javax.swing.GroupLayout.PREFERRED_SIZE, 60,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel19Layout.createSequentialGroup()
.addComponent(jButton18)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton16)
.addGap(18, 18, 18)
.addComponent(jButton17)
.addGap(18, 18, 18)
.addComponent(jButton15)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(panelSpecSc, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
jPanel19Layout.setVerticalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel19Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addGroup(jPanel19Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel23)
.addComponent(textFieldCalendarName,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(spinCalendarYear,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel36))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane15, javax.swing.GroupLayout.PREFERRED_SIZE,
243, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel19Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton18)
.addComponent(jButton16)
.addComponent(jButton17)
.addComponent(jButton15))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelSpecSc, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 437,
Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel19Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonAddCalendar)
.addComponent(buttonDeleteCalendar))
.addContainerGap())
);
tabbedPaneMain
.addTab(resourceMap.getString("jPanel19.TabConstraints.tabTitle"), jPanel19); // NOI18N
jPanel17.setAutoscrolls(true);
jPanel17.setName("jPanel17"); // NOI18N
jScrollPane12.setName("jScrollPane12"); // NOI18N
listSchedule.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("listSchedule.border.title"))); // NOI18N
listSchedule.setModel(new javax.swing.AbstractListModel() {
String[] strings = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
listSchedule.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
listSchedule.setComponentPopupMenu(popupPlans);
listSchedule.setName("listSchedule"); // NOI18N
listSchedule.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
listScheduleMouseClicked(evt);
}
});
jScrollPane12.setViewportView(listSchedule);
listSchedule.getAccessibleContext().setAccessibleName(
resourceMap.getString("jList1.AccessibleContext.accessibleName")); // NOI18N
jLabel21.setText(resourceMap.getString("jLabel21.text")); // NOI18N
jLabel21.setName("jLabel21"); // NOI18N
textFieldScheduleName.setEditable(false);
textFieldScheduleName
.setText(resourceMap.getString("textFieldScheduleName.text")); // NOI18N
textFieldScheduleName.setBorder(javax.swing.BorderFactory.createEtchedBorder());
textFieldScheduleName.setFocusable(false);
textFieldScheduleName.setName("textFieldScheduleName"); // NOI18N
textFieldScheduleName.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textFieldScheduleNameKeyReleased(evt);
}
});
buttonScheduleAdd.setAction(actionMap.get("addSchedule")); // NOI18N
buttonScheduleAdd.setText(resourceMap.getString("buttonScheduleAdd.text")); // NOI18N
buttonScheduleAdd.setName("buttonScheduleAdd"); // NOI18N
buttonSchedulleDelete.setAction(actionMap.get("deleteSchedule")); // NOI18N
buttonSchedulleDelete
.setText(resourceMap.getString("buttonSchedulleDelete.text")); // NOI18N
buttonSchedulleDelete.setName("buttonSchedulleDelete"); // NOI18N
labelSchedule.setText(resourceMap.getString("labelSchedule.text")); // NOI18N
labelSchedule.setVerticalAlignment(javax.swing.SwingConstants.TOP);
labelSchedule.setName("labelSchedule"); // NOI18N
jScrollPane21.setName("jScrollPane21"); // NOI18N
listBreaks.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("listBreaks.border.title"))); // NOI18N
listBreaks.setComponentPopupMenu(popupBreaks);
listBreaks.setName("listBreaks"); // NOI18N
listBreaks.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
listBreaksMouseClicked(evt);
}
});
jScrollPane21.setViewportView(listBreaks);
jButton13.setAction(actionMap.get("editSchedule")); // NOI18N
jButton13.setName("jButton13"); // NOI18N
jButton14.setAction(actionMap.get("addBreakToList")); // NOI18N
jButton14.setName("jButton14"); // NOI18N
jButton19.setAction(actionMap.get("deleteBreakFromList")); // NOI18N
jButton19.setName("jButton19"); // NOI18N
jButton20.setAction(actionMap.get("editBreak")); // NOI18N
jButton20.setName("jButton20"); // NOI18N
jPanel10.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel10.border.title"))); // NOI18N
jPanel10.setName("jPanel10"); // NOI18N
jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
jLabel10.setName("jLabel10"); // NOI18N
jLabel14.setText(resourceMap.getString("jLabel14.text")); // NOI18N
jLabel14.setName("jLabel14"); // NOI18N
textFieldStartTime.setText(resourceMap.getString("textFieldStartTime.text")); // NOI18N
textFieldStartTime.setName("textFieldStartTime"); // NOI18N
textFieldFinishTime.setText(resourceMap.getString("textFieldFinishTime.text")); // NOI18N
textFieldFinishTime.setName("textFieldFinishTime"); // NOI18N
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel10Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel14))
.addGap(30, 30, 30)
.addGroup(
jPanel10Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(textFieldStartTime,
javax.swing.GroupLayout.PREFERRED_SIZE,
43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textFieldFinishTime,
javax.swing.GroupLayout.PREFERRED_SIZE,
43, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel10Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel10Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldStartTime,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel10Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldFinishTime,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel14))
.addContainerGap())
);
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel17Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton13)
.addComponent(buttonScheduleAdd)
.addComponent(jScrollPane12, javax.swing.GroupLayout.PREFERRED_SIZE,
231,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonSchedulleDelete))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel17Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addGroup(jPanel17Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelSchedule,
javax.swing.GroupLayout.DEFAULT_SIZE,
430, Short.MAX_VALUE)
.addGroup(jPanel17Layout.createSequentialGroup()
.addComponent(jLabel21)
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(18, 18, 18))
.addGroup(jPanel17Layout.createSequentialGroup()
.addGroup(jPanel17Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel10,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textFieldScheduleName))
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(
jPanel17Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton20, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton14, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane21, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.PREFERRED_SIZE, 293,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton19, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel17Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addGroup(jPanel17Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel17Layout.createSequentialGroup()
.addComponent(jScrollPane21,
javax.swing.GroupLayout.DEFAULT_SIZE, 379,
Short.MAX_VALUE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton14)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton20))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel17Layout.createSequentialGroup()
.addComponent(jScrollPane12,
javax.swing.GroupLayout.DEFAULT_SIZE, 379,
Short.MAX_VALUE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonScheduleAdd)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton13)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel17Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton19)
.addComponent(buttonSchedulleDelete))
.addContainerGap())
.addGroup(jPanel17Layout.createSequentialGroup()
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textFieldScheduleName,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelSchedule, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))))
);
tabbedPaneMain
.addTab(resourceMap.getString("jPanel17.TabConstraints.tabTitle"), jPanel17); // NOI18N
jPanel2.setAutoscrolls(true);
jPanel2.setName("jPanel2"); // NOI18N
jSplitPane7.setDividerLocation(350);
jSplitPane7.setContinuousLayout(true);
jSplitPane7.setName("jSplitPane7"); // NOI18N
jPanel30.setName("jPanel30"); // NOI18N
jScrollPane8.setName("jScrollPane8"); // NOI18N
treeInfo.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("treeInfo.border.title"))); // NOI18N
treeInfo.setComponentPopupMenu(popupInfo);
treeInfo.setName("treeInfo"); // NOI18N
treeInfo.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
treeInfoMouseClicked(evt);
}
});
jScrollPane8.setViewportView(treeInfo);
jButton9.setAction(actionMap.get("addInfoItem")); // NOI18N
jButton9.setName("jButton9"); // NOI18N
jButton10.setAction(actionMap.get("deleteInfoItem")); // NOI18N
jButton10.setName("jButton10"); // NOI18N
javax.swing.GroupLayout jPanel30Layout = new javax.swing.GroupLayout(jPanel30);
jPanel30.setLayout(jPanel30Layout);
jPanel30Layout.setHorizontalGroup(
jPanel30Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane8)
.addGroup(jPanel30Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton10)
.addContainerGap(85, Short.MAX_VALUE))
);
jPanel30Layout.setVerticalGroup(
jPanel30Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel30Layout.createSequentialGroup()
.addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, 446,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel30Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton9)
.addComponent(jButton10))
.addContainerGap())
);
jSplitPane7.setLeftComponent(jPanel30);
jPanel31.setName("jPanel31"); // NOI18N
textFieldInfoItemName
.setText(resourceMap.getString("textFieldInfoItemName.text")); // NOI18N
textFieldInfoItemName.setName("textFieldInfoItemName"); // NOI18N
textFieldInfoItemName.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textFieldInfoItemNameKeyReleased(evt);
}
});
jSplitPane5.setDividerLocation(310);
jSplitPane5.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jSplitPane5.setContinuousLayout(true);
jSplitPane5.setName("jSplitPane5"); // NOI18N
jScrollPane16.setName("jScrollPane16"); // NOI18N
textPaneInfoPrint.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("textPaneInfoPrint.border.title"))); // NOI18N
textPaneInfoPrint.setName("textPaneInfoPrint"); // NOI18N
textPaneInfoPrint.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textPaneInfoPrintKeyReleased(evt);
}
});
jScrollPane16.setViewportView(textPaneInfoPrint);
textPaneInfoPrint.getAccessibleContext().setAccessibleName(
resourceMap.getString("jTextPane1.AccessibleContext.accessibleName")); // NOI18N
jSplitPane5.setBottomComponent(jScrollPane16);
jPanel29.setName("jPanel29"); // NOI18N
butWysInfo1.setText(resourceMap.getString("butWysInfo1.text")); // NOI18N
butWysInfo1.setName("butWysInfo1"); // NOI18N
butWysInfo1.setPreferredSize(new java.awt.Dimension(81, 15));
butWysInfo1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
butWysInfo1ActionPerformed(evt);
}
});
jSplitPane6.setDividerLocation(165);
jSplitPane6.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jSplitPane6.setContinuousLayout(true);
jSplitPane6.setName("jSplitPane6"); // NOI18N
jScrollPane9.setName("jScrollPane9"); // NOI18N
textPaneInfoItem.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("textPaneInfoItem.border.title"))); // NOI18N
textPaneInfoItem.setName("textPaneInfoItem"); // NOI18N
textPaneInfoItem.setPreferredSize(new java.awt.Dimension(18, 200));
textPaneInfoItem.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textPaneInfoItemKeyReleased(evt);
}
});
jScrollPane9.setViewportView(textPaneInfoItem);
jSplitPane6.setTopComponent(jScrollPane9);
jPanel14.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel14.border.title"))); // NOI18N
jPanel14.setName("jPanel14"); // NOI18N
jPanel14.setPreferredSize(new java.awt.Dimension(626, 200));
jScrollPane17.setName("jScrollPane17"); // NOI18N
labelInfoItem.setText(resourceMap.getString("labelInfoItem.text")); // NOI18N
labelInfoItem.setVerticalAlignment(javax.swing.SwingConstants.TOP);
labelInfoItem.setName("labelInfoItem"); // NOI18N
jScrollPane17.setViewportView(labelInfoItem);
javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 626,
Short.MAX_VALUE)
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 94,
Short.MAX_VALUE)
);
jSplitPane6.setRightComponent(jPanel14);
javax.swing.GroupLayout jPanel29Layout = new javax.swing.GroupLayout(jPanel29);
jPanel29.setLayout(jPanel29Layout);
jPanel29Layout.setHorizontalGroup(
jPanel29Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel29Layout.createSequentialGroup()
.addComponent(butWysInfo1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jSplitPane6, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
);
jPanel29Layout.setVerticalGroup(
jPanel29Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel29Layout.createSequentialGroup()
.addComponent(butWysInfo1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSplitPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 288,
Short.MAX_VALUE))
);
jSplitPane5.setLeftComponent(jPanel29);
jLabel22.setText(resourceMap.getString("jLabel22.text")); // NOI18N
jLabel22.setName("jLabel22"); // NOI18N
javax.swing.GroupLayout jPanel31Layout = new javax.swing.GroupLayout(jPanel31);
jPanel31.setLayout(jPanel31Layout);
jPanel31Layout.setHorizontalGroup(
jPanel31Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane5)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel31Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel22)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textFieldInfoItemName)
.addContainerGap())
);
jPanel31Layout.setVerticalGroup(
jPanel31Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel31Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel31Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldInfoItemName,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSplitPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 449,
Short.MAX_VALUE))
);
jSplitPane7.setRightComponent(jPanel31);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane7)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane7)
);
tabbedPaneMain
.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N
jPanel13.setAutoscrolls(true);
jPanel13.setName("jPanel13"); // NOI18N
jSplitPane8.setDividerLocation(300);
jSplitPane8.setContinuousLayout(true);
jSplitPane8.setName("jSplitPane8"); // NOI18N
jPanel32.setName("jPanel32"); // NOI18N
jButton8.setAction(actionMap.get("addRespItem")); // NOI18N
jButton8.setName("jButton8"); // NOI18N
jButton7.setAction(actionMap.get("deleteRespItem")); // NOI18N
jButton7.setName("jButton7"); // NOI18N
jScrollPane25.setName("jScrollPane25"); // NOI18N
treeResp.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("treeResp.border.title"))); // NOI18N
treeResp.setName("treeResp"); // NOI18N
jScrollPane25.setViewportView(treeResp);
javax.swing.GroupLayout jPanel32Layout = new javax.swing.GroupLayout(jPanel32);
jPanel32.setLayout(jPanel32Layout);
jPanel32Layout.setHorizontalGroup(
jPanel32Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel32Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton7)
.addContainerGap(55, Short.MAX_VALUE))
.addComponent(jScrollPane25)
);
jPanel32Layout.setVerticalGroup(
jPanel32Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel32Layout.createSequentialGroup()
.addComponent(jScrollPane25, javax.swing.GroupLayout.DEFAULT_SIZE, 446,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel32Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton8)
.addComponent(jButton7))
.addContainerGap())
);
jSplitPane8.setLeftComponent(jPanel32);
jSplitPane9.setDividerLocation(330);
jSplitPane9.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jSplitPane9.setContinuousLayout(true);
jSplitPane9.setName("jSplitPane9"); // NOI18N
jPanel15.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel15.border.title"))); // NOI18N
jPanel15.setName("jPanel15"); // NOI18N
labelRespinse.setText(resourceMap.getString("labelRespinse.text")); // NOI18N
labelRespinse.setVerticalAlignment(javax.swing.SwingConstants.TOP);
labelRespinse.setName("labelRespinse"); // NOI18N
javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(labelRespinse, javax.swing.GroupLayout.DEFAULT_SIZE, 658,
Short.MAX_VALUE)
.addContainerGap())
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addComponent(labelRespinse, javax.swing.GroupLayout.DEFAULT_SIZE, 116,
Short.MAX_VALUE)
.addContainerGap())
);
jSplitPane9.setBottomComponent(jPanel15);
jPanel33.setName("jPanel33"); // NOI18N
jLabel16.setText(resourceMap.getString("jLabel16.text")); // NOI18N
jLabel16.setName("jLabel16"); // NOI18N
textFieldResponse.setText(resourceMap.getString("textFieldResponse.text")); // NOI18N
textFieldResponse.setName("textFieldResponse"); // NOI18N
textFieldResponse.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textFieldResponseKeyReleased(evt);
}
});
btnWysResp1.setText(resourceMap.getString("btnWysResp1.text")); // NOI18N
btnWysResp1.setName("btnWysResp1"); // NOI18N
btnWysResp1.setPreferredSize(new java.awt.Dimension(79, 15));
btnWysResp1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnWysResp1ActionPerformed(evt);
}
});
jScrollPane11.setName("jScrollPane11"); // NOI18N
textPaneResponse.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("textPaneResponse.border.title"))); // NOI18N
textPaneResponse.setName("textPaneResponse"); // NOI18N
textPaneResponse.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
textPaneResponseKeyReleased(evt);
}
});
jScrollPane11.setViewportView(textPaneResponse);
cbCommentForResp.setText(resourceMap.getString("cbCommentForResp.text")); // NOI18N
cbCommentForResp.setName("cbCommentForResp"); // NOI18N
cbCommentForResp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbCommentForRespActionPerformed(evt);
}
});
tfHeaderCmtResp.setText(resourceMap.getString("tfHeaderCmtResp.text")); // NOI18N
tfHeaderCmtResp.setName("tfHeaderCmtResp"); // NOI18N
tfHeaderCmtResp.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
tfHeaderCmtRespKeyReleased(evt);
}
});
jLabel37.setText(resourceMap.getString("jLabel37.text")); // NOI18N
jLabel37.setName("jLabel37"); // NOI18N
tfRespID.setEditable(false);
tfRespID.setText(resourceMap.getString("tfRespID.text")); // NOI18N
tfRespID.setName("tfRespID"); // NOI18N
javax.swing.GroupLayout jPanel33Layout = new javax.swing.GroupLayout(jPanel33);
jPanel33.setLayout(jPanel33Layout);
jPanel33Layout.setHorizontalGroup(
jPanel33Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane11)
.addGroup(jPanel33Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel33Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel33Layout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textFieldResponse,
javax.swing.GroupLayout.DEFAULT_SIZE,
422, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfRespID, javax.swing.GroupLayout.PREFERRED_SIZE, 125,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel33Layout.createSequentialGroup()
.addComponent(jLabel37)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfHeaderCmtResp))
.addGroup(jPanel33Layout.createSequentialGroup()
.addGroup(jPanel33Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cbCommentForResp)
.addComponent(btnWysResp1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel33Layout.setVerticalGroup(
jPanel33Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel33Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel33Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldResponse, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel16)
.addComponent(tfRespID, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbCommentForResp)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel33Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tfHeaderCmtResp, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel37))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnWysResp1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane11, javax.swing.GroupLayout.DEFAULT_SIZE, 224,
Short.MAX_VALUE))
);
jSplitPane9.setLeftComponent(jPanel33);
jSplitPane8.setRightComponent(jSplitPane9);
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane8)
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane8, javax.swing.GroupLayout.Alignment.TRAILING)
);
tabbedPaneMain
.addTab(resourceMap.getString("jPanel13.TabConstraints.tabTitle"), jPanel13); // NOI18N
jPanel18.setAutoscrolls(true);
jPanel18.setName("jPanel18"); // NOI18N
jButton11.setAction(actionMap.get("addResult")); // NOI18N
jButton11.setText(resourceMap.getString("jButton11.text")); // NOI18N
jButton11.setName("jButton11"); // NOI18N
jButton12.setAction(actionMap.get("deleteResult")); // NOI18N
jButton12.setName("jButton12"); // NOI18N
jPanel7.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel7.border.title"))); // NOI18N
jPanel7.setName("jPanel7"); // NOI18N
jLabel26.setText(resourceMap.getString("jLabel26.text")); // NOI18N
jLabel26.setName("jLabel26"); // NOI18N
spinnerWaitMax.setModel(new javax.swing.SpinnerNumberModel(0, 0, 60, 1));
spinnerWaitMax.setName("spinnerWaitMax"); // NOI18N
jLabel27.setText(resourceMap.getString("jLabel27.text")); // NOI18N
jLabel27.setName("jLabel27"); // NOI18N
spinnerWorkMax.setModel(new javax.swing.SpinnerNumberModel(0, 0, 600, 1));
spinnerWorkMax.setName("spinnerWorkMax"); // NOI18N
jLabel28.setText(resourceMap.getString("jLabel28.text")); // NOI18N
jLabel28.setName("jLabel28"); // NOI18N
spinnerDowntimeNax.setModel(new javax.swing.SpinnerNumberModel(0, 0, 600, 1));
spinnerDowntimeNax.setName("spinnerDowntimeNax"); // NOI18N
jLabel29.setText(resourceMap.getString("jLabel29.text")); // NOI18N
jLabel29.setName("jLabel29"); // NOI18N
spinnerLineServiceMax.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));
spinnerLineServiceMax.setName("spinnerLineServiceMax"); // NOI18N
jLabel30.setText(resourceMap.getString("jLabel30.text")); // NOI18N
jLabel30.setName("jLabel30"); // NOI18N
spinnerLineTotalMax.setModel(new javax.swing.SpinnerNumberModel(0, 0, 1000, 1));
spinnerLineTotalMax.setName("spinnerLineTotalMax"); // NOI18N
spinnerRelocation.setModel(new javax.swing.SpinnerNumberModel(1, 1, 600, 1));
spinnerRelocation.setName("spinnerRelocation"); // NOI18N
jLabel35.setText(resourceMap.getString("jLabel35.text")); // NOI18N
jLabel35.setName("jLabel35"); // NOI18N
jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
jLabel6.setName("jLabel6"); // NOI18N
spinnerBlackListTimeMin.setModel(new javax.swing.SpinnerNumberModel(0, 0, 1440, 1));
spinnerBlackListTimeMin.setName("spinnerBlackListTimeMin"); // NOI18N
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel26)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerWaitMax,
javax.swing.GroupLayout.PREFERRED_SIZE,
47, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel27)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerWorkMax,
javax.swing.GroupLayout.PREFERRED_SIZE,
49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel28)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerDowntimeNax,
javax.swing.GroupLayout.PREFERRED_SIZE, 49,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel29)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerLineServiceMax,
javax.swing.GroupLayout.PREFERRED_SIZE, 46,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel30)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerLineTotalMax,
javax.swing.GroupLayout.PREFERRED_SIZE, 55,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel35)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerRelocation,
javax.swing.GroupLayout.PREFERRED_SIZE,
54, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerBlackListTimeMin,
javax.swing.GroupLayout.PREFERRED_SIZE, 51,
javax.swing.GroupLayout.PREFERRED_SIZE))))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel7Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(spinnerWaitMax, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(
jPanel7Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel27)
.addComponent(spinnerWorkMax, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(
jPanel7Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel28)
.addComponent(spinnerDowntimeNax,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(
jPanel7Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel29)
.addComponent(spinnerLineServiceMax,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(
jPanel7Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel30)
.addComponent(spinnerLineTotalMax,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel7Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel35)
.addComponent(spinnerRelocation, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel7Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(spinnerBlackListTimeMin,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
spinnerRemoveRecall.setModel(new javax.swing.SpinnerNumberModel(0, 0, 5, 1));
spinnerRemoveRecall.setName("spinnerRemoveRecall"); // NOI18N
jSplitPane4.setDividerLocation(300);
jSplitPane4.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jSplitPane4.setAutoscrolls(true);
jSplitPane4.setContinuousLayout(true);
jSplitPane4.setName("jSplitPane4"); // NOI18N
jScrollPane7.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jScrollPane7.border.title"))); // NOI18N
jScrollPane7.setName("jScrollPane7"); // NOI18N
listReposts.setModel(new javax.swing.AbstractListModel() {
String[] strings = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
listReposts.setName("listReposts"); // NOI18N
jScrollPane7.setViewportView(listReposts);
jSplitPane4.setTopComponent(jScrollPane7);
jScrollPane13.setName("jScrollPane13"); // NOI18N
listResults.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("listResults.border.title"))); // NOI18N
listResults.setModel(new javax.swing.AbstractListModel() {
String[] strings = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
listResults.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
listResults.setComponentPopupMenu(popupResults);
listResults.setName("listResults"); // NOI18N
jScrollPane13.setViewportView(listResults);
jSplitPane4.setBottomComponent(jScrollPane13);
jPanel12.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel12.border.title"))); // NOI18N
jPanel12.setName("jPanel12"); // NOI18N
dateChooserStartCsv.setDate(new Date());
dateChooserStartCsv.setName("dateChooserStartCsv"); // NOI18N
jLabel31.setText(resourceMap.getString("jLabel31.text")); // NOI18N
jLabel31.setName("jLabel31"); // NOI18N
jLabel32.setText(resourceMap.getString("jLabel32.text")); // NOI18N
jLabel32.setName("jLabel32"); // NOI18N
dateChooserFinishCsv.setDate(new Date());
dateChooserFinishCsv.setName("dateChooserFinishCsv"); // NOI18N
jLabel33.setText(resourceMap.getString("jLabel33.text")); // NOI18N
jLabel33.setName("jLabel33"); // NOI18N
cbSeparateCSV.setEditable(true);
cbSeparateCSV
.setModel(new javax.swing.DefaultComboBoxModel(new String[]{";", ",", "#", "\\t"}));
cbSeparateCSV.setName("cbSeparateCSV"); // NOI18N
buttonExportToCSV.setText(resourceMap.getString("buttonExportToCSV.text")); // NOI18N
buttonExportToCSV.setName("buttonExportToCSV"); // NOI18N
buttonExportToCSV.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonExportToCSVActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel12Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel31)
.addComponent(jLabel32)
.addComponent(jLabel33))
.addGap(18, 18, 18)
.addGroup(jPanel12Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(dateChooserFinishCsv, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(dateChooserStartCsv, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbSeparateCSV, javax.swing.GroupLayout.Alignment.TRAILING, 0,
102,
Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45,
Short.MAX_VALUE)
.addComponent(buttonExportToCSV)
.addContainerGap())
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel12Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addGroup(jPanel12Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel31)
.addComponent(dateChooserStartCsv,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel12Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel32)
.addComponent(dateChooserFinishCsv,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel12Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel33)
.addComponent(cbSeparateCSV,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(buttonExportToCSV,
javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
jLabel25.setText(resourceMap.getString("jLabel25.text")); // NOI18N
jLabel25.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabel25.setName("jLabel25"); // NOI18N
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addGroup(
jPanel18Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addGroup(jPanel18Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel12,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel18Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addGap(0, 297, Short.MAX_VALUE)
.addComponent(jButton11)
.addGap(18, 18, 18)
.addComponent(jButton12))
.addComponent(jSplitPane4)))
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinnerRemoveRecall,
javax.swing.GroupLayout.PREFERRED_SIZE, 43,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel18Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 17,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(spinnerRemoveRecall,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel18Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, 114,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addGroup(jPanel18Layout.createSequentialGroup()
.addComponent(jSplitPane4, javax.swing.GroupLayout.DEFAULT_SIZE,
405,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel18Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton12)
.addComponent(jButton11))
.addGap(17, 17, 17))))
);
tabbedPaneMain
.addTab(resourceMap.getString("jPanel18.TabConstraints.tabTitle"), jPanel18); // NOI18N
jPanel8.setAutoscrolls(true);
jPanel8.setName("jPanel8"); // NOI18N
jPanel9.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel9.border.title"))); // NOI18N
jPanel9.setName("jPanel9"); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
jLabel8.setName("jLabel8"); // NOI18N
jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
jLabel9.setName("jLabel9"); // NOI18N
spinnerPropServerPort.setName("spinnerPropServerPort"); // NOI18N
spinnerWebServerPort.setName("spinnerWebServerPort"); // NOI18N
spinnerPropClientPort.setName("spinnerPropClientPort"); // NOI18N
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(jPanel9Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel3)))
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel9Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(spinnerPropServerPort,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.PREFERRED_SIZE, 64,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(spinnerWebServerPort,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.PREFERRED_SIZE, 64,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(spinnerPropClientPort,
javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.PREFERRED_SIZE, 64,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addGroup(
jPanel9Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(spinnerPropServerPort,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel9Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(spinnerWebServerPort,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel9Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spinnerPropClientPort,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel16.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel16.border.title"))); // NOI18N
jPanel16.setName("jPanel16"); // NOI18N
spinnerFirstNumber.setModel(new javax.swing.SpinnerNumberModel(1, 1, 10000, 1));
spinnerFirstNumber.setName("spinnerFirstNumber"); // NOI18N
spinnerLastNumber.setModel(new javax.swing.SpinnerNumberModel(99, 99, 10000, 1));
spinnerLastNumber.setName("spinnerLastNumber"); // NOI18N
jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
jLabel11.setName("jLabel11"); // NOI18N
jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
jLabel12.setName("jLabel12"); // NOI18N
jPanel22.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel22.border.title"))); // NOI18N
jPanel22.setName("jPanel22"); // NOI18N
buttonGroupKindNum.add(rbKindPersonal);
rbKindPersonal.setText(resourceMap.getString("rbKindPersonal.text")); // NOI18N
rbKindPersonal.setName("rbKindPersonal"); // NOI18N
buttonGroupKindNum.add(rbKindCommon);
rbKindCommon.setText(resourceMap.getString("rbKindCommon.text")); // NOI18N
rbKindCommon.setName("rbKindCommon"); // NOI18N
javax.swing.GroupLayout jPanel22Layout = new javax.swing.GroupLayout(jPanel22);
jPanel22.setLayout(jPanel22Layout);
jPanel22Layout.setHorizontalGroup(
jPanel22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel22Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel22Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(rbKindPersonal)
.addComponent(rbKindCommon))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel22Layout.setVerticalGroup(
jPanel22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel22Layout.createSequentialGroup()
.addComponent(rbKindPersonal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rbKindCommon))
);
chBoxBtnFreeDsn.setText(resourceMap.getString("chBoxBtnFreeDsn.text")); // NOI18N
chBoxBtnFreeDsn.setName("chBoxBtnFreeDsn"); // NOI18N
labExtPrior.setText(resourceMap.getString("labExtPrior.text")); // NOI18N
labExtPrior.setName("labExtPrior"); // NOI18N
spinExtPrior.setModel(new javax.swing.SpinnerNumberModel(0, 0, 99, 1));
spinExtPrior.setName("spinExtPrior"); // NOI18N
javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel16Layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(jPanel16Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel16Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spinnerFirstNumber,
javax.swing.GroupLayout.PREFERRED_SIZE,
73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(spinnerLastNumber, javax.swing.GroupLayout.PREFERRED_SIZE,
73,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel22, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel16Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel16Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel16Layout.createSequentialGroup()
.addComponent(labExtPrior)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spinExtPrior, javax.swing.GroupLayout.PREFERRED_SIZE,
52,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(chBoxBtnFreeDsn))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel16Layout.createSequentialGroup()
.addGroup(
jPanel16Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel22, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel16Layout.createSequentialGroup()
.addGap(9, 9, 9)
.addGroup(jPanel16Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(spinnerFirstNumber,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(jPanel16Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(spinnerLastNumber,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chBoxBtnFreeDsn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel16Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spinExtPrior, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labExtPrior))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane2.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jTabbedPane2.border.title"))); // NOI18N
jTabbedPane2.setName("jTabbedPane2"); // NOI18N
jPanel23.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel23.border.title"))); // NOI18N
jPanel23.setName("jPanel23"); // NOI18N
textFieldURLWebService
.setText(resourceMap.getString("textFieldURLWebService.text")); // NOI18N
textFieldURLWebService.setName("textFieldURLWebService"); // NOI18N
spinnerBranchId.setModel(new javax.swing.SpinnerNumberModel(0L, 0L, null, 1L));
spinnerBranchId.setName("spinnerBranchId"); // NOI18N
jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
jLabel7.setName("jLabel7"); // NOI18N
jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N
jLabel13.setName("jLabel13"); // NOI18N
buttonCloudTest.setText(resourceMap.getString("buttonCloudTest.text")); // NOI18N
buttonCloudTest.setName("buttonCloudTest"); // NOI18N
buttonCloudTest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonCloudTestActionPerformed(evt);
}
});
buttonSendDataToSky.setText(resourceMap.getString("buttonSendDataToSky.text")); // NOI18N
buttonSendDataToSky.setName("buttonSendDataToSky"); // NOI18N
buttonSendDataToSky.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSendDataToSkyActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel23Layout = new javax.swing.GroupLayout(jPanel23);
jPanel23.setLayout(jPanel23Layout);
jPanel23Layout.setHorizontalGroup(
jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel23Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel23Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel23Layout.createSequentialGroup()
.addGroup(jPanel23Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jLabel13))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel23Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel23Layout.createSequentialGroup()
.addComponent(spinnerBranchId,
javax.swing.GroupLayout.PREFERRED_SIZE, 86,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addComponent(textFieldURLWebService)))
.addGroup(jPanel23Layout.createSequentialGroup()
.addGap(0, 103, Short.MAX_VALUE)
.addComponent(buttonCloudTest)
.addGap(18, 18, 18)
.addComponent(buttonSendDataToSky)
.addContainerGap())))
);
jPanel23Layout.setVerticalGroup(
jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel23Layout.createSequentialGroup()
.addGroup(
jPanel23Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(spinnerBranchId, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel23Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldURLWebService,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel23Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonSendDataToSky)
.addComponent(buttonCloudTest))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane2
.addTab(resourceMap.getString("jPanel23.TabConstraints.tabTitle"), jPanel23); // NOI18N
jPanel24.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("jPanel24.border.title"))); // NOI18N
jPanel24.setName("jPanel24"); // NOI18N
jLabel15.setText(resourceMap.getString("jLabel15.text")); // NOI18N
jLabel15.setName("jLabel15"); // NOI18N
jLabel24.setText(resourceMap.getString("jLabel24.text")); // NOI18N
jLabel24.setName("jLabel24"); // NOI18N
textFieldZonBoadrServAddr
.setText(resourceMap.getString("textFieldZonBoadrServAddr.text")); // NOI18N
textFieldZonBoadrServAddr.setName("textFieldZonBoadrServAddr"); // NOI18N
spinnerZonBoadrServPort.setModel(new javax.swing.SpinnerNumberModel(500, 500, 60000, 1));
spinnerZonBoadrServPort.setName("spinnerZonBoadrServPort"); // NOI18N
buttonCheckZoneBoardServ
.setText(resourceMap.getString("buttonCheckZoneBoardServ.text")); // NOI18N
buttonCheckZoneBoardServ.setName("buttonCheckZoneBoardServ"); // NOI18N
buttonCheckZoneBoardServ.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonCheckZoneBoardServActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel24Layout = new javax.swing.GroupLayout(jPanel24);
jPanel24.setLayout(jPanel24Layout);
jPanel24Layout.setHorizontalGroup(
jPanel24Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel24Layout.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel24Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel24Layout.createSequentialGroup()
.addGroup(jPanel24Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15)
.addComponent(jLabel24))
.addGap(18, 18, 18)
.addGroup(jPanel24Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel24Layout.createSequentialGroup()
.addComponent(spinnerZonBoadrServPort,
javax.swing.GroupLayout.PREFERRED_SIZE, 87,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(textFieldZonBoadrServAddr,
javax.swing.GroupLayout.DEFAULT_SIZE, 286,
Short.MAX_VALUE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
jPanel24Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(buttonCheckZoneBoardServ)))
.addContainerGap())
);
jPanel24Layout.setVerticalGroup(
jPanel24Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel24Layout.createSequentialGroup()
.addGroup(
jPanel24Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(textFieldZonBoadrServAddr,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(
jPanel24Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel24)
.addComponent(spinnerZonBoadrServPort,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonCheckZoneBoardServ)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane2
.addTab(resourceMap.getString("jPanel24.TabConstraints.tabTitle"), jPanel24); // NOI18N
propsPanel.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("propsPanel.border.title"))); // NOI18N
propsPanel.setName("propsPanel"); // NOI18N
jSplitPane10.setDividerLocation(300);
jSplitPane10.setContinuousLayout(true);
jSplitPane10.setName("jSplitPane10"); // NOI18N
sectionPanel.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("sectionPanel.border.title"))); // NOI18N
sectionPanel.setName("sectionPanel"); // NOI18N
jScrollPane10.setName("jScrollPane10"); // NOI18N
sectionsList.setFont(resourceMap.getFont("sectionsList.font")); // NOI18N
sectionsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
sectionsList.setComponentPopupMenu(popupSections);
sectionsList.setName("sectionsList"); // NOI18N
jScrollPane10.setViewportView(sectionsList);
btnDeleteSection.setText(resourceMap.getString("miDeleteSection.text")); // NOI18N
btnDeleteSection.setName("btnDeleteSection"); // NOI18N
btnDeleteSection.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miDeleteSectionActionPerformed(evt);
}
});
btnAddSection.setText(resourceMap.getString("miAddSection.text")); // NOI18N
btnAddSection.setName("btnAddSection"); // NOI18N
btnAddSection.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miAddSectionActionPerformed(evt);
}
});
javax.swing.GroupLayout sectionPanelLayout = new javax.swing.GroupLayout(sectionPanel);
sectionPanel.setLayout(sectionPanelLayout);
sectionPanelLayout.setHorizontalGroup(
sectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 287,
Short.MAX_VALUE)
.addGroup(sectionPanelLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnAddSection)
.addGap(18, 18, 18)
.addComponent(btnDeleteSection))
);
sectionPanelLayout.setVerticalGroup(
sectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sectionPanelLayout.createSequentialGroup()
.addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 238,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(sectionPanelLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnDeleteSection)
.addComponent(btnAddSection)))
);
jSplitPane10.setLeftComponent(sectionPanel);
keyvaluePanel.setBorder(javax.swing.BorderFactory
.createTitledBorder(resourceMap.getString("keyvaluePanel.border.title"))); // NOI18N
keyvaluePanel.setName("keyvaluePanel"); // NOI18N
jScrollPane26.setName("jScrollPane26"); // NOI18N
propsTable.setAutoCreateRowSorter(true);
propsTable.setFont(resourceMap.getFont("propsTable.font")); // NOI18N
propsTable
.setModel(new PropsTableModel(new ServerProps.Section("", new LinkedHashMap<>())));
propsTable.setComponentPopupMenu(popupProps);
propsTable.setName("propsTable"); // NOI18N
propsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
propsTable.getTableHeader().setReorderingAllowed(false);
jScrollPane26.setViewportView(propsTable);
btnRemoveProp.setText(resourceMap.getString("muDeleteProp.text")); // NOI18N
btnRemoveProp.setName("btnRemoveProp"); // NOI18N
btnRemoveProp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
muDeletePropActionPerformed(evt);
}
});
btnAddProp.setText(resourceMap.getString("muAddProp.text")); // NOI18N
btnAddProp.setName("btnAddProp"); // NOI18N
btnAddProp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
muAddPropActionPerformed(evt);
}
});
btnReloadProps.setText(resourceMap.getString("btnReloadProps.text")); // NOI18N
btnReloadProps.setName("btnReloadProps"); // NOI18N
btnReloadProps.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnReloadPropsActionPerformed(evt);
}
});
javax.swing.GroupLayout keyvaluePanelLayout = new javax.swing.GroupLayout(keyvaluePanel);
keyvaluePanel.setLayout(keyvaluePanelLayout);
keyvaluePanelLayout.setHorizontalGroup(
keyvaluePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane26, javax.swing.GroupLayout.DEFAULT_SIZE, 668,
Short.MAX_VALUE)
.addGroup(keyvaluePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(btnReloadProps)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAddProp)
.addGap(18, 18, 18)
.addComponent(btnRemoveProp))
);
keyvaluePanelLayout.setVerticalGroup(
keyvaluePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(keyvaluePanelLayout.createSequentialGroup()
.addComponent(jScrollPane26, javax.swing.GroupLayout.DEFAULT_SIZE, 238,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(keyvaluePanelLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRemoveProp)
.addComponent(btnAddProp)
.addComponent(btnReloadProps)))
);
jSplitPane10.setRightComponent(keyvaluePanel);
javax.swing.GroupLayout propsPanelLayout = new javax.swing.GroupLayout(propsPanel);
propsPanel.setLayout(propsPanelLayout);
propsPanelLayout.setHorizontalGroup(
propsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane10)
);
propsPanelLayout.setVerticalGroup(
propsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane10)
);
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel16, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0,
Short.MAX_VALUE))
.addComponent(propsPanel, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 156,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel16, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(propsPanel, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
tabbedPaneMain
.addTab(resourceMap.getString("jPanel8.TabConstraints.tabTitle"), jPanel8); // NOI18N
tabHide.setBackground(resourceMap.getColor("tabHide.background")); // NOI18N
tabHide.setName("tabHide"); // NOI18N
jScrollPane24.setBackground(resourceMap.getColor("jScrollPane24.background")); // NOI18N
jScrollPane24.setName("jScrollPane24"); // NOI18N
labHidePic.setBackground(resourceMap.getColor("labHidePic.background")); // NOI18N
labHidePic.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labHidePic.setIcon(resourceMap.getIcon("labHidePic.icon")); // NOI18N
labHidePic.setText(resourceMap.getString("labHidePic.text")); // NOI18N
labHidePic.setName("labHidePic"); // NOI18N
labHidePic.setOpaque(true);
jScrollPane24.setViewportView(labHidePic);
javax.swing.GroupLayout tabHideLayout = new javax.swing.GroupLayout(tabHide);
tabHide.setLayout(tabHideLayout);
tabHideLayout.setHorizontalGroup(
tabHideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane24, javax.swing.GroupLayout.DEFAULT_SIZE, 998,
Short.MAX_VALUE)
);
tabHideLayout.setVerticalGroup(
tabHideLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane24)
);
tabbedPaneMain
.addTab(resourceMap.getString("tabHide.TabConstraints.tabTitle"), tabHide); // NOI18N
jPanel1.add(tabbedPaneMain);
panelPager.setBackground(resourceMap.getColor("panelPager.background")); // NOI18N
panelPager.setBorder(new javax.swing.border.MatteBorder(null));
panelPager.setName("panelPager"); // NOI18N
panelPager.setPreferredSize(new java.awt.Dimension(1010, 50));
labelPager.setText(resourceMap.getString("labelPager.text")); // NOI18N
labelPager.setName("labelPager"); // NOI18N
labelPager.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelPagerMouseClicked(evt);
}
});
panelPagerRadio.setBackground(resourceMap.getColor("panelPagerRadio.background")); // NOI18N
panelPagerRadio.setName("panelPagerRadio"); // NOI18N
panelPagerRadio.setOpaque(false);
panelPagerRadio.setLayout(new java.awt.GridLayout(3, 0));
bgPager.add(rbPager1);
rbPager1.setText(resourceMap.getString("rbPager1.text")); // NOI18N
rbPager1.setName("rbPager1"); // NOI18N
rbPager1.setOpaque(false);
rbPager1.setPreferredSize(new java.awt.Dimension(93, 14));
rbPager1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rbPager1ActionPerformed(evt);
}
});
panelPagerRadio.add(rbPager1);
bgPager.add(rbPager2);
rbPager2.setText(resourceMap.getString("rbPager2.text")); // NOI18N
rbPager2.setName("rbPager2"); // NOI18N
rbPager2.setOpaque(false);
rbPager2.setPreferredSize(new java.awt.Dimension(93, 14));
rbPager2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rbPager1ActionPerformed(evt);
}
});
panelPagerRadio.add(rbPager2);
bgPager.add(rbPager3);
rbPager3.setText(resourceMap.getString("rbPager3.text")); // NOI18N
rbPager3.setName("rbPager3"); // NOI18N
rbPager3.setOpaque(false);
rbPager3.setPreferredSize(new java.awt.Dimension(93, 14));
rbPager3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rbPager1ActionPerformed(evt);
}
});
panelPagerRadio.add(rbPager3);
panelPagerCombo.setName("panelPagerCombo"); // NOI18N
panelPagerCombo.setOpaque(false);
labelPagerCaptionCombo
.setText(resourceMap.getString("labelPagerCaptionCombo.text")); // NOI18N
labelPagerCaptionCombo.setName("labelPagerCaptionCombo"); // NOI18N
comboBoxPager.setModel(
new javax.swing.DefaultComboBoxModel(
new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));
comboBoxPager.setName("comboBoxPager"); // NOI18N
comboBoxPager.setOpaque(false);
comboBoxPager.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboBoxPagerActionPerformed(evt);
}
});
javax.swing.GroupLayout panelPagerComboLayout = new javax.swing.GroupLayout(
panelPagerCombo);
panelPagerCombo.setLayout(panelPagerComboLayout);
panelPagerComboLayout.setHorizontalGroup(
panelPagerComboLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelPagerComboLayout.createSequentialGroup()
.addGroup(panelPagerComboLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelPagerCaptionCombo)
.addComponent(comboBoxPager, 0, 323, Short.MAX_VALUE))
.addContainerGap())
);
panelPagerComboLayout.setVerticalGroup(
panelPagerComboLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelPagerComboLayout.createSequentialGroup()
.addComponent(labelPagerCaptionCombo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(comboBoxPager, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelEditPager.setName("panelEditPager"); // NOI18N
panelEditPager.setOpaque(false);
labelPagerCaptionEdit
.setText(resourceMap.getString("labelPagerCaptionEdit.text")); // NOI18N
labelPagerCaptionEdit.setName("labelPagerCaptionEdit"); // NOI18N
textFieldPager.setText(resourceMap.getString("textFieldPager.text")); // NOI18N
textFieldPager.setName("textFieldPager"); // NOI18N
buttonPagerEdit.setText(resourceMap.getString("buttonPagerEdit.text")); // NOI18N
buttonPagerEdit.setName("buttonPagerEdit"); // NOI18N
buttonPagerEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPagerEditActionPerformed(evt);
}
});
javax.swing.GroupLayout panelEditPagerLayout = new javax.swing.GroupLayout(panelEditPager);
panelEditPager.setLayout(panelEditPagerLayout);
panelEditPagerLayout.setHorizontalGroup(
panelEditPagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelEditPagerLayout.createSequentialGroup()
.addGroup(panelEditPagerLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
panelEditPagerLayout.createSequentialGroup()
.addComponent(textFieldPager, javax.swing.GroupLayout.DEFAULT_SIZE,
246,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonPagerEdit))
.addComponent(labelPagerCaptionEdit))
.addContainerGap())
);
panelEditPagerLayout.setVerticalGroup(
panelEditPagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelEditPagerLayout.createSequentialGroup()
.addComponent(labelPagerCaptionEdit)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelEditPagerLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldPager, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonPagerEdit))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout panelPagerLayout = new javax.swing.GroupLayout(panelPager);
panelPager.setLayout(panelPagerLayout);
panelPagerLayout.setHorizontalGroup(
panelPagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
panelPagerLayout.createSequentialGroup()
.addContainerGap()
.addComponent(labelPager, javax.swing.GroupLayout.DEFAULT_SIZE, 55,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelEditPager, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelPagerCombo, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelPagerRadio, javax.swing.GroupLayout.PREFERRED_SIZE, 280,
javax.swing.GroupLayout.PREFERRED_SIZE))
);
panelPagerLayout.setVerticalGroup(
panelPagerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
panelPagerLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addGroup(panelPagerLayout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelPagerCombo, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(panelPagerRadio, javax.swing.GroupLayout.PREFERRED_SIZE,
44,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(panelPagerLayout.createSequentialGroup()
.addComponent(labelPager)
.addContainerGap())
.addComponent(panelEditPager, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
);
jMenuBar1.setName("jMenuBar1"); // NOI18N
menuFile.setText(resourceMap.getString("menuFile.text")); // NOI18N
menuFile.setName("menuFile"); // NOI18N
menuLangs.setText(resourceMap.getString("menuLangs.text")); // NOI18N
menuLangs.setName("menuLangs"); // NOI18N
menuFile.add(menuLangs);
jSeparator15.setName("jSeparator15"); // NOI18N
menuFile.add(jSeparator15);
jMenuItem25.setAction(actionMap.get("sendMessage")); // NOI18N
jMenuItem25.setName("jMenuItem25"); // NOI18N
menuFile.add(jMenuItem25);
jMenuItem8.setAction(actionMap.get("saveConfiguration")); // NOI18N
jMenuItem8.setName("jMenuItem8"); // NOI18N
menuFile.add(jMenuItem8);
jMenuItem4.setAction(actionMap.get("hideWindow")); // NOI18N
jMenuItem4.setName("jMenuItem4"); // NOI18N
menuFile.add(jMenuItem4);
jSeparator1.setName("jSeparator1"); // NOI18N
menuFile.add(jSeparator1);
jMenuItem3.setAction(actionMap.get("quit")); // NOI18N
jMenuItem3.setName("jMenuItem3"); // NOI18N
menuFile.add(jMenuItem3);
jMenuBar1.add(menuFile);
jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
jMenu1.setName("jMenu1"); // NOI18N
jMenuItem19.setAction(actionMap.get("editMainBoard")); // NOI18N
jMenuItem19.setName("jMenuItem19"); // NOI18N
jMenu1.add(jMenuItem19);
menuBoards.setText(resourceMap.getString("menuBoards.text")); // NOI18N
menuBoards.setName("menuBoards"); // NOI18N
bgBoards.add(rbmClassic);
rbmClassic.setSelected(true);
rbmClassic.setText(resourceMap.getString("rbmClassic.text")); // NOI18N
rbmClassic.setName("rbmClassic"); // NOI18N
rbmClassic.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rbmClassicActionPerformed(evt);
}
});
menuBoards.add(rbmClassic);
bgBoards.add(rbmHtml);
rbmHtml.setText(resourceMap.getString("rbmHtml.text")); // NOI18N
rbmHtml.setName("rbmHtml"); // NOI18N
rbmHtml.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rbmClassicActionPerformed(evt);
}
});
menuBoards.add(rbmHtml);
jMenu1.add(menuBoards);
jMenuBar1.add(jMenu1);
menuUsers.setText(resourceMap.getString("menuUsers.text")); // NOI18N
menuUsers.setName("menuUsers"); // NOI18N
jMenuItem5.setAction(actionMap.get("addUser")); // NOI18N
jMenuItem5.setName("jMenuItem5"); // NOI18N
menuUsers.add(jMenuItem5);
jSeparator2.setName("jSeparator2"); // NOI18N
menuUsers.add(jSeparator2);
jMenuItem2.setAction(actionMap.get("deleteUser")); // NOI18N
jMenuItem2.setName("jMenuItem2"); // NOI18N
menuUsers.add(jMenuItem2);
jSeparator14.setName("jSeparator14"); // NOI18N
menuUsers.add(jSeparator14);
jMenuItem37.setAction(actionMap.get("changePriority")); // NOI18N
jMenuItem37.setName("jMenuItem37"); // NOI18N
menuUsers.add(jMenuItem37);
jMenuItem43.setAction(actionMap.get("checkClient")); // NOI18N
jMenuItem43.setName("jMenuItem43"); // NOI18N
menuUsers.add(jMenuItem43);
jMenuBar1.add(menuUsers);
menuServices.setText(resourceMap.getString("menuServices.text")); // NOI18N
menuServices.setName("menuServices"); // NOI18N
jMenuItem7.setAction(actionMap.get("addService")); // NOI18N
jMenuItem7.setName("jMenuItem7"); // NOI18N
menuServices.add(jMenuItem7);
jSeparator3.setName("jSeparator3"); // NOI18N
menuServices.add(jSeparator3);
jMenuItem6.setAction(actionMap.get("deleteService")); // NOI18N
jMenuItem6.setName("jMenuItem6"); // NOI18N
menuServices.add(jMenuItem6);
jSeparator4.setName("jSeparator4"); // NOI18N
menuServices.add(jSeparator4);
jMenuItem9.setAction(actionMap.get("getTicket")); // NOI18N
jMenuItem9.setName("jMenuItem9"); // NOI18N
menuServices.add(jMenuItem9);
jMenuItem23.setAction(actionMap.get("standAdvance")); // NOI18N
jMenuItem23.setName("jMenuItem23"); // NOI18N
menuServices.add(jMenuItem23);
jMenuBar1.add(menuServices);
menuAbout.setText(resourceMap.getString("menuAbout.text")); // NOI18N
menuAbout.setName("menuAbout"); // NOI18N
menuItemHelp.setAction(actionMap.get("getHelp")); // NOI18N
menuItemHelp.setName("menuItemHelp"); // NOI18N
menuAbout.add(menuItemHelp);
menuItemAbout.setAction(actionMap.get("getAbout")); // NOI18N
menuItemAbout.setName("menuItemAbout"); // NOI18N
menuAbout.add(menuItemAbout);
jSeparator17.setName("jSeparator17"); // NOI18N
menuAbout.add(jSeparator17);
jMenuItemBagtracker.setText(resourceMap.getString("jMenuItemBagtracker.text")); // NOI18N
jMenuItemBagtracker.setName("jMenuItemBagtracker"); // NOI18N
jMenuItemBagtracker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemBagtrackerActionPerformed(evt);
}
});
menuAbout.add(jMenuItemBagtracker);
jMenuItemForum.setText(resourceMap.getString("jMenuItemForum.text")); // NOI18N
jMenuItemForum.setName("jMenuItemForum"); // NOI18N
jMenuItemForum.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemForumActionPerformed(evt);
}
});
menuAbout.add(jMenuItemForum);
jMenuBar1.add(menuAbout);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 1005, Short.MAX_VALUE)
.addComponent(panelPager, javax.swing.GroupLayout.DEFAULT_SIZE, 1005,
Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 518,
Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(panelPager, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void checkBoxServerAutoStateChanged(
javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_checkBoxServerAutoStateChanged
buttonServerRequest.setEnabled(!checkBoxServerAuto.isSelected());
if (timer.isRunning() && checkBoxServerAuto.isSelected()) {
checkServer();
}
startTimer();
}//GEN-LAST:event_checkBoxServerAutoStateChanged
private void buttonLockActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLockActionPerformed
checkWelcome(Uses.WELCOME_LOCK);
}//GEN-LAST:event_buttonLockActionPerformed
private void buttonUnlockActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonUnlockActionPerformed
//GEN-LAST:event_buttonUnlockActionPerformed
checkWelcome(Uses.WELCOME_UNLOCK);
}
//**********************************************************************************************************************
//**********************************************************************************************************************
//*****************************************Сохранение*******************************************************************
private void checkBoxServerAutoFocusLost(
java.awt.event.FocusEvent evt) {//GEN-FIRST:event_checkBoxServerAutoFocusLost
saveSettings();
}//GEN-LAST:event_checkBoxServerAutoFocusLost
private void textFieldClientAdressFocusLost(
java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textFieldClientAdressFocusLost
saveSettings();
}//GEN-LAST:event_textFieldClientAdressFocusLost
private void checkBoxClientAutoFocusLost(
java.awt.event.FocusEvent evt) {//GEN-FIRST:event_checkBoxClientAutoFocusLost
saveSettings();
}//GEN-LAST:event_checkBoxClientAutoFocusLost
//*****************************************Сохранение*******************************************************************
//**********************************************************************************************************************
//*************************************** Запрос в ручную **************************************************************
private void buttonServerRequestActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonServerRequestActionPerformed
checkServer();
}//GEN-LAST:event_buttonServerRequestActionPerformed
private void buttonClientRequestActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonClientRequestActionPerformed
checkWelcome(null);
}//GEN-LAST:event_buttonClientRequestActionPerformed
private void checkBoxClientAutoStateChanged(
javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_checkBoxClientAutoStateChanged
buttonClientRequest.setEnabled(!checkBoxClientAuto.isSelected());
if (timer.isRunning() && checkBoxClientAuto.isSelected()) {
checkWelcome(null);
}
startTimer();
}//GEN-LAST:event_checkBoxClientAutoStateChanged
private void buttonShutDownActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonShutDownActionPerformed
// Уточним намерения
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.close_welcame.title"),
getLocaleMessage("admin.close_welcame.caption"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
checkWelcome(Uses.WELCOME_OFF);
}//GEN-LAST:event_buttonShutDownActionPerformed
private void buttonRestartActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRestartActionPerformed
checkWelcome(Uses.WELCOME_REINIT);
final ATalkingClock clock = new ATalkingClock(1000, 1) {
@Override
public void run() {
checkWelcome(null);
JOptionPane.showConfirmDialog(null, getLocaleMessage("admin.server_reinit.title"),
getLocaleMessage("admin.server_reinit.caption"), JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
}
};
clock.start();
}//GEN-LAST:event_buttonRestartActionPerformed
private void textFieldServerAddrFocusLost(
java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textFieldServerAddrFocusLost
saveSettings();
}//GEN-LAST:event_textFieldServerAddrFocusLost
private void passwordFieldUserKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordFieldUserKeyReleased
saveUser();
}//GEN-LAST:event_passwordFieldUserKeyReleased
private void tabbedPaneMainStateChanged(
javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tabbedPaneMainStateChanged
// это событие переключения закладок на табе.
menuServices.setEnabled(tabbedPaneMain.getSelectedIndex() == 1);
menuUsers.setEnabled(tabbedPaneMain.getSelectedIndex() == 1);
// в пейджере листнем новость
if (form != null && forPager != null
&& new Date().getTime() - ancorPager > 0/*1000 * 60 * 5*/) {
ancorPager = new Date().getTime();
forPager.showData(true);
}
if (forHidehide) {
tabbedPaneMain.remove(tabHide);
forHidehide = false;
}
forHidehide = tabbedPaneMain.getSelectedComponent() == tabHide;
}//GEN-LAST:event_tabbedPaneMainStateChanged
private void textFieldUserIdentKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldUserIdentKeyReleased
saveUser();
}//GEN-LAST:event_textFieldUserIdentKeyReleased
private void listUserServiceMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listUserServiceMouseClicked
// назначение приоритета услуге.
if (evt.getClickCount() == 2) {
changeServicePriority();
}
}//GEN-LAST:event_listUserServiceMouseClicked
private void checkBoxReportMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkBoxReportMouseClicked
saveUser();
}//GEN-LAST:event_checkBoxReportMouseClicked
private void checkBoxAdminMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkBoxAdminMouseClicked
//проверим не последний ли это админ
final QUser user = (QUser) listUsers.getSelectedValue();
if (user.getAdminAccess()) {
int cnt = 0;
for (int i = 0; i < listUsers.getModel().getSize(); i++) {
if (((QUser) listUsers.getModel().getElementAt(i)).getAdminAccess()) {
cnt++;
}
}
if (cnt == 1) {
JOptionPane.showConfirmDialog(this, getLocaleMessage("admin.edit_user_err.title"),
getLocaleMessage("admin.edit_user_err.caption"), JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
checkBoxAdmin.setSelected(true);
return;
}
}
saveUser();
}//GEN-LAST:event_checkBoxAdminMouseClicked
private void treeServicesMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeServicesMouseClicked
// Редактирование услуги.
if (evt.getClickCount() == 2) {
final TreePath selectedPath = treeServices.getSelectionPath();
if (selectedPath != null) {
editService();
}
}
}//GEN-LAST:event_treeServicesMouseClicked
private void buttonRestartServerActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRestartServerActionPerformed
if (JOptionPane
.showConfirmDialog(null, "Ты точно хочешь проделать эту богомерскую операцию?",
"Подумай три раза, о мышкатыкатель!", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == 1) {
return;
}
NetCommander.restartServer(new ServerNetProperty());
final ATalkingClock clock = new ATalkingClock(4000, 1) {
@Override
public void run() {
JOptionPane.showConfirmDialog(null, getLocaleMessage("admin.server_restart.title"),
getLocaleMessage("admin.server_restart.caption"), JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
checkServer();
}
};
clock.start();
}//GEN-LAST:event_buttonRestartServerActionPerformed
private void textFieldInfoItemNameKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldInfoItemNameKeyReleased
final QInfoItem item = (QInfoItem) treeInfo.getLastSelectedPathComponent();
if (item != null/* && !item.isRoot()*/) {
item.setName(textFieldInfoItemName.getText());
}
}//GEN-LAST:event_textFieldInfoItemNameKeyReleased
private void textPaneInfoItemKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textPaneInfoItemKeyReleased
final QInfoItem item = (QInfoItem) treeInfo.getLastSelectedPathComponent();
if (item != null/* && !item.isRoot()*/) {
item.setHTMLText(textPaneInfoItem.getText());
labelInfoItem.setText(textPaneInfoItem.getText());
}
}//GEN-LAST:event_textPaneInfoItemKeyReleased
private void treeInfoMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeInfoMouseClicked
final QInfoItem item = (QInfoItem) treeInfo.getLastSelectedPathComponent();
if (item != null) {
//textFieldInfoItemName.setEnabled(!item.isRoot());
//textPaneInfoItem.setEnabled(!item.isRoot());
//textPaneInfoPrint.setEnabled(!item.isRoot());
}
}//GEN-LAST:event_treeInfoMouseClicked
private void textFieldResponseKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldResponseKeyReleased
final QRespItem item = (QRespItem) treeResp.getLastSelectedPathComponent();
if (item != null) {
item.setName(textFieldResponse.getText());
}
}//GEN-LAST:event_textFieldResponseKeyReleased
private void textPaneResponseKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textPaneResponseKeyReleased
final QRespItem item = (QRespItem) treeResp.getLastSelectedPathComponent();
if (item != null) {
item.setHTMLText(textPaneResponse.getText());
labelRespinse.setText(textPaneResponse.getText());
}
}//GEN-LAST:event_textPaneResponseKeyReleased
private void textFieldScheduleNameKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldScheduleNameKeyReleased
final QSchedule item = (QSchedule) listSchedule.getSelectedValue();
if (item != null) {
item.setName(textFieldScheduleName.getText());
}
}//GEN-LAST:event_textFieldScheduleNameKeyReleased
private void listScheduleMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listScheduleMouseClicked
// Редактирование услуги.
if (evt.getClickCount() == 2) {
final QSchedule item = (QSchedule) listSchedule.getSelectedValue();
if (item != null) {
editSchedule();
}
}
}//GEN-LAST:event_listScheduleMouseClicked
private void textFieldCalendarNameKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldCalendarNameKeyReleased
final QCalendar item = (QCalendar) listCalendar.getSelectedValue();
if (item != null) {
item.setName(textFieldCalendarName.getText());
}
}//GEN-LAST:event_textFieldCalendarNameKeyReleased
private void tabbedPaneMainFocusLost(
java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tabbedPaneMainFocusLost
final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel();
if (!model.isSaved()) {
if (0 == JOptionPane
.showConfirmDialog(null, getLocaleMessage("admin.calendar_change.message"),
getLocaleMessage("admin.calendar_change.title"), JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE)) {
model.save();
}
}
}//GEN-LAST:event_tabbedPaneMainFocusLost
private void tableCalendarFocusGained(
java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tableCalendarFocusGained
if (inGrid > 0) {
inGrid = 0;
return;
}
// проверка на то что перед редактированием сетки нужно сохранать сам список календарей
// инече не будет известно с каким ID привязки к календарю сохранять выходные дни
inGrid++;
for (int i = 0; i < listCalendar.getModel().getSize(); i++) {
boolean flag = false;
for (QCalendar calendar : QCalendarList.getInstance().getItems()) {
if (((QCalendar) listCalendar.getModel().getElementAt(i)).getId()
.equals(calendar.getId())) {
flag = true;
}
}
if (!flag) {
JOptionPane.showConfirmDialog(this, getLocaleMessage("admin.calendar_warn.message"),
getLocaleMessage("admin.calendar_warn.title"), JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
return;
}
}
}//GEN-LAST:event_tableCalendarFocusGained
private void textPaneInfoPrintKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textPaneInfoPrintKeyReleased
final QInfoItem item = (QInfoItem) treeInfo.getLastSelectedPathComponent();
if (item != null /*&& !item.isRoot()*/) {
item.setTextPrint(textPaneInfoPrint.getText());
}
}//GEN-LAST:event_textPaneInfoPrintKeyReleased
private void buttonResetMainTabloActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonResetMainTabloActionPerformed
NetCommander.restartMainTablo(new ServerNetProperty());
JOptionPane.showConfirmDialog(null, getLocaleMessage("admin.main_tablo_restart.message"),
getLocaleMessage("admin.main_tablo_restart.title"), JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_buttonResetMainTabloActionPerformed
private void buttonCloudTestActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCloudTestActionPerformed
// поддержка расширяемости плагинами
final StringBuilder sb = new StringBuilder(
getLocaleMessage("admin.cloud_test_dialog.results") + ":\n");
try {
for (final IPing event : ServiceLoader.load(IPing.class)) {
if (event.getUID() == 01L) {
QLog.l().logger()
.info("Вызов SPI расширения. Описание: " + event.getDescription());
sb.append(event.getDescription()).append(" ")
.append(getLocaleMessage("admin.cloud_test_dialog.result")).append(": ")
.append(event.ping()).append("\n");
}
}
} catch (Throwable ex) {
QLog.l().logger().error("SPI error: ", ex);
sb.append(getLocaleMessage("admin.cloud_test_dialog.error"));
}
final String res =
"URL=\"" + ServerProps.getInstance().getProps().getSkyServerUrl() + "\"\n\n" + sb
.toString();
sb.setLength(0);
JOptionPane.showConfirmDialog(null, res, getLocaleMessage("admin.cloud_test_dialog.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_buttonCloudTestActionPerformed
private void buttonSendDataToSkyActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSendDataToSkyActionPerformed
// поддержка расширяемости плагинами
final Thread th = new Thread(() -> {
int all = 0;
all = QServiceTree.getInstance().getNodes().stream()
.filter((service) -> (service.isLeaf()))
.map((_item) -> 1).reduce(all, Integer::sum);
all += QUserList.getInstance().getSize();
int tmp = 0;
try {
for (final IDataExchange event : ServiceLoader.load(IDataExchange.class)) {
QLog.l().logger()
.info("Вызов SPI расширения. Описание: " + event.getDescription());
for (QService service : QServiceTree.getInstance().getNodes()) {
if (service.isLeaf()) {
event.sendServiceName(
ServerProps.getInstance().getProps().getBranchOfficeId(),
service.getId(), service.getName());
tmp++;
final String s = "" + tmp + "/" + all + " " + tmp * 100 / all + "%";
SwingUtilities.invokeLater(() -> {
buttonSendDataToSky.setText(s);
});
}
}
for (QUser user : QUserList.getInstance().getItems()) {
event.sendUserName(ServerProps.getInstance().getProps().getBranchOfficeId(),
user.getId(), user.getName());
tmp++;
final String s = "" + tmp + "/" + all + " " + tmp * 100 / all + "%";
SwingUtilities.invokeLater(() -> {
buttonSendDataToSky.setText(s);
});
}
}
} catch (Throwable ex) {
QLog.l().logger().error("Не отослали названия в облако.", ex);
JOptionPane.showConfirmDialog(null,
getLocaleMessage("admin.cloud_senddata_dialog.message_err") + "\n" + ex
.getMessage(),
getLocaleMessage("admin.cloud_senddata_dialog.title"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showConfirmDialog(null,
getLocaleMessage("admin.cloud_senddata_dialog.message") + " " + tmp + "/" + all,
getLocaleMessage("admin.cloud_senddata_dialog.title"), JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE);
SwingUtilities.invokeLater(() -> {
buttonSendDataToSky.setText(getLocaleMessage("buttonSendDataToSky.text"));
});
});
th.start();
}//GEN-LAST:event_buttonSendDataToSkyActionPerformed
private void buttonCheckZoneBoardServActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCheckZoneBoardServActionPerformed
// поддержка расширяемости плагинами
final StringBuilder sb = new StringBuilder(
getLocaleMessage("admin.zoneboard_test_dialog.results") + ":\n");
try {
for (final IPing event : ServiceLoader.load(IPing.class)) {
QLog.l().logger().info("Вызов SPI расширения. Описание: " + event.getDescription());
System.out.println(">>SPI: " + event.getDescription());
sb.append(event.getDescription()).append(" ")
.append(getLocaleMessage("admin.zoneboard_test_dialog.result")).append(": ")
.append(event.ping()).append("\n");
}
} catch (Throwable ex) {
QLog.l().logger().error("Ошибка при пинговании зонального сервера. ", ex);
sb.append(getLocaleMessage("admin.zoneboard_test_dialog.error"));
}
final String res = sb.toString();
sb.setLength(0);
JOptionPane
.showConfirmDialog(null, res, getLocaleMessage("admin.zoneboard_test_dialog.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_buttonCheckZoneBoardServActionPerformed
private void buttonRefreshBanActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRefreshBanActionPerformed
listBan.setModel(
new DefaultComboBoxModel(NetCommander.getBanedList(new ServerNetProperty()).toArray()));
}//GEN-LAST:event_buttonRefreshBanActionPerformed
private void listBreaksMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listBreaksMouseClicked
// Редактирование перерывов
if (evt.getClickCount() == 2) {
final QBreaks item = (QBreaks) listBreaks.getSelectedValue();
if (item != null) {
editBreak();
}
}
}//GEN-LAST:event_listBreaksMouseClicked
private void textFieldSearchServiceKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldSearchServiceKeyReleased
TreeNode node = null;
boolean flag = evt.getKeyCode() != 114;
final QService ser = (QService) treeServices.getLastSelectedPathComponent();
for (Object object : ((ATreeModel) treeServices.getModel()).getNodes()) {
final QService service = (QService) object;
if (flag) {
if (service.toString().toLowerCase()
.contains(textFieldSearchService.getText().trim().toLowerCase())) {
node = (TreeNode) object;
break;
}
} else if (!flag && (ser == null || service.getId().equals(ser.getId()))) {
flag = true;
}
}
if (node != null) {
TreeNode[] nodes = ((DefaultTreeModel) treeServices.getModel()).getPathToRoot(node);
TreePath path = new TreePath(nodes);
treeServices.setSelectionPath(path);
treeServices.setExpandsSelectedPaths(true);
treeServices.scrollPathToVisible(path);
} else {
Toolkit.getDefaultToolkit().beep();
}
}//GEN-LAST:event_textFieldSearchServiceKeyReleased
private void treeServicesKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_treeServicesKeyReleased
if (evt.getKeyCode() == 114) {
textFieldSearchServiceKeyReleased(evt);
}
}//GEN-LAST:event_treeServicesKeyReleased
private void buttonExportToCSVActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExportToCSVActionPerformed
final JFileChooser fc = new JFileChooser();
fc.setDialogTitle(getLocaleMessage("save.statictic"));
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return !f.isFile() || f.getAbsolutePath().toLowerCase().endsWith(".csv");
}
@Override
public String getDescription() {
return getLocaleMessage("files.type.csv");
}
});
//fc.setCurrentDirectory(new File("config"));
//fc.setSelectedFile(new File(configuration.getSystemName()));
fc.setDialogType(JFileChooser.SAVE_DIALOG);
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
final File file;
//This is where a real application would open the file.
if (!fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".csv")) {
file = new File(fc.getSelectedFile().getAbsoluteFile() + ".csv");
} else {
file = fc.getSelectedFile();
}
Spring.getInstance().getHt().getSessionFactory().openSession()
.doWork((Connection connection) -> {
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dateChooserStartCsv.getDate());
gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
gc.set(GregorianCalendar.MINUTE, 0);
gc.set(GregorianCalendar.SECOND, 0);
gc.set(GregorianCalendar.MILLISECOND, 0);
final String std = Uses.FORMAT_FOR_REP.format(gc.getTime());
gc.setTime(dateChooserFinishCsv.getDate());
gc.set(GregorianCalendar.HOUR_OF_DAY, 0);
gc.set(GregorianCalendar.MINUTE, 0);
gc.set(GregorianCalendar.SECOND, 0);
gc.set(GregorianCalendar.MILLISECOND, 0);
gc.add(GregorianCalendar.HOUR, 24);
final String find = Uses.FORMAT_FOR_REP.format(gc.getTime());
final String sql = " SELECT "
+ " s.client_id as id, "
+ " concat(c.service_prefix , c.number) as num, "
+ " c.input_data as inp, "
+ (
"org.h2.Driver".equalsIgnoreCase(Spring.getInstance().getDriverClassName())
? " FORMATDATETIME(s.client_stand_time, 'd.MM.yyyy HH:mm') as stnd, "
+ " sv.name as srv, "
+ " FORMATDATETIME(s.user_start_time, 'd.MM.yyyy HH:mm') as strt, "
+ " FORMATDATETIME(s.user_finish_time, 'd.MM.yyyy HH:mm') as fin, "
: " DATE_FORMAT(s.client_stand_time, '%d.%m.%y %H:%i') as stnd, "
+ " sv.name as srv, "
+ " DATE_FORMAT(s.user_start_time, '%d.%m.%y %H:%i') as strt, "
+ " DATE_FORMAT(s.user_finish_time, '%d.%m.%y %H:%i') as fin, ")
+ " u.name as usr, "
+ " s.client_wait_period as wt, "
+ " s.user_work_period as wrk, "
+ " IFNULL(r.name, '') as res "
+ " FROM statistic s left join results r on s.results_id=r.id, clients c, users u, services sv "
+ " WHERE s.client_id=c.id and s.user_id=u.id and s.service_id=sv.id "
+ " and s.client_stand_time>='" + std + "' and s.client_stand_time<='"
+ find
+ "'";
try (ResultSet set = connection.createStatement().executeQuery(sql)) {
Writer writer;
try {
writer = new OutputStreamWriter(new FileOutputStream(file), "cp1251")
.append("");
writer.append("№");
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.number"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.data"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.stand_time"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.service_name"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.start_time"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.finish_time"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.user"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.wait"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.work"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(getLocaleMessage("csv.result"));
writer.append('\n');
while (set.next()) {
writer.append(set.getString("id"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("num"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("inp"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("stnd"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("srv")
.replace(cbSeparateCSV.getSelectedItem().toString(), " "));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("strt"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("fin"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("usr"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("wt"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("wrk"));
writer.append(cbSeparateCSV.getSelectedItem().toString());
writer.append(set.getString("res"));
writer.append('\n');
}
//generate whatever data you want
writer.flush();
writer.close();
} catch (IOException ex) {
throw new ClientException(ex);
}
}
JOptionPane.showMessageDialog(fc,
getLocaleMessage("stat.saved"),
getLocaleMessage("stat.saving"),
JOptionPane.INFORMATION_MESSAGE);
});
}
}//GEN-LAST:event_buttonExportToCSVActionPerformed
private void textFieldExtPointKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldExtPointKeyReleased
saveUser();
}//GEN-LAST:event_textFieldExtPointKeyReleased
private void buttonPagerEditActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPagerEditActionPerformed
sendPager();
}//GEN-LAST:event_buttonPagerEditActionPerformed
private void comboBoxPagerActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxPagerActionPerformed
sendPager();
}//GEN-LAST:event_comboBoxPagerActionPerformed
private void rbPager1ActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbPager1ActionPerformed
sendPager();
}//GEN-LAST:event_rbPager1ActionPerformed
private void spinCalendarYearStateChanged(
javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinCalendarYearStateChanged
System.out.println(spinCalendarYear.getValue());
tableCalendar.setModel((CalendarTableModel) tableCalendar.getModel());
tableCalendar
.setDefaultRenderer(FreeDay.class,
new TableCell((Integer) (spinCalendarYear.getValue())));
tableCalendar
.setDefaultRenderer(Object.class,
new TableCell((Integer) (spinCalendarYear.getValue())));
((CalendarTableModel) tableCalendar.getModel()).fireTableDataChanged();
((CalendarTableModel) tableCalendar.getModel()).fireTableStructureChanged();
tableCalendar.getColumnModel().getColumn(0).setPreferredWidth(500);
}//GEN-LAST:event_spinCalendarYearStateChanged
private void jMenuItemBagtrackerActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemBagtrackerActionPerformed
try {
Desktop.getDesktop().browse(new URI("https://bitbucket.org/Apertum/qsystem/issues"));
} catch (URISyntaxException | IOException ex) {
QLog.l().logger().error(ex);
}
}//GEN-LAST:event_jMenuItemBagtrackerActionPerformed
private void jMenuItemForumActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemForumActionPerformed
try {
Desktop.getDesktop().browse(new URI("http://qsystem.info/index.php/forum/index"));
} catch (URISyntaxException | IOException ex) {
QLog.l().logger().error(ex);
}
}//GEN-LAST:event_jMenuItemForumActionPerformed
private void labelPagerMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelPagerMouseClicked
if (pagerUrl != null) {
try {
Desktop.getDesktop().browse(new URI(pagerUrl));
} catch (URISyntaxException | IOException ex) {
QLog.l().logger().error(ex);
}
}
}//GEN-LAST:event_labelPagerMouseClicked
private void butWysInfo1ActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butWysInfo1ActionPerformed
textPaneInfoItem.setText(WysiwygDlg.showInstance(textPaneInfoItem.getText()));
labelInfoItem.setText(textPaneInfoItem.getText());
}//GEN-LAST:event_butWysInfo1ActionPerformed
private void btnWysResp1ActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnWysResp1ActionPerformed
textPaneResponse.setText(WysiwygDlg.showInstance(textPaneResponse.getText()));
labelRespinse.setText(textPaneResponse.getText());
}//GEN-LAST:event_btnWysResp1ActionPerformed
private void butAddSpecScedActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butAddSpecScedActionPerformed
QSpecSchedule sps = FSpecScheduleDialog.changeQSpecSchedule(form, true, null);
if (sps != null) {
final QCalendar item = (QCalendar) listCalendar.getSelectedValue();
if (item == null) {
return;
}
sps.setCalendar(item);
item.getSpecSchedules().add(sps);
listSpecSced.setModel(new DefaultComboBoxModel(item.getSpecSchedules().toArray()));
}
}//GEN-LAST:event_butAddSpecScedActionPerformed
private void butEditSpecScedActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butEditSpecScedActionPerformed
if (listSpecSced.getSelectedIndex() != -1) {
QSpecSchedule sps = FSpecScheduleDialog
.changeQSpecSchedule(form, true, (QSpecSchedule) listSpecSced.getSelectedValue());
if (sps != null) {
final QCalendar item = (QCalendar) listCalendar.getSelectedValue();
if (item == null) {
return;
}
listSpecSced.setModel(new DefaultComboBoxModel(item.getSpecSchedules().toArray()));
}
}
}//GEN-LAST:event_butEditSpecScedActionPerformed
private void butDeleteSpecScedActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butDeleteSpecScedActionPerformed
if (listSpecSced.getSelectedIndex() != -1) {
if (0 != JOptionPane
.showConfirmDialog(this, "Do you really want remove the special schedule?",
"Removing",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)) {
return;
}
QSpecSchedule sps = (QSpecSchedule) listSpecSced.getSelectedValue();
if (sps != null) {
final QCalendar item = (QCalendar) listCalendar.getSelectedValue();
if (item == null) {
return;
}
item.getSpecSchedules().remove(sps);
listSpecSced.setModel(new DefaultComboBoxModel(item.getSpecSchedules().toArray()));
}
}
}//GEN-LAST:event_butDeleteSpecScedActionPerformed
private void listSpecScedMouseClicked(
java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listSpecScedMouseClicked
if (evt.getClickCount() > 1) {
butEditSpecScedActionPerformed(null);
}
}//GEN-LAST:event_listSpecScedMouseClicked
private void tfHeaderCmtRespKeyReleased(
java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfHeaderCmtRespKeyReleased
final QRespItem item = (QRespItem) treeResp.getLastSelectedPathComponent();
if (item != null) {
item.setInput_caption(tfHeaderCmtResp.getText());
}
}//GEN-LAST:event_tfHeaderCmtRespKeyReleased
private void cbCommentForRespActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbCommentForRespActionPerformed
final QRespItem item = (QRespItem) treeResp.getLastSelectedPathComponent();
if (item != null) {
item.setInput_required(cbCommentForResp.isSelected());
}
}//GEN-LAST:event_cbCommentForRespActionPerformed
private void jMenuItemEditUserActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemEditUserActionPerformed
final QUser user = (QUser) listUsers.getSelectedValue();
if (user != null) {
FUserChangeDialog.changeUser(form, true, user);
}
}//GEN-LAST:event_jMenuItemEditUserActionPerformed
private void muAddPropActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_muAddPropActionPerformed
if (sectionsList.getLastVisibleIndex() == -1) {
return;
}
final ServerProps.Section section = sectionsList.getSelectedValue();
if (section == null) {
return;
}
final String key = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_prop_name.message"),
getLocaleMessage("admin.prop.title"), 3, null, null, "");
if (key == null) {
return;
}
if (key.isEmpty()) {
JOptionPane.showMessageDialog(this, getLocaleMessage("admin.prop_key_empty.error"),
getLocaleMessage("admin.prop.title"), JOptionPane.ERROR_MESSAGE);
return;
}
if (section.getProperty(key) != null) {
JOptionPane.showMessageDialog(this, getLocaleMessage("admin.prop_key_dublicate.error"),
getLocaleMessage("admin.prop.title"), JOptionPane.ERROR_MESSAGE);
return;
}
QProperty prop = section.addProperty(key, null, null);
((PropsTableModel) propsTable.getModel()).fireTableDataChanged();
propsTable.setRowSelectionInterval(section.getProperties().size() - 1,
section.getProperties().size() - 1);
}//GEN-LAST:event_muAddPropActionPerformed
private void muDeletePropActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_muDeletePropActionPerformed
if (sectionsList.getLastVisibleIndex() == -1) {
return;
}
final ServerProps.Section section = sectionsList.getSelectedValue();
if (section == null) {
return;
}
if (!propsTable.getSelectionModel().isSelectionEmpty()) {
final String key = (String) propsTable.getModel()
.getValueAt(propsTable.getSelectedRow(), 0);
final QProperty prop = ((PropsTableModel) propsTable.getModel()).getPropertyByKey(key);
if (prop == null || JOptionPane.showConfirmDialog(this,
java.text.MessageFormat
.format(getLocaleMessage("admin.del_prop_asc.msg"),
new Object[]{prop.toString()}),
getLocaleMessage("admin.prop.title"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
int i = propsTable.getSelectedRow();
// удалим навсегда
((PropsTableModel) propsTable.getModel()).removeByKey(prop);
((PropsTableModel) propsTable.getModel()).fireTableDataChanged();
// в фокус запись рядом
if (propsTable.getRowCount() != 0) {
if (propsTable.getRowCount() - 1 < i) {
i--;
}
propsTable.getSelectionModel().setSelectionInterval(i, i);
}
}
}//GEN-LAST:event_muDeletePropActionPerformed
private void miAddSectionActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miAddSectionActionPerformed
final String secName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_section_name.message"),
getLocaleMessage("admin.section.title"), 3, null, null, "");
if (secName == null) {
return;
}
if (secName.isEmpty()) {
JOptionPane.showMessageDialog(this, getLocaleMessage("admin.section_empty.error"),
getLocaleMessage("admin.section.title"), JOptionPane.ERROR_MESSAGE);
return;
}
if (ServerProps.getInstance().getSection(secName) != null) {
JOptionPane.showMessageDialog(this, getLocaleMessage("admin.section_dublicate.error"),
getLocaleMessage("admin.section.title"), JOptionPane.ERROR_MESSAGE);
return;
}
final ServerProps.Section section = ServerProps.getInstance().addSection(secName);
sectionsList
.setModel(new DefaultComboBoxModel(ServerProps.getInstance().getSections().toArray()));
sectionsList.setSelectedValue(section, true);
}//GEN-LAST:event_miAddSectionActionPerformed
private void miDeleteSectionActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miDeleteSectionActionPerformed
if (sectionsList.getSelectedIndex() != -1) {
if (JOptionPane.showConfirmDialog(this,
java.text.MessageFormat.format(getLocaleMessage("admin.del_section_asc.msg"),
new Object[]{sectionsList.getSelectedValue().toString()}),
getLocaleMessage("admin.section.title"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
final int del = sectionsList.getSelectedIndex();
final int col = sectionsList.getModel().getSize();
final ServerProps.Section section = sectionsList.getSelectedValue();
ServerProps.getInstance().deleteSection(section.getName());
sectionsList
.setModel(
new DefaultComboBoxModel(ServerProps.getInstance().getSections().toArray()));
if (col != 1) {
if (col == del + 1) {
sectionsList.setSelectedIndex(del - 1);
} else if (col > del + 1) {
sectionsList.setSelectedIndex(del);
}
}
}
}//GEN-LAST:event_miDeleteSectionActionPerformed
private void miCopyServiceActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miCopyServiceActionPerformed
final QService service = (QService) treeServices.getLastSelectedPathComponent();
if (service != null && !service.isRoot()) {
serviceForCopy = service;
serviceForCut = null;
}
}//GEN-LAST:event_miCopyServiceActionPerformed
private void miPasteServiceActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miPasteServiceActionPerformed
final QService service = (QService) treeServices.getLastSelectedPathComponent();
if (service == null) {
return;
}
if (serviceForCut != null) {
if (service.getName().equalsIgnoreCase(serviceForCut.getName()) || service.getName()
.equalsIgnoreCase(serviceForCut.getParent().getName())) {
return;
}
((QServiceTree) treeServices.getModel()).moveNode(serviceForCut, service, 0);
//подсветим перенесенный сервис
final TreeNode[] nodes = QServiceTree.getInstance().getPathToRoot(serviceForCut);
final TreePath path = new TreePath(nodes);
treeServices.scrollPathToVisible(path);
treeServices.setSelectionPath(path);
// родительскую услугу к новой услуге нужно исключить из списка привязанных к юзерам, т.к. она стала группой
deleteServiceFromUsers(service);
QLog.l().logger().debug(
"Перенесена услуга \"" + serviceForCut.getName() + "\" в группу \"" + service
.getName()
+ "\"");
serviceForCut = null;
}
if (serviceForCopy != null) {
if (service.getName().equalsIgnoreCase(serviceForCopy.getName()) || service.getName()
.equalsIgnoreCase(serviceForCopy.getParent().getName())) {
return;
}
// Созданим новую услугу и добавим ее в модель
final QService newService = new QService();
newService
.setName(serviceForCopy.getName() + "-copy" + (System.currentTimeMillis() % 1000));
newService.setDescription(serviceForCopy.getDescription());
newService.setDayLimit(serviceForCopy.getDayLimit());
newService.setDuration(serviceForCopy.getDuration());
newService.setStatus(serviceForCopy.getStatus());
newService.setSoundTemplate(serviceForCopy.getSoundTemplate());
newService.setAdvanceTimePeriod(serviceForCopy.getAdvanceTimePeriod());
newService.setAdvanceLimitPeriod(serviceForCopy.getAdvanceLimitPeriod());
newService.setAdvanceLinit(serviceForCopy.getAdvanceLimit());
newService.setCalendar(serviceForCopy.getCalendar());
newService.setCountPerDay(serviceForCopy.getCountPerDay());
newService.setSchedule(serviceForCopy.getSchedule());
newService.setButtonText(serviceForCopy.getButtonText());
//проставим букавку
newService.setPrefix(serviceForCopy.getPrefix());
newService.setPreInfoHtml(serviceForCopy.getPreInfoHtml());
newService.setPreInfoPrintText(serviceForCopy.getPreInfoPrintText());
newService.setButB(serviceForCopy.getButB());
newService.setButH(serviceForCopy.getButH());
newService.setButX(serviceForCopy.getButX());
newService.setButY(serviceForCopy.getButY());
newService.setEnable(serviceForCopy.getEnable());
newService.setExpectation(serviceForCopy.getExpectation());
newService.setInput_caption(serviceForCopy.getInput_caption());
newService.setInput_required(serviceForCopy.getInput_required());
newService.setTicketText(serviceForCopy.getTicketText());
newService.setTempReasonUnavailable(serviceForCopy.getTempReasonUnavailable());
newService.setResult_required(serviceForCopy.getResult_required());
newService.setPoint(serviceForCopy.getPoint());
newService.setLink(serviceForCopy.getLink());
final Set<QServiceLang> langs = new HashSet<>();
serviceForCopy.getLangs().stream().forEach((lang) -> {
QServiceLang clon = new QServiceLang();
clon.setButtonText(lang.getButtonText());
clon.setDescription(lang.getDescription());
clon.setInput_caption(lang.getInput_caption());
clon.setLang(lang.getLang());
clon.setName(lang.getName());
clon.setPreInfoHtml(lang.getPreInfoHtml());
clon.setPreInfoPrintText(lang.getPreInfoPrintText());
clon.setTicketText(lang.getTicketText());
clon.setService(newService);
langs.add(clon);
});
newService.setLangs(langs);
QServiceTree.getInstance().insertNodeInto(newService, service, 0);
// скопированную услугу обрабатывают те же узеры
QUserList.getInstance().getItems().forEach(user -> {
if (user.hasService(serviceForCopy.getId())) {
user.addPlanService(newService);
}
});
//подсветим перенесенный сервис
final TreeNode[] nodes = QServiceTree.getInstance().getPathToRoot(newService);
final TreePath path = new TreePath(nodes);
treeServices.scrollPathToVisible(path);
treeServices.setSelectionPath(path);
// родительскую услугу к новой услуге нужно исключить из списка привязанных к юзерам, т.к. она стала группой
deleteServiceFromUsers(service);
serviceForCopy = null;
QLog.l().logger().debug(
"Скопирована услуга \"" + newService + "\" в группу \"" + service.getName() + "\"");
}
}//GEN-LAST:event_miPasteServiceActionPerformed
private void miCutServiceActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miCutServiceActionPerformed
final QService service = (QService) treeServices.getLastSelectedPathComponent();
if (service != null && !service.isRoot()) {
serviceForCut = service;
serviceForCopy = null;
}
}//GEN-LAST:event_miCutServiceActionPerformed
private void popupServicesPopupMenuWillBecomeVisible(
javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_popupServicesPopupMenuWillBecomeVisible
miPasteService.setEnabled(serviceForCopy != null || serviceForCut != null);
}//GEN-LAST:event_popupServicesPopupMenuWillBecomeVisible
private void rbmClassicActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbmClassicActionPerformed
ServerProps.getInstance()
.saveOrUpdateProperty(IIndicatorBoard.SECTION, IIndicatorBoard.PARAMETER,
rbmClassic.isSelected() ? IIndicatorBoard.CLASSIC : IIndicatorBoard.HTML,
"Type of main tablo");
}//GEN-LAST:event_rbmClassicActionPerformed
private void btnReloadPropsActionPerformed(
java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReloadPropsActionPerformed
ServerProps.getInstance().reloadProperties();
sectionsList
.setModel(new DefaultComboBoxModel(ServerProps.getInstance().getSections().toArray()));
if (!ServerProps.getInstance().getSections().isEmpty()) {
sectionsList.setSelectedIndex(0);
}
}//GEN-LAST:event_btnReloadPropsActionPerformed
private void sendPager() {
if (forPager != null) {
final Thread t = new Thread(() -> {
forPager.sendData();
});
t.setDaemon(true);
t.start();
}
}
@Action
public void changeServicePriority() {
final QPlanService plan = (QPlanService) listUserService.getSelectedValue();
if (plan == null) {
return;
}
// тут надо фокус перекинуть, чтоб названия услуги изменилось с учетом приоритета.
listUserService.requestFocus();
listUserService.requestFocusInWindow();
final String name = (String) JOptionPane.showInputDialog(this,
getLocaleMessage("admin.select_priority.message"),
getLocaleMessage("admin.select_priority.title"),
JOptionPane.QUESTION_MESSAGE,
null,
Uses.get_COEFF_WORD().values().toArray(),
Uses.get_COEFF_WORD().values().toArray()[
Uses.get_COEFF_WORD().values().toArray().length > plan.getCoefficient() ? plan
.getCoefficient() : 1]);
//Если не выбрали, то выходим
if (name != null) {
for (int i = 0; i < Uses.get_COEFF_WORD().size(); i++) {
if (name.equals(Uses.get_COEFF_WORD().get(i))) {
plan.setCoefficient(i);
}
}
}
}
@Action
public void changeFlexiblePriorityAbility() {
final QPlanService plan = (QPlanService) listUserService.getSelectedValue();
if (plan == null) {
return;
}
// тут надо фокус перекинуть, чтоб названия услуги изменилось с учетом приоритета.
listUserService.requestFocus();
listUserService.requestFocusInWindow();
plan.setFlexible_coef(!plan.getFlexible_coef());
}
@Action
public void setUpdateServiceFire() {
final QPlanService plan = (QPlanService) listUserService.getSelectedValue();
if (plan == null) {
return;
}
final String res = NetCommander
.setServiseFire(new ServerNetProperty(), plan.getService().getId(),
plan.getUser().getId(),
plan.getCoefficient());
JOptionPane
.showMessageDialog(this, res, getLocaleMessage("admin.add_service_to_user.title"),
JOptionPane.INFORMATION_MESSAGE);
}
@Action
public void deleteUpdateServiceFire() {
final QPlanService plan = (QPlanService) listUserService.getSelectedValue();
if (plan == null) {
return;
}
final String res = NetCommander
.deleteServiseFire(new ServerNetProperty(), plan.getService().getId(),
plan.getUser().getId());
JOptionPane
.showMessageDialog(this, res, getLocaleMessage("admin.remove_service_to_user.title"),
JOptionPane.INFORMATION_MESSAGE);
}
@Action
public void getHelp() {
}
@Action
public void editService() {
final TreePath selectedPath = treeServices.getSelectionPath();
if (selectedPath != null) {
final QService service = (QService) selectedPath.getLastPathComponent();
FServiceChangeDialod
.changeService(this, true, service, (ComboBoxModel) listSchedule.getModel(),
(ComboBoxModel) listCalendar.getModel());
showServiceInfo(service);
}
}
@Action
public void getAbout() {
FAbout.showAbout(this, true, ServerProps.getInstance().getProps().getVersion());
}
@Action
public void standAdvance() {
final QService service = (QService) treeServices.getLastSelectedPathComponent();
if (service != null && service.isLeaf()) {
String inputData = null;
if (service.getInput_required()) {
inputData = (String) JOptionPane
.showInputDialog(this, service.getInput_caption(), "***", 3, null, null, "");
if (inputData == null) {
return;
}
}
String comments = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.comments"), "***", 3, null, null,
"");
if (inputData == null) {
inputData = "";
}
final QAdvanceCustomer res;
try {
res = FAdvanceCalendar
.showCalendar(this, true, new ServerNetProperty(), service, false, 0, -1,
inputData,
comments);
} catch (Exception ex) {
throw new ClientException(getLocaleMessage("admin.send_cmd_adv.err") + " " + ex);
}
if (res == null) {
return;
}
// печатаем результат
new Thread(() -> {
FWelcome.printTicketAdvance(res,
((QService) treeServices.getModel().getRoot())
.getTextToLocale(QService.Field.NAME));
}).start();
JOptionPane.showMessageDialog(this,
getLocaleMessage("admin.client_adv_dialog.msg_1") + " \"" + service.getName()
+ "\". "
+ getLocaleMessage("admin.client_adv_dialog.msg_2") + " \"" + res.getId()
+ "\".",
getLocaleMessage("admin.client_adv_dialog.title"), JOptionPane.INFORMATION_MESSAGE);
}
}
@Action
public void editMainBoard() throws IOException {
QLog.l().logger().info("Открыть редактор главного табло.");
final ServerNetProperty servProp = new ServerNetProperty();
try {
if (board == null) {
adr = servProp.getAddress().getHostAddress();
port = servProp.getPort();
board = MainBoard.getInstance().getRedactor();
board.setParams(servProp);
} else if (!servProp.getAddress().getHostAddress().equals(adr)
|| !servProp.getPort().equals(port)) {
board.setParams(servProp);
adr = servProp.getAddress().getHostAddress();
port = servProp.getPort();
}
} catch (Exception e) {
board = null;
ClientWarning.showWarning(getLocaleMessage("admin.open_editor.wern") + "\n" + e);
return;
}
// Отцентирируем
Uses.setLocation(board);
// Покажем
board.setVisible(true);
} //*****************************************Запрос в ручную*******************************************************************
@Action
public void sendMessage() {
FMessager.getMessager(this, ServerProps.getInstance().getProps().getClientPort(),
listUsers.getModel(), treeServices.getModel());
}
@Action
public void addRespItem() {
// Запросим название юзера и если оно уникально, то примем
String respName = getLocaleMessage("admin.add_resp_dialog.info");
boolean flag = true;
while (flag) {
respName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_resp_dialog.message"),
getLocaleMessage("admin.add_resp_dialog.title"), 3, null, null, respName);
if (respName == null) {
return;
}
if ("".equals(respName)) {
JOptionPane
.showConfirmDialog(this, getLocaleMessage("admin.add_resp_dialog.err1.message"),
getLocaleMessage("admin.add_resp_dialog.err1.title"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (respName.indexOf('\"') != -1) {
JOptionPane
.showConfirmDialog(this, getLocaleMessage("admin.add_resp_dialog.err2.message"),
getLocaleMessage("admin.add_resp_dialog.err2.title"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (respName.length() > 100) {
JOptionPane
.showConfirmDialog(this, getLocaleMessage("admin.add_resp_dialog.err3.message"),
getLocaleMessage("admin.add_resp_dialog.err3.title"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
QLog.l().logger().debug("Добавляем отзыв \"" + respName + "\"");
final QRespItem item = new QRespItem();
item.setName(respName);
item.setInput_required(false);
item.setInput_caption("<html>Add your comment:");
item.setHTMLText(
"<html><b><p align=center><span style='font-size:20.0pt;color:green'>" + respName
+ "</span></b>");
final QRespItem parentItem = (QRespItem) treeResp.getLastSelectedPathComponent();
((QResponseTree) treeResp.getModel())
.insertNodeInto(item, parentItem, parentItem.getChildCount());
final TreeNode[] nodes = ((QResponseTree) treeResp.getModel()).getPathToRoot(item);
final TreePath path = new TreePath(nodes);
treeResp.scrollPathToVisible(path);
treeResp.setSelectionPath(path);
}
@Action
public void deleteRespItem() {
final QRespItem item = (QRespItem) treeResp.getLastSelectedPathComponent();
if (item != null && !item.isRoot()) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.resp_delete.message") + " \"" + item.getName() + "\"?",
getLocaleMessage("admin.resp_delete.title"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
QLog.l().logger().debug("Удаляем отзыв \"" + item.getName() + "\"");
// Удалим сам узел
final int del = item.getParent().getIndex(item);
final int col = item.getParent().getChildCount();
QResponseTree.getInstance().removeNodeFromParent(item);
// Выделение в узла в дереве
if (col == 1) {
treeInfo.setSelectionPath(
new TreePath(
((QInfoTree) treeInfo.getModel()).getPathToRoot(item.getParent())));
} else if (col == del + 1) {
treeInfo.setSelectionPath(new TreePath(
((QInfoTree) treeInfo.getModel())
.getPathToRoot(item.getParent().getChildAt(del - 1))));
} else if (col > del + 1) {
treeInfo.setSelectionPath(new TreePath(
((QInfoTree) treeInfo.getModel())
.getPathToRoot(item.getParent().getChildAt(del))));
}
QLog.l().logger().debug(
"Удален отзыв \"" + item.getName() + "\" из группы \"" + item.getParent().getName()
+ "\"");
}
}
@Action
public void addSchedule() {
// Запросим название плана и если оно уникально, то примем
String scheduleName = getLocaleMessage("admin.add_work_plan_dialog.info");
boolean flag = true;
while (flag) {
scheduleName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_work_plan_dialog.message"),
getLocaleMessage("admin.add_work_plan_dialog.title"), 3, null, null,
scheduleName);
if (scheduleName == null) {
return;
}
if ("".equals(scheduleName)) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_work_plan_dialog.err1.message"),
getLocaleMessage("admin.add_work_plan_dialog.err1.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (scheduleName.indexOf('\"') != -1) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_work_plan_dialog.err2.message"),
getLocaleMessage("admin.add_work_plan_dialog.err2.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (scheduleName.length() > 150) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_work_plan_dialog.err3.message"),
getLocaleMessage("admin.add_work_plan_dialog.err3.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
QLog.l().logger().debug("Добавляем отзыв \"" + scheduleName + "\"");
final QSchedule item = new QSchedule();
item.setName(scheduleName);
item.setType(0);
QScheduleList.getInstance().addElement(item);
listSchedule.setSelectedValue(item, true);
}
@Action
public void deleteSchedule() {
if (listSchedule.getSelectedIndex() != -1) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.work_plan_delete.message") + " \""
+ ((QSchedule) listSchedule
.getSelectedValue()).getName() + "\"?",
getLocaleMessage("admin.work_plan_delete.title"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
QLog.l().logger().debug(
"Удаляем план \"" + ((QSchedule) listSchedule.getSelectedValue()).getName() + "\"");
final int del = listSchedule.getSelectedIndex();
final QScheduleList m = (QScheduleList) listSchedule.getModel();
final int col = m.getSize();
final QSchedule item = (QSchedule) listSchedule.getSelectedValue();
QServiceTree.getInstance().getNodes().stream()
.filter((service) -> (item.equals(service.getSchedule()))).forEach((service) -> {
service.setSchedule(null);
});
// Удалим это расписание как специальное у календарей.
QCalendarList.getInstance().getItems().forEach(calc -> {
final LinkedList<QSpecSchedule> fordel = new LinkedList<>();
calc.getSpecSchedules().forEach(sps -> {
if (sps.getSchedule().getId().equals(item.getId())) {
fordel.add(sps);
}
});
calc.getSpecSchedules().removeAll(fordel);
});
calendarListChange();
QScheduleList.getInstance().removeElement(item);
if (col != 1) {
if (col == del + 1) {
listSchedule.setSelectedValue(m.getElementAt(del - 1), true);
} else if (col > del + 1) {
listSchedule.setSelectedValue(m.getElementAt(del), true);
}
}
}
}
@Action
public void editSchedule() {
final QSchedule item = (QSchedule) listSchedule.getSelectedValue();
if (item != null) {
FScheduleChangeDialod.changeSchedule(this, true, item);
scheduleListChange();
}
}
@Action
public void addResult() {
String resultText = "";
boolean flag = true;
while (flag) {
resultText = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_result_dialog.message"),
getLocaleMessage("admin.add_result_dialog.title"), 3, null, null, resultText);
if (resultText == null) {
return;
}
if ("".equals(resultText)) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_result_dialog.err1.message"),
getLocaleMessage("admin.add_result_dialog.err1.title"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (resultText.indexOf('\"') != -1) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_result_dialog.err2.message"),
getLocaleMessage("admin.add_result_dialog.err2.title"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else if (resultText.length() > 150) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_result_dialog.err3.message"),
getLocaleMessage("admin.add_result_dialog.err3.title"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
QLog.l().logger().debug("Добавляем результат \"" + resultText + "\"");
final QResult item = new QResult();
item.setName(resultText);
QResultList.getInstance().addElement(item);
listResults.setSelectedValue(item, true);
}
@Action
public void deleteResult() {
if (listResults.getSelectedIndex() != -1) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.result_delete.message") + " \"" + ((QResult) listResults
.getSelectedValue()).getName() + "\"?",
getLocaleMessage("admin.result_delete.title"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
QLog.l().logger().debug(
"Удаляем результат \"" + ((QResult) listResults.getSelectedValue()).getName()
+ "\"");
final int del = listResults.getSelectedIndex();
final QResultList m = (QResultList) listResults.getModel();
final int col = m.getSize();
final QResult item = (QResult) listResults.getSelectedValue();
QResultList.getInstance().removeElement(item);
if (col != 1) {
if (col == del + 1) {
listResults.setSelectedValue(m.getElementAt(del - 1), true);
} else if (col > del + 1) {
listResults.setSelectedValue(m.getElementAt(del), true);
}
}
}
}
@Action
public void addCalendar() {
// Запросим название календаря и если оно уникально, то примем
String calendarName = getLocaleMessage("admin.add_calendar_dialog.info");
boolean flag = true;
while (flag) {
calendarName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_calendar_dialog.message"),
getLocaleMessage("admin.add_calendar_dialog.title"), 3, null, null,
calendarName);
if (calendarName == null) {
return;
}
if ("".equals(calendarName)) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_calendar_dialog.err1.message"),
getLocaleMessage("admin.add_calendar_dialog.err1.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (calendarName.indexOf('\"') != -1) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_calendar_dialog.err2.message"),
getLocaleMessage("admin.add_calendar_dialog.err2.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (calendarName.length() > 150) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_calendar_dialog.err3.message"),
getLocaleMessage("admin.add_calendar_dialog.err3.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
QLog.l().logger().debug("Добавляем календарь \"" + calendarName + "\"");
final QCalendar item = new QCalendar();
item.setName(calendarName);
QCalendarList.getInstance().addElement(item);
listCalendar.setSelectedValue(item, true);
}
@Action
public void deleteCalendar() {
if (listCalendar.getSelectedIndex() != -1
&& (((QCalendar) listCalendar.getSelectedValue()).getId() == null
|| ((QCalendar) listCalendar.getSelectedValue()).getId() != 1)) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.calendar_delete.message") + " \""
+ ((QCalendar) listCalendar
.getSelectedValue()).getName() + "\"?",
getLocaleMessage("admin.calendar_delete.title"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
QLog.l().logger().debug(
"Удаляем календарь \"" + ((QCalendar) listCalendar.getSelectedValue()).getName()
+ "\"");
final int del = listCalendar.getSelectedIndex();
final QCalendarList m = (QCalendarList) listCalendar.getModel();
final int col = m.getSize();
final QCalendar item = (QCalendar) listCalendar.getSelectedValue();
QServiceTree.getInstance().getNodes().stream()
.filter((service) -> (item.equals(service.getCalendar()))).forEach((service) -> {
service.setCalendar(null);
});
QCalendarList.getInstance().removeElement(item);
if (col != 1) {
if (col == del + 1) {
listCalendar.setSelectedValue(m.getElementAt(del - 1), true);
} else if (col > del + 1) {
listCalendar.setSelectedValue(m.getElementAt(del), true);
}
}
}
}
@Action
public void dropCalendarSelection() {
final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel();
model.dropCalendar((Integer) (spinCalendarYear.getValue()));
}
@Action
public void checkSaturday() {
final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel();
model.checkSaturday((Integer) (spinCalendarYear.getValue()));
}
@Action
public void checkSundays() {
final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel();
model.checkSunday((Integer) (spinCalendarYear.getValue()));
}
@Action
public void saveCalendar() {
final CalendarTableModel model = (CalendarTableModel) tableCalendar.getModel();
model.save();
JOptionPane.showMessageDialog(this, getLocaleMessage("admin.action.save_calensar.message"),
getLocaleMessage("admin.action.save_calensar.title"), JOptionPane.INFORMATION_MESSAGE);
}
@Action
public void changePriority() {
final String num = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.action.change_priority.num.message"),
getLocaleMessage("admin.action.change_priority.num.title"), 3, null, null, "");
if (num != null) {
final String name = (String) JOptionPane.showInputDialog(this,
getLocaleMessage("admin.action.change_priority.get.message"),
getLocaleMessage("admin.action.change_priority.get.title"),
JOptionPane.QUESTION_MESSAGE,
null,
Uses.get_PRIORITYS_WORD().values().toArray(),
Uses.get_PRIORITYS_WORD().values().toArray()[1]);
//Если не выбрали, то выходим
if (name != null) {
for (int i = 0; i < Uses.get_PRIORITYS_WORD().size(); i++) {
if (name.equals(Uses.get_PRIORITYS_WORD().get(i))) {
JOptionPane.showMessageDialog(this,
NetCommander.setCustomerPriority(new ServerNetProperty(), i, num),
getLocaleMessage("admin.action.change_priority.title"),
JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
}
@Action
public void checkClient() {
final String num = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.action.change_priority.num.message"),
getLocaleMessage("admin.action.change_priority.num.title"), 3, null, null, "");
if (num != null) {
JOptionPane
.showMessageDialog(this,
NetCommander.checkCustomerNumber(new ServerNetProperty(), num),
getLocaleMessage("admin.action.change_priority.num.title"),
JOptionPane.INFORMATION_MESSAGE);
}
}
@Action
public void setCurrentLang() {
for (int i = 0; i < menuLangs.getItemCount(); i++) {
if (((JRadioButtonMenuItem) menuLangs.getItem(i)).isSelected()) {
Locales.getInstance()
.setLangCurrent(((JRadioButtonMenuItem) menuLangs.getItem(i)).getText());
}
}
}
@Action
public void addBreakToList() {
// Запросим название плана и если оно уникально, то примем
String breaksName = getLocaleMessage("admin.add_breaks_dialog.info");
boolean flag = true;
while (flag) {
breaksName = (String) JOptionPane
.showInputDialog(this, getLocaleMessage("admin.add_breaks_dialog.message"),
getLocaleMessage("admin.add_breaks_dialog.title"), 3, null, null, breaksName);
if (breaksName == null) {
return;
}
for (QBreaks qb : QBreaksList.getInstance().getItems()) {
if (qb.getName().equalsIgnoreCase(breaksName)) {
JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.enter_sute_mark.err2.title"),
getLocaleMessage("admin.enter_sute_mark.err1.title"),
JOptionPane.DEFAULT_OPTION,
JOptionPane.ERROR_MESSAGE);
return;
}
}
if ("".equals(breaksName)) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_breaks_dialog.err1.message"),
getLocaleMessage("admin.add_work_plan_dialog.err1.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (breaksName.indexOf('\"') != -1) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_breaks_dialog.err2.message"),
getLocaleMessage("admin.add_work_plan_dialog.err2.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else if (breaksName.length() > 150) {
JOptionPane
.showConfirmDialog(this,
getLocaleMessage("admin.add_breaks_dialog.err3.message"),
getLocaleMessage("admin.add_work_plan_dialog.err3.title"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
} else {
flag = false;
}
}
QLog.l().logger().debug("Добавляем перерывы \"" + breaksName + "\"");
final QBreaks item = new QBreaks();
item.setName(breaksName);
QBreaksList.getInstance().addElement(item);
listBreaks.setSelectedValue(item, true);
}
@Action
public void deleteBreakFromList() {
if (listBreaks.getSelectedIndex() != -1) {
if (JOptionPane.showConfirmDialog(this,
getLocaleMessage("admin.breaks_delete.message") + " \"" + ((QBreaks) listBreaks
.getSelectedValue()).getName() + "\"?",
getLocaleMessage("admin.breaks_delete.title"),
JOptionPane.YES_NO_OPTION) == 1) {
return;
}
QLog.l().logger().debug(
"Удаляем перерывы \"" + ((QBreaks) listBreaks.getSelectedValue()).getName() + "\"");
final int del = listBreaks.getSelectedIndex();
final QBreaksList m = (QBreaksList) listBreaks.getModel();
final int col = m.getSize();
final QBreaks item = (QBreaks) listBreaks.getSelectedValue();
// Уберем удаленные перерывы у расписаний
boolean f = false;
for (QSchedule schedule : QScheduleList.getInstance().getItems()) {
if (item.equals(schedule.getBreaks_1())) {
schedule.setBreaks_1(null);
f = true;
}
if (item.equals(schedule.getBreaks_2())) {
schedule.setBreaks_2(null);
f = true;
}
if (item.equals(schedule.getBreaks_3())) {
schedule.setBreaks_3(null);
f = true;
}
if (item.equals(schedule.getBreaks_4())) {
schedule.setBreaks_4(null);
f = true;
}
if (item.equals(schedule.getBreaks_5())) {
schedule.setBreaks_5(null);
f = true;
}
if (item.equals(schedule.getBreaks_6())) {
schedule.setBreaks_6(null);
f = true;
}
if (item.equals(schedule.getBreaks_7())) {
schedule.setBreaks_7(null);
f = true;
}
}
if (f) {
scheduleListChange();
}
// Подотрать все прикрепленые интервалы не нужно. Они должны сами подтереться по констрейнту.
// подотрем сам список
QBreaksList.getInstance().removeElement(item);
if (col != 1) {
if (col == del + 1) {
listBreaks.setSelectedValue(m.getElementAt(del - 1), true);
} else if (col > del + 1) {
listBreaks.setSelectedValue(m.getElementAt(del), true);
}
}
}
}
@Action
public void editBreak() {
final QBreaks item = (QBreaks) listBreaks.getSelectedValue();
if (item != null) {
FBreaksChangeDialog.changeSchedule(this, true, item);
scheduleListChange();
}
}
@Action
public void editLangs() {
final TreePath selectedPath = treeServices.getSelectionPath();
if (selectedPath != null) {
final QService service = (QService) selectedPath.getLastPathComponent();
FServiceLangList.changeServiceLangList(this, true, service);
showServiceInfo(service);
}
}
@Action
public void setDisableService() {
final TreePath selectedPath = treeServices.getSelectionPath();
if (selectedPath != null) {
final QService service = (QService) selectedPath.getLastPathComponent();
final String name = (String) JOptionPane.showInputDialog(this,
getLocaleMessage("admin.select_ability.message") + " \"" + service.getName() + "\"",
getLocaleMessage("admin.select_ability.title"),
JOptionPane.QUESTION_MESSAGE,
null,
new String[]{getLocaleMessage("admin.service_ability.yes"),
getLocaleMessage("admin.service_ability.no")},
null);
//Если не выбрали, то выходим
if (name != null) {
if (name.equalsIgnoreCase(getLocaleMessage("admin.service_ability.yes"))) {
NetCommander
.changeTempAvailableService(new ServerNetProperty(), service.getId(), "");
} else {
final String mess = (String) JOptionPane.showInputDialog(this,
getLocaleMessage("admin.ability.enter_reason"),
getLocaleMessage("admin.select_ability.title"),
JOptionPane.QUESTION_MESSAGE);
if (mess != null) {
NetCommander
.changeTempAvailableService(new ServerNetProperty(), service.getId(),
mess);
} else {
return;
}
}
JOptionPane.showMessageDialog(this,
getLocaleMessage("admin.select_ability.message") + " " + service.getName()
+ " \""
+ name + "\"",
getLocaleMessage("admin.select_ability.title"),
JOptionPane.INFORMATION_MESSAGE);
}
}
}
public static class Answer {
int tabbi = 0;
@Expose
@SerializedName("curr_version")
private String currVersion;
@Expose
@SerializedName("urlfun")
private String urlfun;
@Expose
@SerializedName("data")
private List<PagerData> data;
private boolean already = false;
private PagerData pd;
public Answer() {
}
public Answer(List<PagerData> data, String currVersion) {
this.data = data;
this.currVersion = currVersion;
}
public String getCurrVersion() {
return currVersion;
}
public void setCurrVersion(String currVersion) {
this.currVersion = currVersion;
}
public String getUrlfun() {
return urlfun;
}
public void setUrlfun(String urlfun) {
this.urlfun = urlfun;
}
public String getUrlFunRnd() {
if (urlfun == null || urlfun.isEmpty()) {
return null;
}
String[] ss = urlfun.split("#");
return ss[new Random().nextInt(ss.length)];
}
public List<PagerData> getData() {
return data;
}
public void setData(List<PagerData> data) {
this.data = data;
}
public void start() {
if (!already) {
for (int i = 0; i < 2000; i++) {
if (form == null || form.panelPager == null) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
} else {
showData(false);
}
}
}
}
private void showData(boolean forse) {
if (!already || forse) {
already = true;
final int d = (int) (Math.random() * data.size());
pd = null;
form.rbPager1.setSelected(false);
form.rbPager2.setSelected(false);
form.rbPager3.setSelected(false);
pd = data.get(d);
form.labelPager.setText(pd.textData);
final Matcher m = P.matcher(pd.textData);
form.pagerUrl = null;
while (m.find()) {
form.pagerUrl = pd.textData.substring(m.start(0), m.end(0));
}
form.labelPagerCaptionCombo.setText(pd.quizCaption);
form.labelPagerCaptionEdit.setText(pd.quizCaption);
switch (pd.dataType) {
case 0:
form.panelEditPager.setVisible(false);
form.panelPagerCombo.setVisible(false);
form.panelPagerRadio.setVisible(false);
break;
case 1:
form.panelEditPager.setVisible(false);
form.panelPagerCombo
.setVisible(!pd.checked && pd.pagerQuizItemsList.size() > 3);
form.panelPagerRadio
.setVisible(!pd.checked && pd.pagerQuizItemsList.size() < 4);
if (pd.pagerQuizItemsList.size() > 3) {
final Object[] ar = ArrayUtils
.addAll(new PagerQuizItems[1], pd.pagerQuizItemsList.toArray());
form.comboBoxPager.setModel(new DefaultComboBoxModel(ar));
} else {
form.rbPager1.setText(pd.pagerQuizItemsList.get(0).itemText);
form.rbPager2.setText(pd.pagerQuizItemsList.get(1).itemText);
if (pd.pagerQuizItemsList.size() == 2) {
form.rbPager3.setVisible(false);
} else {
form.rbPager3.setVisible(true);
form.rbPager3.setText(pd.pagerQuizItemsList.get(2).itemText);
}
}
break;
case 2:
form.panelEditPager.setVisible(!pd.checked);
form.panelPagerCombo.setVisible(false);
form.panelPagerRadio.setVisible(false);
break;
default:
throw new AssertionError();
}
form.panelPager.setVisible(true);
final String uf = getUrlFunRnd();
if (uf != null && !uf.isEmpty()) {
if (tabbi == 0 && Math.random() < 0.1) {
try {
ImageIcon ii = new ImageIcon(new URL(uf));
if (ii.getIconHeight() < 1 || ii.getIconWidth() < 1) {
form.tabbedPaneMain.remove(form.tabHide);
} else {
form.labHidePic.setIcon(ii);
form.tabbedPaneMain
.addTab(getLocaleMessage("tabHideTitle"), form.tabHide);
}
} catch (MalformedURLException ex) {
form.tabbedPaneMain.remove(form.tabHide);
}
}
tabbi = 2;
} else {
form.tabbedPaneMain.remove(form.tabHide);
}
if (!FAbout.VERSION_.equalsIgnoreCase(currVersion) && !forse) {
form.setTitle(
form.getTitle() + " " + getLocaleMessage("qsys.new_ver") + " "
+ currVersion + " "
+ getLocaleMessage("qsys.available"));
}
}
}
public void sendData() {
if (pd != null) {
String paraqms = "&dataid=" + pd.id;
switch (pd.dataType) {
case 0:
break;
case 1:
if (pd.pagerQuizItemsList.size() > 3) {
if (form.comboBoxPager.getSelectedItem() == null) {
return;
}
paraqms = paraqms + "&quizid=" + ((PagerQuizItems) (form.comboBoxPager
.getSelectedItem())).id;
} else {
String sel = "";
if (form.rbPager1.isSelected()) {
sel = form.rbPager1.getText();
} else if (form.rbPager2.isSelected()) {
sel = form.rbPager2.getText();
} else if (form.rbPager3.isSelected()) {
sel = form.rbPager3.getText();
}
for (PagerQuizItems q : pd.pagerQuizItemsList) {
if (q.itemText.equals(sel)) {
paraqms = paraqms + "&quizid=" + q.id;
break;
}
}
}
break;
case 2:
try {
paraqms =
paraqms + "&inputdata=" + new BCodec().encode(URLEncoder.encode(
form.textFieldPager.getText().length() > 545
? form.textFieldPager.getText()
.substring(0, 545) : form.textFieldPager.getText(), "utf8"),
"utf8");
} catch (EncoderException | UnsupportedEncodingException ex) {
}
break;
default:
throw new AssertionError();
}
try {
//http://localhost:8080/qskyapi/setpagerdata?qsysver=1.3.1&dataid=3&inputdata=Hello%20world!
//http://localhost:8080/qskyapi/setpagerdata?qsysver=1.3.1&dataid=2&quizid=3
final URL url = new URL(
PAGER_URL + "/qskyapi/setpagerdata?qsysver=" + FAbout.VERSION_
+ "&qplugins="
+ getMac() + "-" + getStat() + paraqms);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "Java bot");
conn.connect();
final int code = conn.getResponseCode();
if (code != 200) {
System.err.println("Strange! Pager not enabled. Returned code not 200.");
} else {
pd.checked = true;
}
conn.disconnect();
} catch (Exception e) {
System.err.println("Pager not enabled.");
form.bgPager.clearSelection();
return;
}
showData(true);
form.bgPager.clearSelection();
}
}
}
public static class PagerData {
public boolean checked = false;
@Expose
@SerializedName("id")
private Long id;
@Expose
@SerializedName("type")
private int dataType;
@Expose
@SerializedName("text")
private String textData;
@Expose
@SerializedName("qcap")
private String quizCaption;
@Expose
@SerializedName("quis_items")
private List<PagerQuizItems> pagerQuizItemsList;
public PagerData() {
}
}
public static class PagerQuizItems {
@Expose
@SerializedName("id")
private Long id;
@Expose
@SerializedName("text")
private String itemText;
public PagerQuizItems() {
}
@Override
public String toString() {
return itemText;
}
}
private class StartTimer extends Timer {
public StartTimer(int delay, ActionListener listener) {
super(delay, listener);
}
public void startTimer() {
if (checkBoxServerAuto.isSelected()) {
checkServer();
}
if (checkBoxClientAuto.isSelected()) {
checkWelcome(null);
}
start();
}
}
/**
* Собыите автосканирования сервера и пункта регистрации на таймер.
*/
private class TimerPrinter implements ActionListener {
/**
* Обеспечение автоматизации запроса.
*/
@Override
public void actionPerformed(ActionEvent e) {
if (checkBoxServerAuto.isSelected()) {
checkBoxServerAuto.setSelected(checkServer());
}
if (checkBoxClientAuto.isSelected()) {
checkBoxClientAuto.setSelected(checkWelcome(null));
}
}
}
/**
* Сохранять спинедиты сетевых настроек
*/
private class ChangeNet implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
saveNet();
}
}
/**
* Сохранять настройки спинедита мониторинга
*/
private class ChangeSettings implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
saveSettings();
}
}
/**
* Сохранять настройки спинедита юзера
*/
private class ChangeUser implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
saveUser();
}
}
private class ServerNetProperty implements INetProperty {
@Override
public Integer getPort() {
return (Integer) spinnerServerPort.getValue();
}
@Override
public InetAddress getAddress() {
InetAddress adr = null;
try {
adr = InetAddress.getByName(textFieldServerAddr.getText());
} catch (UnknownHostException ex) {
throw new ClientException("Error! " + ex);
}
return adr;
}
}
// End of variables declaration//GEN-END:variables
}
| mark-walle/sbc-qsystem | QSystem/src/ru/apertum/qsystem/client/forms/FAdmin.java | Java | gpl-3.0 | 433,971 |
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera ([email protected])
L. Sánchez ([email protected])
J. Alcalá-Fdez ([email protected])
S. García ([email protected])
A. Fernández ([email protected])
J. Luengo ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
**********************************************************************/
package keel.Algorithms.RE_SL_Postprocess.Post_G_TS_LatAmp_FRBSs;
import java.io.*;
import java.util.*;
/**
* The class that reads the file of the rule base
* @author Diana Arquillos
*
*/
public class LeerWm {
private String rutaFichero;
public int numReglas;
public double []base;
public double exit;
/**
* It stores the name of the file
* @param ruta it contains the name of the file
*/
public LeerWm(String ruta) {
this.rutaFichero = ruta;
}
/**
* It reads the file
* @param n_variables it contains the number of variables
*/
public void leer(int n_variables){
File fichero = new File(this.rutaFichero);
String linea = null;
StringTokenizer tokens = null;
try
{
BufferedReader reader = new BufferedReader(new FileReader(fichero));
linea = reader.readLine();
tokens = new StringTokenizer(linea,":");
tokens.nextElement();
numReglas = (int)Double.parseDouble(tokens.nextElement().toString());
base = new double [numReglas*(3*n_variables)];
int i=0;
int j=0;
double aux;
int contador=0;
linea = reader.readLine();
while( j<((numReglas*n_variables))){
linea = reader.readLine();
tokens = new StringTokenizer(linea," ");
aux = Double.parseDouble(tokens.nextElement().toString());
base[i]=aux;
i++;
aux = Double.parseDouble(tokens.nextElement().toString());
base[i]=aux;
aux = Double.parseDouble(tokens.nextElement().toString());
i++;
base[i]=aux;
i++;
j++;
contador++;
if(contador==n_variables){
contador=0;
linea= reader.readLine();
}
}
exit = -1;
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| TheMurderer/keel | src/keel/Algorithms/RE_SL_Postprocess/Post_G_TS_LatAmp_FRBSs/LeerWm.java | Java | gpl-3.0 | 3,035 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.